Why is the return function not passing the variables to the next function?

Question:

I’m trying to get rid of the error without moving the input function out of the userInput function. I expected the return function to remove the NameError. I looked all over stack exchange and in my textbook to figure out this problem.

def userInput():
    a = float(input("Enter a: "))
    b = float(input("Enter b: "))
    return (a,b)

def printFunction(a2,b2):
    print(a2)
    print(b2)

def main():
    userInput()
    printFunction(a2,b2)
    
main()

NameError: name ‘a2’ is not defined

Asked By: Stavros Piliaris

||

Answers:

Functions return values, not variables. The names a and b are only defined in userInput: you need to receive the values returned by userInput in variables defined in main.

def main():
    x, y = userInput()
    Printfunction(x, y)
Answered By: chepner

You need to assign the return values of userInput to variables if you want to be able to refer to them on the next line:

def main():
    a2, b2 = userInput()
    Printfunction(a2,b2)

or you could skip a step and pass userInput‘s output directly to Printfunction as positional arguments with the * operator:

def main():
    Printfunction(*userInput())
Answered By: Samwise
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.