Python猜拳程序while循环无法退出问题及变量必要性咨询
问题分析与修改方案
1. while循环无法退出的原因及修复
你的checking函数里有两个关键问题导致循环无法终止:
- 赋值错误:判断用户输入合法后,你写的是
user_choice == True,这是比较运算符而非赋值操作,根本不会改变user_choice的状态。必须改成user_choice = True才能终止循环。 - 未返回有效选择:函数内的
choice_user是局部变量,修改后不会传递到函数外部,而且当前代码没有返回值,导致外部无法获取用户的合法选择。需要让函数返回最终的有效选择结果。
修改后的checking函数:
corect_options = ["KAMIEŃ","PAPIER","NOŻYCE"] def checking(player): global corect_options user_choice = False while not user_choice: choice_user = input("%s wpisz wybór: " % player).upper() # 处理拼写变体 if choice_user == "KAMIEN": choice_user = "KAMIEŃ" elif choice_user == "NOZYCE": choice_user = "NOŻYCE" if choice_user in corect_options: user_choice = True return choice_user # 返回合法选择
2. choice_user1变量是否必要?
完全没必要。当前代码里choice_user1 = "something"只是一个无意义的初始值,传入函数后也不会被修改(函数内的choice_user是局部变量,和外部的choice_user1无关)。直接调用checking函数并接收返回值即可:
修改主循环部分:
while points_1 < lifes and points_2 < lifes: choice_user1 = checking(player_1) # 同理获取玩家2的选择 choice_user2 = checking(player_2) # 此处可添加胜负判断与积分更新逻辑
额外补充(可选)
原代码缺少胜负判断和积分更新逻辑,这里提供一个示例供你参考:
# 判断胜负 if choice_user1 == choice_user2: print("Remis!") elif (choice_user1 == "KAMIEŃ" and choice_user2 == "NOŻYCE") or \ (choice_user1 == "PAPIER" and choice_user2 == "KAMIEŃ") or \ (choice_user1 == "NOŻYCE" and choice_user2 == "PAPIER"): points_1 += 1 print(f"{player_1} zdobywa punkt! Aktualne wyniki: {player_1} {points_1} - {player_2} {points_2}") else: points_2 += 1 print(f"{player_2} zdobywa punkt! Aktualne wyniki: {player_1} {points_1} - {player_2} {points_2}")
内容的提问来源于stack exchange,提问作者Krzysztof Polak
相关产品推荐
相关产品推荐

