Python编写石头剪刀布游戏时rps_choice变量未定义报错如何解决
错误原因
这是局部变量作用域限制+函数返回值未接收导致的问题:
- 定义在
rps_input()内部的rps_choice是函数局部变量,仅在rps_input()的执行范围内有效,外层的Rock_Paper_Scissors函数无法直接访问这个内部变量 - 你虽然在
rps_input()里通过return语句返回了rps_choice的值,但调用rps_input()时没有用变量接住返回值,外层函数的作用域里始终没有创建名为rps_choice的变量,运行时自然会触发未定义报错。
修复步骤
只需要修改两处调用rps_input()的代码,接收返回值即可:
- 首次调用
rps_input()时赋值给外层变量:
# 原代码:rps_input() rps_choice = rps_input()
- 平局分支下重新调用
rps_input()时也要重新赋值:
if rps_choice == rps_random: print("You both picked the same. Please try again.") # 原代码:rps_input() rps_choice = rps_input()
完整修复后代码
import time import random def Rock_Paper_Scissors(): print("Welcome to the \"Rock, Paper, Scissors\" game!") time.sleep(2) def rps_input(): while True: rps_choice = input("Say \"Rock\", \"Paper\", or \"Scissors\" to get started: ") if rps_choice.upper() == "ROCK": print("Great! You chose", rps_choice.upper(), end='') print("! The computer picked...") return rps_choice.upper() if rps_choice.upper() == "PAPER": print("Great! You chose", rps_choice.upper(), end='') print("! The computer picked...") return rps_choice.upper() if rps_choice.upper() == "SCISSORS": print("Great! You chose", rps_choice.upper(), end='') print("! The computer picked...") return rps_choice.upper() else: print("Sorry, please say \"Rock\", \"Paper\", or \"Scissors.\"") time.sleep(2) print("\n") # 修复1:接收返回值 rps_choice = rps_input() time.sleep(2) rps_list = ["ROCK","PAPER","SCISSORS"] rps_random = random.choice(rps_list) print(rps_random, end='') print("!") time.sleep(2) if rps_choice == rps_random: print("You both picked the same. Please try again.") # 修复2:重新接收返回值 rps_choice = rps_input() else: if rps_choice == "ROCK": if rps_random == "PAPER": print("The computer's paper beats your rock.") time.sleep(2) print("You LOSE.") if rps_random == "SCISSORS": print("Your rock beats the computer's scissors!") time.sleep(2) print("You WIN.") if rps_choice == "PAPER": if rps_random == "ROCK": print("Your paper beats the computer's rock!") time.sleep(2) print("You WIN.") if rps_random == "SCISSORS": print("The computer's scissors beats your paper.") time.sleep(2) print("You LOSE.") else: if rps_random == "ROCK": print("The computer's rock beats your scissors.") time.sleep(2) print("You LOSE.") if rps_random == "PAPER": print("Your scissors beat the computer's paper.") time.sleep(2) print("You WIN.") time.sleep(2) def RPS_Reset_Quit(): rq = input("Restart or quit? (R/Q): ") if rq.lower() == "r": print("\n") Rock_Paper_Scissors() if rq.lower() == "q": print("Quiting...") time.sleep(2) quit() else: print("Sorry, please say either R or Q.") time.sleep(2) RPS_Reset_Quit() RPS_Reset_Quit() Rock_Paper_Scissors()
逻辑优化提示
当前修复后的代码仍存在一个小逻辑缺陷:平局时用户重新选择后,电脑不会重新生成随机选择,仍会使用上一轮的结果。如果要优化可以将「生成电脑随机值+胜负判断」的逻辑也放到循环里,平局时就重新执行完整的选择流程。
内容的提问来源于stack exchange,提问作者Mr. Unknownymous
相关产品推荐
相关产品推荐

