![](/img/trans.png)
[英]How do I use the output of one function for another function?
[英]How do I use the data collected of one function in another function
所以基本上我是一个纯粹的初学者,试图完成这项学校作业。
def function1():
while True:
choice1 = (input("Random text")).lower()
if choice1 in ('option1', 'option2'):
break
else:
print("Even more random text")
return choice1
def function2():
rightEvenOdd = 'random word'
if choice1 == rightEvenOdd:
print('Yay')
else:
print('Not yay')
NameError: name 'choice1' is not defined
第二个函数无法访问锁定在第一个函数中的变量,我不知道如何让它访问它。 请帮忙。
function2 无法访问它,因为 choice1 是Local Variable 。 在python中,函数中创建的任何变量默认都是局部变量。 您可以通过将 choice1 分配为全局变量来覆盖它。 另外,请阅读这些指导以设置代码样式。 https://www.python.org/dev/peps/pep-0008/
choice1
变量是在function1
定义的,但不是在您也使用它的function2
中定义。
一个选项中,并避免使用全局变量,是的结果传递function1
到function2
作为参数,然后function2
可以使用它。
def function1():
while True:
choice1 = (input("Random text")).lower()
if choice1 in ('option1', 'option2'):
break
else:
print("Even more random text")
return choice1
def function2(choice1): #function2 receives the choice1 value
rightEvenOdd = 'random word'
if choice1 == rightEvenOdd:
print('Yay')
else:
print('Not yay')
choice1 = function1() # assign result of function1 to a variable
function2(choice1) # pass the new value to function2
您可以将函数 1 调用到函数 2 中,因为您已经从函数 1 返回了 choice1 值。 例如 :
def function2():
choice1 = function1()
rightEvenOdd = 'random word'
if choice1 == rightEvenOdd:
print('Yay')
else:
print('Not yay')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.