运行代码后,我的 while 循环回到顶部。我怎样才能让它在"再次"之后重新开始?



我正试图创建一个骰子游戏,但在游戏完成后,我希望它能以问题"重新开始;你想再掷骰子吗;而不是转到第一个语句。这是我所了解到的,我不确定该如何更正代码。非常感谢您的帮助!!

import random
dice_number = random.randint(1, 6)
play = True
while play:
roll_dice = input("Would you like to roll the dice?")
if roll_dice.lower() == 'yes':
print(dice_number)
else:
print("Let us play later then.")
break
again = str(input("Do you want to roll the dice again?")) 
if again == 'yes':
print(dice_number)  
if again == 'no':
play = False
print("It has been fun playing with you.")
continue

试试这个:

import random
dice_number = random.randint(1, 6)
play = True
first = True
while play:
again = input("Would you like to roll the dice?") if first else str(input("Do you want to roll the dice again?")) 
first = False
if again.lower() == 'yes':
print(dice_number)
else:
print("Let us play later then.")
break

你可以试试这个。

import random
dice_number = random.randint(1, 6)
play = True
started = False
while play:
if started:
again = str(input("Do you want to roll the dice again?"))
if again == 'yes':
print(dice_number)
elif again == 'no':
play = False
print("It has been fun playing with you.")
break
else:
roll_dice = input("Would you like to roll the dice?")
if roll_dice.lower() == 'yes':
started = True
print(dice_number)
else:
print("Let us play later then.")
break

样本输出:

Would you like to roll the dice?yes
3
Do you want to roll the dice again?yes
3
Do you want to roll the dice again?yes
3
Do you want to roll the dice again?yes
3
Do you want to roll the dice again?yes
3
Do you want to roll the dice again?no
It has been fun playing with you.

最新更新