为什么我的变量没有按定义显示?
我正在尝试将“摇滚,纸,剪刀”作为我的第二个程序。我一直遇到错误,
"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()拨打了两条不同的线路。这两行都需要更新。