[英]Why isn't my variable showing as defined?
我正在尝试将“摇滚,纸,剪刀”作为我的第二个程序。 我一直遇到错误,
"Traceback (most recent call last):
File "/home/cabox/workspace/main.py", line 118, in <module>
File "/home/cabox/workspace/main.py", line 48, in Rock_Paper_Scissors
else:
NameError: name 'rps_choice' is not defined"
这是代码。
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")
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.")
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()
正如您可能看到的,我的变量rps_choice
未定义,即使它已定义并从rps_input()
函数返回。 我真的不知道为什么会这样。
您打算在rps_choice
捕获返回值:
rps_choice = rps_input()
另外,我看到您在两条不同的行上调用了rps_input()
。 这两行都需要更新。
因为你在函数rps_input()
定义了它,所以它只属于那个函数。 把它想象成一个层次结构,下层作用域的变量可以访问上层作用域的变量,但不能相反。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.