[英]How to create a while loop that adds user inputted integers into a list, then displays that list of user inputs after every failed input?
[英]how to create a list after a while loop
我有一个关于在while循环后如何创建列表的问题。 我想将从while循环中获得的所有数字放入一个列表中,例如:
x=4
while(1):
print(x)
x=x+1
if x==8:break
然后我得到
4
5
6
7
我想在一个列表中显示这些数字。
l=[]
x=4
while(1):
print(x)
l.append(x)
x=x+1
if x==8:break
print(l)
这就是将其添加到代码中的方式。 仅供参考,如果您想以“ Pythonic”的方式进行操作,则非常简单:
l = range(4, 8)
L = []
i = 4
while i<=8:
print(i)
L.append(i)
i += 1
您正在寻找append()函数。 在此处查看python列表文档以获取更多信息。
list=[] #declare a blank list to use later
x=4
while(1):
list.append(x) #add x to the list
x += 1 # a shorthand way to add 1 to x
if x == 8:break
print(list) #after the loop is finished, print the list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.