Feipi Wen Feipi Wen - 4 years ago 126
Python Question

Python : How to prompt user to enter numbers to an empty list?

So, I know how to calculate a

list: list = [],
but I want to ask the user to enter random numbers; however, if the user enters 0, then it quits, which means the

list is : [number1, number2, number3, ..., 0].


I tried to write: l
ist = input ("Please enter number: ", []),
but it seems it's not right.

Answer Source

You'll want to use a while loop to keep the program going until the user enters a 0.

# Don't call this 'list', it's a reserved keyword in python
lst = []

user_input = int(input("Please enter a number: "))

while user_input != 0:
  lst.append(user_input)

  user_input = int(input("Please enter a number: "))

print("You said: " + lst)

Alternatively, if you don't want to duplicate your input line, you can use a break instead:

lst = []

while True:
  user_input = int(input("Please enter a number: "))

  if user_input == 0:
    break

  lst.append(user_input)

print("You said: " + lst)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download