Xuan
Xuan

Reputation: 77

Calling functions into another function and using its variables

def func1():
    x = 100
    john = 'hello'
    return x, john

def func2():
    func1()
    y = x
    return y

print(func2())

So this returns an error:

NameError: name 'x' is not defined

Can someone explain how to use variables of func1 in func2, and explain how calling func1 in func2 work.

Upvotes: 1

Views: 54

Answers (2)

Nimish Bansal
Nimish Bansal

Reputation: 1759

def func1():
    x = 100
    john = 'hello'
    return x, john

def func2():
    x,john=func1()
    y = x
    return y

print(func2())

If you are returning two variables from func1 then the result of func1 should be passed to some other variables too. So you should add:

x,john=func1()

Upvotes: 1

Simpom
Simpom

Reputation: 987

def func1():
    x = 100
    john = 'hello'
    return x, john

def func2():
    x, john = func1()
    y = x
    return y

print(func2())

x is local to func1 (so as to john). But it is one of the returned values of the function; so use it!

Upvotes: 1

Related Questions