1

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
4
  • 7
    You need to provide a base code. At least you need to try :) Commented Mar 11, 2019 at 3:06
  • 1
    Welcome to SO, please read: stackoverflow.com/help/how-to-ask and stackoverflow.com/help/mcve if you want to get help on this platform. Commented Mar 11, 2019 at 3:06
  • 6
    I got a solution, but i am hesitant to answer. Commented Mar 11, 2019 at 3:07
  • 1
    Can you show your code please? Commented Mar 11, 2019 at 3:08

2 Answers 2

1

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")
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, This makes a lot more sense to me now. I've never knew about try or except so this helps a ton. Also they way you've looped the code makes much more sense. But i'm still confused on why list_of_sums is equal to empty brackets. Would making it equal to zero work too? And could you make the value have a starting number if you wanted? Thanks again.
That's great - list_of_sums is [] because if you want to append a value to it each time, you have to tell python that it is initialized as a list first - so setting it to zero would not work. And you could definitely initialize it with a starting number - ex. [5]
So saying list_of_sums = () wouldn't work? or would it make it something else?
No that wouldn't work, because that would tell python that you are initializing it as a tuple.
0

Python 3

lists=[]
while(True):
    i=int(input("Enter The Input"))
    if i==0:
        break
    else:
        lists.append(i)
print(lists)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.