Python实现幸运7骰子游戏时无法退出内层While循环问题求助
问题修复说明
布尔条件逻辑错误
你写的playing == 'Yes' or 'yes'语法逻辑不成立,or右侧的'yes'作为非空字符串,布尔值永远为True,所以无论playing变量的值是什么,这个判断条件永远成立。
建议修改为更简洁的playing.lower() == 'yes',可以同时兼容大小写输入的Yes/YES/yes等情况。变量赋值误用比较运算符
代码中两处接收用户是否继续游玩的输入时,都写成了playing == input(),==是相等比较运算符,不会修改左侧变量的值,所以playing变量从第一次赋值后就从未更新,导致退出逻辑不生效,需要把==修改为赋值用的单等号=。
修正后完整代码
import random # 初始化变量 times_played = 0 # 询问是否开始游戏 print('Would you like to play Lucky 7s? Type Yes or No.') playing = input() if playing.lower() == 'yes': print('How much would you like to bet?') user_total = int(input('$ ')) while playing.lower() == 'yes': die1 = random.randint(1,6) die2 = random.randint(1,6) dice_total = die1 + die2 if dice_total == 7: print('You won $4!') times_played += 1 user_total += 4 print('You have $', user_total, '.') print('Would you like to keep playing?') playing = input() if playing.lower() == 'no': break else: print('Sorry, you lost.') times_played += 1 user_total -= 1 print('You have $', user_total, '.') print('Would you like to keep playing?') playing = input() if playing.lower() == 'no': break print('Thanks for playing.') print('You rolled', times_played, 'time(s).')
内容的提问来源于stack exchange,提问作者BenB
相关产品推荐
相关产品推荐

