【发布时间】:2019-07-20 16:35:57
【问题描述】:
我在一个函数中定义了一个名为“computerChoice”的变量,然后尝试在另一个变量中使用它,但它说“computerChoice”是未定义的……作为 Python 新手,我不确定为什么会发生这种情况,所以我希望您能帮助回答我的问题!
def computerDecision():
import random
for x in range(1):
num = random.randint(1,4)
if num == 1:
computerChoice = 'rock'
elif num == 2:
computerChoice = 'paper'
elif num == 3:
computerChoice = 'scissors'
def determineWinner():
if userInput == computerChoice:
print("You both chose " + computerChoice)
print("DRAW!")
elif userInput == 'rock' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'rock' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print('USER WINS!')
elif userInput == 'paper' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("USER WINS!")
elif userInput == 'paper' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("USER WINS!")
【问题讨论】:
-
你的意思是你试图在另一个函数中使用
computerChoice?除非您将变量声明为全局变量,否则这是行不通的 -
首先修复示例代码中的缩进,因为这一切都搞砸了,然后粘贴一个完整的最小可运行示例,以及运行代码后的完整输出。请记住,帮助您的人也需要能够完全按照您的方式运行您的代码。
-
修复代码中的缩进,因为不清楚您实际在做什么。其次,根据您运行程序的方式,您有两种选择:使用
global关键字,或者,从一个函数返回值并将其传递给另一个函数(这是更可取的)
标签: python python-3.x function variables