我如何编写一个程序,询问一个数字,直到零被引入?

时间:2012-10-16 14:59:25

标签: python list element

如何编写一个程序来创建一个整数列表,要求用户输入一个新的数字,直到引入零。

for example
    Enter elements for a list, one at a time. Enter 0 to stop.
    element =  9 
    element = 3 
    element = 1
    element = -7
    element = 2
    element = 0
    Finished getting user input.
    The list is:  [9, 3, 1, -7, 2]

这就是我所拥有的。

listA = [9, 3, 1, -7, 2]
while True:
    input = int("some number: ")


    if input == 0
        break
    print("Finished getting user input")
    print("the list is: [9,3,1,-7,2]")
    else:
        listA.append(int(input))

2 个答案:

答案 0 :(得分:4)

mylist = []
while True:
    try:
        input = int(raw_input("add a number: "))
    except ValueError:
        print "please only input integers, input 0 to quit"
        continue
    if input == 0
        break
    else: 
        mylist.append(int(input))

在此循环运行之后,您有一个列表mylist,其中包含用户在输入0之前输入的所有整数。

答案 1 :(得分:0)

要查看您的代码:

File "temp.py", line 6
    if input == 0
            ^

SyntaxError:语法无效

如果语句最后需要冒号。修复此问题,然后重试您的程序。

试试这个:

if input == 0:

另外,如果你对问题得到了很好的答案,你应该检查一下,以便最能回答你的人获得积分