Reputation: 23
My program needs to read a set of integers from the user and store them in a list. It should read numbers from the user until the user enters 0 to quit. Then it needs to add them up and display the sum to the user. If the user types anything that is not an integer, it needs to display an error to the user.
I'm having a hard time figuring out how to make a list that the user can infinitely input numbers into.
From what I have tried to do and looked up, I've only been able to make a defined list and make a program that takes in a specific amount of inputs.
This is what I have. Obviously, it doesn't work, but it shows what I'm going for.
n, ns = 0, 0 # count of numbers, sum of numbers
print("Enter numbers or any other 0 to quit.")
while(1):
grades = input("enter = ")
if (int):
ns += int
n += 1
else:
if (0):
print(ns)
break
Upvotes: 1
Views: 236
Reputation: 380
Python 3
lists=[]
while(True):
i=int(input("Enter The Input"))
if i==0:
break
else:
lists.append(i)
print(lists)
Upvotes: 0
Reputation: 140
Use this:
list_of_nums = []
loop = True
while loop == True:
try: num = int(input("Enter Integer: "))
except ValueError: num = "invalid"
if num == "invalid": print("\nPlease Print A Valid Integer!\n");
elif num != 0: list_of_nums.append(num)
else: loop = False
print("\nSum of Inputed Integers: " + str(sum(list_of_nums)) + "\n")
Upvotes: 1