Check out this classic computer program:
Note: in this page, we will refer to functions and procedures as modules.
As you can see, it doesn't work! That's because the variable name is declared inside a module called main. This variable is not visible to other modules in the program.
A variable has local scope if it is declared inside a module. Only that module can see it.
So, in the above program, name is declared in the main() module and the intro() module cannot see it.
The best way around this problem is to pass a variable as an argument to other modules in our program.
Look at this program. What do you think will be displayed in the output? Write it down on a piece of paper.
def main():
age = 17 #local variable in main module
print("In the main procedure, you are",age,"years old!")
birthday(age) #the birthday module accepts age as an argument
print("In the main procedure, you are",age,"years old!")
def birthday(num): #the birthday module's design requires one parameter
num = num+1
print("Happy birthday! You are",num,"years old!")
#call the main procedure
main()
Code this program. Was your prediction correct?
module procedure return identifier parameter pseudocode return typedefinecalldata type