免责声明;我大约一周前才开始使用Python,所以请原谅我使用任何错误的语法和类似内容。
我尝试用Python编写一个小程序,将6个骰子掷骰子,并一直进行到6个6。然后,它计算所需的卷数。进行得很好,但是,我决定让用户决定重复此过程多少次,并将每个所需的卷数添加到列表中。
我的问题是,例如,如果我让程序运行3次,则末尾的列表将包含需要3次的LAST Rolls,而不是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)
import random as rd
n=int(input("How many times do you want to roll 6 sixes?"))
g=[]
for i in range(n):
rollno = 0
rollsum = 0
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
保留了先前的计数。所以我的更改是在外部循环而不是外部都初始化。