Python猜密码小游戏While循环持续运行问题求助
问题修复方案
核心问题分析
你的while循环条件用了or,导致逻辑恒成立:
while user_decision != 'play' or user_decision != 'rules':
任何输入不可能同时等于play和rules,所以这个条件永远为True,循环会无限运行。
修复后的完整代码
import random, time user = input("Enter your name: ") bet_coins = 7000 # 秘密密码(转为字符串列表方便对比) secret_code = ['12', '1', '7', '4'] print("Welcome to the safe game, " + user[0].upper() + user[1::] + ".") time.sleep(2) print("Your goal here is to guess the safe key.") time.sleep(2) print("Here's how you start:") time.sleep(2) def check_score(user_guess): # 将用户输入分割为列表 user_guess_fixed = user_guess.split() # 检查输入是否符合4位格式 if len(user_guess_fixed) != 4: print("Invalid format! Please enter 4 numbers separated by spaces, e.g '1 2 3 4'") return # 对比密码,计算正确位数 correct_count = 0 for secret, guess in zip(secret_code, user_guess_fixed): if secret == guess: correct_count += 1 print(f"You got {correct_count} out of 4 digits right!") # 判断是否猜对全部密码 if correct_count == 4: print("Congratulations! You opened the safe!") return True return False # 主循环:处理用户选择 while True: user_decision = input("To play send *play*, for rules send *rules*, to quit send *quit*\n").lower() time.sleep(2) if user_decision == 'play': print("HERE WE GO! Guess the code!") print("(Remember, 4 blocks, each one is a number between 1-20, e.g '1 2 3 4')") # 游戏循环:直到猜对密码 while True: user_guess = input("Enter your guess: ") if check_score(user_guess): break # 猜对后退出游戏循环 print("Try again!") time.sleep(1) elif user_decision == 'rules': print("Game Rules:") print("- You need to guess a 4-digit code, each digit is between 1-20") print("- Each guess will tell you how many digits you got right") print("- Keep guessing until you get all 4 digits correct!") time.sleep(3) elif user_decision == 'quit': print(f"Thanks for playing, {user}! See you next time!") break else: print("Oops, invalid entry. Please enter 'play', 'rules', or 'quit'.") time.sleep(2)
关键修改点
修复循环逻辑:
- 改用无限循环
while True,通过quit选项主动终止程序,流程更合理 - 移除原错误的
or条件,改为明确判断输入是否为有效选项
- 改用无限循环
优化函数设计:
- 函数重命名为
check_score(符合Python命名规范) - 把
user_guess作为参数传入,避免依赖全局变量 - 添加输入格式校验,确保用户输入符合要求
- 完善密码对比逻辑,返回是否猜对的结果来控制游戏循环
- 函数重命名为
完善游戏体验:
- 新增
quit选项,支持主动退出 - 补充规则说明内容
- 猜对密码后自动退出游戏环节,回到主选择界面
- 新增
内容的提问来源于stack exchange,提问作者Shahar
相关产品推荐
相关产品推荐

