I am currently working on a simple calculator program and I have run into a problem with taking data from a nested function and using it in another nested function.
Here is the portion of my code that this problem relates to:
def func():
def func1():
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
def func2():
print(f"{a}, {b}")
func1()
func2()
func()
As you can see, func()
is called which calls func1()
and func2()
. However, running this program results in NameError: name 'a' is not defined
with an error reference line pointing towards the body of func2()
.
I know it is not possible to access a, b
within func2()
as they are only defined within func1()
, but I cannot use the nonlocal
statement as according to the documentation:
'names listed in a nonlocal statement ... must refer to pre-existing bindings in an enclosing scope.'
and func1()
does not enclose func2()
.
More so, I am trying to avoid using the global
statement or defining a
and b
in func()
because it seems to be poor practise in any programming language (reference) and could lead to unintended side-effects later on in my program's development.
Is there any way to declare a
and b
as usable and modifiable anywhere within func()
, whilst still defining it in func1
?
You just need to return them in func1 and pass the results to func2
def func1():
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
return a, b
Then,
def func2(a, b):
print(f"{a}, {b}")
And then when you call the functions you assign variables a and b to the result of func1 and pass them as parameters to func2,
a,b = func1()
func2(a, b)
You could initialize the variables in the scope of func but it is better to handle them as the return of the function, it easier to keep track of the algorithm that way.