42.4k views
2 votes
3-Write a Python program that has subprograms nested four deep and in which each nested subprogram references local variables, variables defined in all of its enclosing subprograms, and global variables.

User Gog
by
7.3k points

1 Answer

4 votes

Answer:

Step-by-step explanation:

Below is a little explanation to guide us through;

There are 4 nested methods : level 0, level 1, level 2, and level 3.

Before the methods, there's a global variable defined that can be accessed by all the methods.

Level 0:

This method uses global variable, creates a level 0 variable in its scope, this level 0 variable can be used by all underlying nested methods.

Level 1: this method uses global, level 0, and level 1 variable, which can be accessed by all underlying nested methods: level 2, level 3.

Level 2: similar to te previous ones, it also uses global, level 0, level 1 variables. And creates a level 2 variable that can be accessed by level 3 also.

Level 3:

This method uses all previously created variables, and creates a new level 3 variable.

Function calls:

As you can see, the function calls are part of the method scopes. So, in order to call level 3, we need to access level 2 (because it is getting called from level 2 scope), for level 2, we must call level 1, for which level 0 needs to be called.

So, level 0 is called, which gives its out put and calls level 1, which gives its own output and calls level 2 and so on till level 3 is also called.

CODE:

global_var = "global" #accessible to all functions

def level0():

level0_var = "level 0" #accessible to level 0,1,2,3

print();

print("Level 0 function:")

print("global variable: ",global_var)

print("local variable 0: ",level0_var)

def level1():

print();

print("Level 1 function:")

level1_var = "level 1" ##accessible to level 1,2,3

print("global variable: ",global_var)

print("local variable 0: ",level0_var)

print("local variable 1: ",level1_var)

def level2():

print();

print("Level 2 function:")

level2_var = "level 2" #accessible to level 2,3

print("global variable: ",global_var)

print("local variable 0: ",level0_var)

print("local variable 1: ",level1_var)

print("local variable 2: ",level2_var)

def level3():

print();

print("Level 3 function:")

level3_var = "level 3" #accessible to level 3

print("global variable: ",global_var)

print("local variable 0: ",level0_var)

print("local variable 1: ",level1_var)

print("local variable 2: ",level2_var)

print("local variable 3: ",level3_var)

level3()

level2()

level1()

level0()

attached is the result of the code, also take note of the indentations too

cheers i hope this helps!!!!!

3-Write a Python program that has subprograms nested four deep and in which each nested-example-1
3-Write a Python program that has subprograms nested four deep and in which each nested-example-2
User Soully
by
8.0k points