如何在Python 3中的多个不同函数中使用变量
我在一个函数中定义了一个名为“computerChoice”的变量,然后尝试在另一个变量中使用它,但它说“computerChoice”未定义。。。作为Python新手,我不知道为什么会发生这种情况,所以我希望您能帮助回答我的问题如何在Python 3中的多个不同函数中使用变量,python,python-3.x,function,variables,Python,Python 3.x,Function,Variables,我在一个函数中定义了一个名为“computerChoice”的变量,然后尝试在另一个变量中使用它,但它说“computerChoice”未定义。。。作为Python新手,我不知道为什么会发生这种情况,所以我希望您能帮助回答我的问题 def computerDecision(): import random for x in range(1): num = random.randint(1,4) if
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
将其声明为全局(可从任何地方访问):
全球计算机选择
然而,这可能不是您想要的,因为您的函数不需要彼此交互。您只需让computerDecision()
返回其选择即可
随机导入
def computerDecision():
对于范围(1)内的x:
num=random.randint(1,4)
如果num==1:
返回“摇滚乐”
elif num==2:
返回“文件”
elif num==3:
返回“剪刀”
def determineWinner():
computerChoice=computerDecision()
如果userInput==computerChoice:
打印(“你们都选择了”+计算机选择)
打印(“绘制!”)
elif userInput=='rock'和computerChoice=='paper':
打印(“计算机选择”+计算机选择)
打印(“计算机获胜!”)
elif userInput=='rock'和computerChoice=='scissors':
打印(“计算机选择”+计算机选择)
打印('用户赢!')
elif userInput=='paper'和computerChoice=='rock':
打印(“计算机选择”+计算机选择)
打印(“用户赢!”)
elif userInput=='paper'和computerChoice=='scissors':
打印(“计算机选择”+计算机选择)
打印(“计算机获胜!”)
elif userInput==“剪刀”和computerChoice==“石头”:
打印(“计算机选择”+计算机选择)
打印(“计算机获胜!”)
elif userInput==“剪刀”和computerChoice==“纸”:
打印(“计算机选择”+计算机选择)
打印(“用户赢!”)
还要注意的是,
computerDecision()
可以更简单地重新定义,只需返回random.choice((“石头”、“布”、“剪刀”)
您的意思是您试图在另一个函数中使用computerChoice
?除非您通过修复示例代码中的缩进将变量声明为globalStart,否则这是行不通的,因为这一切都搞砸了,然后粘贴一个完整的最小可运行示例,并作为运行代码的结果粘贴完整的输出。请记住,帮助您的人也需要能够完全按照您现有的方式运行代码。修复代码中的缩进,因为不清楚您实际在做什么。第二,根据您运行程序的方式,您有两个选项可以执行此操作:使用global
关键字,或者从一个函数返回值并将其传递给另一个(这是最好的)