密码验证程序:如何仅在失败时显示剩余尝试次数
解决密码验证程序中剩余尝试次数提示的问题
你的问题出在代码逻辑顺序上:当前不管输入的密码是否正确,程序都会先扣减尝试次数并打印剩余次数,导致密码正确时也会弹出这条多余的提示。只需调整判断和输出的顺序,就能实现「仅失败时显示剩余次数,成功时只显示Access Granted」的效果。
修改后的代码方案一
# 设置变量 correct_password = "Password123!" attempt_limit = 3 user_input = "" # 循环验证密码 while user_input != correct_password: user_input = input("Enter your password: ") # 先判断密码是否正确,正确直接授权并跳出循环 if user_input == correct_password: print("Access Granted") break # 密码错误时才处理剩余次数 attempt_limit -= 1 print(f"You have {attempt_limit} attempts left") # 次数用完则拒绝访问并终止循环 if attempt_limit == 0: print("Access Denied") break
修改后的代码方案二(利用while-else结构)
correct_password = "Password123!" attempt_limit = 3 user_input = "" # 循环条件:密码不正确且还有剩余尝试次数 while user_input != correct_password and attempt_limit > 0: user_input = input("Enter your password: ") # 密码正确就跳出循环,进入else分支处理授权 if user_input == correct_password: break # 密码错误时才扣减次数并提示剩余次数 attempt_limit -= 1 print(f"You have {attempt_limit} attempts left") else: # 循环结束后判断是授权还是拒绝 print("Access Granted" if user_input == correct_password else "Access Denied")
核心修改逻辑
- 提前判断密码正确性:输入密码后先检查是否匹配,匹配则直接输出授权信息并终止流程,跳过后续的次数扣减和提示逻辑。
- 仅错误触发次数提示:只有当密码输入错误时,才执行扣减尝试次数、打印剩余次数的操作。
内容的提问来源于stack exchange,提问作者user23498718
相关产品推荐
相关产品推荐

