I'm trying to write a python program that asks the user to enter an integer or "q" (case-insensitive) to quit that will then take any integers and print the sum of the last 5.
I have created a holding list and some counter and test variables to help with this, but I can't seem to get it to work the way I'd like. I keep getting various errors.
The code I currently have is
my_list = []
quit = 0
i = 0
while quit == 0:
value = eval(input("Please enter an integer or the letter 'q' to quit: ")
if value.isdigit()
my_list.append(value)
i = 1
print(sum(my_list[-1] my_list[-2] my_list[-3] my_list[-4] my_list[-5]))
if value == q:
quit = 1
elif
print("Your input is not an integer, please try again")
This is returning and error of invalid syntax for the my_list.append(value)
line.
What I would like this to do is allow for me to enter any integer, have the loop test if it is an integer, and if so, add it to the holding list and print out the sum of the most recent 5 entries in the list (or all if less than 5). If I enter "q" or "Q" I want the loop to break and the program to end.
CodePudding user response:
There are many errors in your code.
Fixed code:
while quit == False:
value = input("Please enter an integer or the letter 'q' to quit: ")
if value.isdigit():
my_list.append(int(value))
i = 1
print(sum(my_list[-5:]))
elif value == 'q' or value == 'Q':
quit = True
else:
print("Your input is not an integer, please try again")
Notes:
Do not use
eval
, it can be dangerous. As you check if the value contains digit, you can safely useint
to cast the value.If you want to quit with 'q' or 'Q', you have to check both.
You have to slice your list to avoid exception if your list does not contain at least 5 elements.
CodePudding user response:
You can try if this: *It is shorter and more readable
my_list = []
while True:
x = input("Please enter an integer or the letter 'q' to quit: ")
if x == 'q':
break
else:
my_list.append(int(x))
output_sum = sum(my_list[-5:])
print(output_sum)
Input
1
2
3
4
5
q
Output
15
CodePudding user response:
You should check that the input contains at least 5 digits. You can do this by first checking the length of the input string then calling isnumeric() on the string.
Then you just need to slice the string (last 5 characters) and sum the individual values as follows:
while (n := input("Please enter an integer of at least 5 digits or 'q' to quit: ").lower()) != 'q':
if len(n) > 4 and n.isnumeric():
print(sum(int(v) for v in n[-5:]))
...or if you want to input numerous values then:
numbers = []
while (n := input("Please enter a number or 'q' to quit: ").lower()) != 'q':
if n.isnumeric():
numbers.append(n)
else:
print(f'{n} is not numeric')
if len(numbers) < 5:
print(f'You only entered {len(numbers)} numbers')
else:
print(sum(int(v) for v in numbers[-5:]))