免责声明;我大约一周前才学会Python,所以请原谅我的语法和诸如此类的错误
我用Python尝试了一个小程序,它掷6个骰子并一直运行直到得到6个6。然后计算所需的卷数。这进行得很顺利,但是,我决定让用户决定这个过程重复多少次,并将每个需要的卷数添加到列表中
我的问题是,例如,如果我让程序运行3次,那么最后的列表包含需要3次的最后转鼓数,而不是3个唯一的值
import random as rd
rollsum = 0
rollno = 0
n=int(input("How many times do you want to roll 6 sixes?"))
g=[]
for _ in range(n):
while rollsum != 36:
a, b, c, d, e, f = (rd.randint(1, 6) for k in range(6)) # The die get assigned a random value between 1 and 6
rollsum = a + b + c + d + e + f # The sum of the die is calculated
rollno += 1 # The number of rolls is increased by 1
print()
print("Roll:", a, b, c, d, e) # Prints the value of each of the 6 die
print("Sum:", rollsum) # Prints the sum of the 6 sie
print("Roll number:", rollno) # Prints the number of rolls
g.append(rollno)
print(g)
代码早期失败的原因是,在第一次之后,
rollsum
是36,因此它没有进入内部循环。第二件事是rollno
保留了先前的计数。所以我的改变是在外部循环中初始化,而不是在外部循环中初始化相关问题 更多 >
编程相关推荐