I need some help creating a python program that does the following:
Example Execution:
Enter a number: 5
Enter another number, or enter to quit: 8
Enter another number, or enter to quit: -2
Enter another number, or enter to quit: 1
Enter another number, or enter to quit:
Numbers entered: 4
Sum: 12
Max: 8
Min: -2
I currently have this and I am stuck:
user_input = " "
while user_input != "":
user_input = input("Enter a number, or nothing to quit: ")
if user_input != "":
user_input = int(user_input)
user_input = 1
print(user_input)
Help would be much appreciated!
CodePudding user response:
You can first collect the inputs in a list, and then print the results, where f-strings are handy:
lst = []
while (user_input := input("Enter a number (blank to quit): ").strip()):
lst.append(int(user_input))
print(f"You have entered {len(lst)} numbers:", *lst)
print(f"Sum: {sum(lst)}")
print(f"Max: {max(lst)}")
print(f"Min: {min(lst)}")
If you are not familiar with walrus operator :=
, then
lst = []
user_input = input("Enter a number: ").strip() # ask for input
while user_input != '': # check whether it is empty (!= '' can be omitted)
lst.append(int(user_input))
user_input = input("Enter a number (blank to quit): ").strip() # ask for input
Example:
Enter a number (blank to quit): 1
Enter a number (blank to quit): 2
Enter a number (blank to quit): 3
Enter a number (blank to quit):
You have entered 3 numbers: 1 2 3
Sum: 6
Max: 3
Min: 1
CodePudding user response:
Detailed version:
user_inputs_values = []
user_inputs_count = 0 # (a)
user_input = input("Enter a number: ")
user_inputs_values.append(int(user_input))
user_inputs_count = 1 # (a)
while True:
user_input = input("Enter another number, or enter to quit: ")
if not user_input:
break
user_inputs_values.append(int(user_input))
user_inputs_count = 1 # (a)
print(f"Numbers entered: {user_inputs_count}") # (b)
print(f"Sum: {sum(user_inputs_values)}")
print(f"Max: {max(user_inputs_values)}")
print(f"Min: {min(user_inputs_values)}")
Note that the first input message is different than the following ones.
Note using a count of entries is also possible, taas the count is equal to len(user_inputs_values). So you can remove lines marked (a) and replace line marked (b) with:
print(f"Numbers entered: {len(user_inputs_values)}")