[英]populating a list in python via append
I am practicing beginners Python projects and trying to do the dice rolling simulator, where it stores the totals of all die in a list. 我正在练习Python的初学者项目,并尝试做骰子滚动模拟器,它将所有骰子的总数存储在列表中。 However, it doesn't work for some reason.
但是,由于某些原因,它不起作用。 Could someone explain why a code like this works:
有人可以解释为什么这样的代码起作用:
n=0
a=[]
while n<6:
n+=1
a.append(n)
print(a)
and produces [1, 2, 3, 4, 5, 6], but this code doesn't: 并生成[1、2、3、4、5、6],但是此代码不会:
import random
maxnum=6
minnum=1
roll_again="y"
count=0
while roll_again=="y":
tots=[]
print("rolling the dice...")
roll1=(random.randint(minnum,maxnum))
roll2=(random.randint(minnum,maxnum))
count+=1
total=roll1+roll2
print(roll1, roll2)
print("Try #",count, ": Total = ", total,"\n")
roll_again=input("Roll the dice again? Y/N ")
if roll_again!="y" and roll_again!="n":
print("please enter 'y' for yes or 'n' for no")
roll_again=input("Roll the dice again? Y/N ")
tots.append(total)
print(tots)
It just prints the last total as a list with one value. 它只是将最后一个总数打印为带有一个值的列表。 What am I missing here?
我在这里想念什么?
Move the tots = []
out of while loop, as wnnmaw suggested. 按照wnnmaw的建议,将
tots = []
移出while循环。 Write it just before the loop, underneath count=0
. 将其写在循环之前,在
count=0
。
you reset the list tots=[]
in each iteration so that it never gets to hold more than one element. 您可以在每次迭代中重置列表
tots=[]
,这样它就永远不会容纳多个元素。 try to put it outside the while loop: 尝试将其放在while循环之外:
tots=[]
while roll_again=="y":
...
tots.append(...)
print(tots)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.