Python中询问用户是否要另一数字的while循环无法停止如何解决
问题根本原因
你的内层循环无法终止是缩进错误导致的:
你用来判断用户输入、修改Additional_Num变量的代码块,放在了while Additional_Num == True循环的外部,内层循环运行过程中永远不会修改终止条件变量的值,因此不管用户输入什么内容,循环都会一直重复执行。
除此之外代码还有两处明显逻辑错误:
- 打印AI数值的语句错误输出了布尔变量
Additional_Num,应该输出预先生成的AI_num - "Bye for now!"的打印放在了最外层循环内部,会导致每次询问是否重玩后都会先打印一次,不符合预期
修复后的完整代码
import random play = True print("Hello! Welcome to 13 in - to Win") name = input("What is your name? ") while play == True: AI_num = random.randint(1,19) Additional_Num = True PTotal = 0 while Additional_Num == True: Player_Num = random.randint(1,10) PTotal = PTotal + Player_Num print(name,"Got A",Player_Num) print("Your Total is: ",PTotal) play_again = input("Would You Like Another Number? <Yes or No>") # 以下判断逻辑缩进移到内层循环内部 if play_again == "Yes": Additional_Num = True else: Additional_Num = False print("AI got ",AI_num) print(name,"Got total",PTotal) play_again = input("Would you like to play again? <Yes or No>") if play_again == "Yes": play = True else: play = False # 结束提示移到最外层循环外 print("Bye for now!")
可选优化建议
- 输入判断兼容大小写:将用户输入转成全小写/全大写后再判断,兼容用户输入
yes、YES、no、NO等不同写法 - 增加胜负判定逻辑:可以对比玩家总点数和AI点数、或者判断是否超过13点,输出胜负结果
- 增加输入合法性校验:如果用户输入的不是Yes/No,给出提示要求重新输入,避免逻辑错误
内容的提问来源于stack exchange,提问作者Surajjh
相关产品推荐
相关产品推荐

