Python: Variable Scope

This code has been written in Python to represent the baggage weight check process based on the weight limit specified by an airline.

You can go through the below code and guess the output.

	def baggage_check(baggage_wt):
	    if not(baggage_wt>=0 and baggage_wt<=wt_limit):
	    return extra_baggage_charge
	def update_baggage_limit(new_wt_limit):
	    print("This airline now allows baggage limit till",wt_limit,"kgs")
	print("This airline allows baggage limit till",wt_limit,"kgs")
	print("Pay the extra baggage charge of",baggage_check(35),"rupees")
	print("Pay the extra baggage charge of",baggage_check(35),"rupees")	 

Let us go through the code now in more detail to see the scope of variables.

Python scope of variables

extra_baggage and extra_baggage_charge are created inside the function baggage_check(). Hence they are local to that function or in other words, they are local variables. They are created when owning function starts execution and remains in memory till owning function finishes execution. They can be accessed only inside that function.

wt_limit is created outside the functions. Hence it is a global variable. Global variables are created when the program execution starts and remains in memory till the program terminates. They can be read anywhere in the program – within a function or outside. But they are protected from modification inside a function. As it is available throughout the program, use of global variable should be restricted to avoid accidental misuse by developers and to minimize memory usage.

In cases where a global variable needs to be modified inside a function, like in function update_baggage_limit(), Python allows you to do that using the global keyword.

Python Variable Scope