def main():
x = int(input("Enter a number (0 to stop) "))
y = x
l = []
while x != 0:
x = int(input("Enter a number (0 to stop) "))
l = [x]
print(l[x])
main()
我以为我应该在循环之外初始化列表,并且在循环中我认为它将接受任何输入的X并将其存储到以后打印出来,但这不是案件。有什么指针吗?
答案 0 :(得分:0)
每次都需要附加到列表中:
def main():
x = int(input("Enter a number (0 to stop) "))
l = [x] # add first x, we will add to the is list not reassign l inside the loop
while x != 0:
x = int(input("Enter a number (0 to stop) "))
l.append(x) # append each time
print(l) # print all when user enters 0
l = [x]
将l
重新分配给包含x
每次循环的值的列表,以获取必须附加到列表的所有数字l在循环外初始化
你也可以使用iter
,其标记值为“0”:
def main():
l = []
print("Enter a number (0 to stop) ")
for x in iter(input,"0"):
print("Enter a number (0 to stop) ")
l.append(int(x))
print(l)