我怎么能把它放在一个循环中,一开始尝试使用while循环,但我会得到错误的输出


  • 如果两个六面骰子得分相同(例如:(6,6((等于一个双,则模拟两个六面的骰子滚动的程序。

  • 我希望用户在掷骰子并显示出双打次数后能够再次上场。

提前感谢。

import random
user_input= int(input("How many times would you like to roll the dice?"))
Dice_1 = [random.randint(1,6) for x in range(user_input)]
Dice_2 = [random.randint(1,6) for x in range(user_input)]
count = 0
for a,b in zip(Dice_1,Dice_2):
if((a)) == ((b)):
print("double")
count += 1
else:
print((a,b))
print(f'nYou have scored {count} doubles! out of {user_input}')

所以我不确定你的第一次尝试,但我想说,即使失败了,也很高兴看到你尝试了什么:(

使用while循环是最简单、最方便的方法。例如

import random
while user_input := int(input("How many times would you like to roll the dice?")) :
Dice_1 = ...
... # roll dice, blah blah

会做你想做的事。输入0将中断while循环(因为0在python中被认为是false,即while 0->while False和除0之外的任何其他整数都被认为是true(。注意,它使用了海象运算符:=而不是=

如果没有海象操作员,上面与下面类似:

user_input = int(input("How many times would you like to roll the dice?"))
while user_input != 0:
... # roll dice, blah blah

#then ask again if they want to roll again
user_input = int(input("How many times would you like to roll the dice?")

:=海象运算符只是使其更可读的一种方式(它计算:= int(input("How many times would you like to roll the dice?"))的结果值并将其分配给user_input(。

最新更新