满足验证条件后Python While循环未终止的问题求助
解决你的登录验证循环无法终止问题
嘿,我一眼就看到问题出在哪了——你的循环一直跑是因为没有正确更新用来判断终止的confirmation变量,还有几个小细节拖了后腿。咱们一步步来修复:
核心问题分析
- 函数返回值没被接收:你调用
loginConfirmation后,没有把它返回的结果赋值给外部的confirmation,所以这个变量一直是初始的0,循环条件confirmation !=4永远为真。 - 参数传递的坑:你把
confirm1和confirm2作为参数传给函数,但Python里是按值传递,函数内部修改的只是局部变量,外部的这两个值根本不会变,等于白加。 - 没有重置计数:就算前面的问题解决了,每次循环不重置
confirm1和confirm2,它们会一直累加,导致confirmation数值混乱,逻辑出错。
修复后的完整代码
def loginConfirmation(user1, user2, pass1, pass2): # 每次校验都重新初始化计数,避免旧值干扰 confirm1 = 0 confirm2 = 0 # 校验玩家1的用户名 if len(user1) > 6: confirm1 += 1 else: print("Invalid username Player 1") # 校验玩家2的用户名 if len(user2) > 6: confirm2 += 1 else: print("Invalid username Player 2") # 校验玩家1的密码(修正了拼写错误:passsword → password) if pass1 == "password": confirm1 += 1 else: print("Invalid password Player 1") # 校验玩家2的密码 if pass2 == "password": confirm2 += 1 else: print("Invalid password Player 2") return confirm1 + confirm2 # 初始化确认状态 confirmation = 0 while confirmation != 4: print("Please enter your details below. Usernames must be at least six letters long.") user1 = input("Player 1, enter your username: ") pass1 = input("Player 1, enter your password: ") user2 = input("Player 2, enter your username: ") pass2 = input("Player 2, enter your password: ") # 关键:把函数返回的校验结果赋值给confirmation,让循环能判断是否终止 confirmation = loginConfirmation(user1, user2, pass1, pass2)
关键修改说明
- 把计数变量移到函数内部:这样每次调用函数都会重新初始化
confirm1和confirm2,避免外部变量的干扰,也不用再纠结参数传递的问题。 - 接收函数返回值:调用
loginConfirmation时,一定要把返回的结果赋值给confirmation,这样循环条件才能根据每次的校验结果更新。 - 修正拼写错误:你代码里的
passsword多了一个s,我已经帮你改成正确的password了,不然密码校验永远通不过哦。
现在当两个玩家的用户名长度都超过6,并且密码都是password时,函数会返回4,循环条件confirmation !=4不成立,程序就会正常终止啦。
内容的提问来源于stack exchange,提问作者Prudence
相关产品推荐
相关产品推荐

