![](/img/trans.png)
[英]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.