[英]while loop could not break
有NameError: name 'user' is not defined
为什么while循环没有结束请帮助找到问题
该程序用于 pyhton 中的掷骰子我想毫无例外地掷骰子,但有异常发生
rand_num=random.randint(1, 6)
game_is_on=True
while True:
try:
user=int(input("What's your choice : "))
continue
except:
print("Please Enter 1-6")
if user == rand_num:
print("\t congrats ! \n You guessed it right 🎊")
elif user != rand_num:
print("Sorry! your guess is incorrect🥺")
replay=input("Do you want to play again (Yes/No)")
if replay =='yes'.lower():
game_is_on=True
else:
print("Thanks for playing this game")
game_is_on=False```
hlep to find the problem please
要退出循环:
game_is_on
。 而不是永远循环, game_is_on
应该在 while 旁边,continue
语句,因为只要条件为真,该行将只是 go 到下一次迭代,以下是您需要的代码:
rand_num=random.randint(1, 6)
game_is_on=True
# while True:
while game_is_on:
try:
user=int(input("What's your choice : "))
# continue
except:
print("Please Enter 1-6")
if user == rand_num:
print("\t congrats ! \n You guessed it right 🎊")
elif user != rand_num:
print("Sorry! your guess is incorrect🥺")
replay=input("Do you want to play again (Yes/No)")
if replay.lower() =='yes':
game_is_on=True
else:
print("Thanks for playing this game")
game_is_on=False
快乐编码!
导入随机 rand_num=random.randint(1, 6) game_is_on=True
while game_is_on: try: user=int(input("What's your choice: ")) except: print("Please Enter 1-6")
if user == rand_num:
print("\t congrats ! \n You guessed it right 🎊")
elif user != rand_num:
print("Sorry! your guess is incorrect🥺")
replay=input("Do you want to play again (Yes/No)")
if replay =='yes'.lower():
game_is_on=True
else:
print("Thanks for playing this game")
game_is_on=False
注意:在while循环中,您必须为该变量编写'game_is_on',它会告诉您是真还是假,而不是您写了True,因此您的循环将永远不会结束,因为没有任何东西破坏循环更正的代码粘贴在上面,希望这可能会有所帮助你。
您可以使用运算符 break 来结束 while 循环。 lower() 应该与变量一起使用。
if replay.lower() != 'yes':
print("Thanks for playing this game")
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.