简体   繁体   中英

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

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

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)

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM