Home > front end >  How do I use the data collected of one function in another function
How do I use the data collected of one function in another function

Time:10-17

So basically I'm a pure beginner trying to do this school assignment.

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

The second function can't access the variable locked in the first function and I don't know how to get it to access it. Plz help.

CodePudding user response:

function2 can't access it because choice1 is a Local Variable. In python, any variable created in a function is a local variable by default. You could override this by assigning choice1 as a global variable. Also, read these guidelines for styling your code. https://www.python.org/dev/peps/pep-0008/

CodePudding user response:

choice1 variable is defined in function1, but not in function2 where you also use it.

One option, and avoid using globals, is to pass the result of function1 into function2 as a parameter, then function2 can use it.

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

CodePudding user response:

You can call the function 1 into function 2 as you already return choice1 value from function1. For example :

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