首页 > 解决方案 > 如何在另一个函数中使用一个函数收集的数据

问题描述

所以基本上我是一个纯粹的初学者,试图做这个学校作业。

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

第二个函数无法访问锁定在第一个函数中的变量,我不知道如何让它访问它。请帮忙。

标签: pythonfunction

解决方案


您可以将函数 1 调用到函数 2 中,因为您已经从 function1 返回了 choice1 值。例如 :

def function2(): 
    choice1 = function1()
    rightEvenOdd = 'random word'
    if choice1 == rightEvenOdd:
     print('Yay')
    else: 
     print('Not yay')

推荐阅读