Understanding Variable Scope In Nested Functions In Python
I have the following functions in Python3.7 def output_report(): sheet_dict = {1: 'All', 2: 'Wind', 3: 'Soalr'} sheet_name = sheet_dict[sheet_num] file_name = f'{file_
Solution 1:
In your first case
def good_func():
sheet_num = 2
row_num = 2
a = test_file('new file')
return a
sheet_num
and row_num
are local to the function good_func
and hence cannot be accessed in another function output_report
But when you do
sheet_num = 2
row_num = 2def good_func():
a = test_file('new file')
return a
sheet_num
and row_num
become global variables accessible to all other functions, hence they are accessible in output_report
as well
Also nested function are functions whose definition lies within another function like so, where a
is accessible in inner
def outer():
a = 1def inner():
print(a)
inner()
outer()
Calling another function inside a function like you do in good_func
doesn't make them output_function
nested.
Post a Comment for "Understanding Variable Scope In Nested Functions In Python"