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.

	wt_limit=30
	
	def baggage_check(baggage_wt):
	    extra_baggage_charge=0
	    if not(baggage_wt>=0 and baggage_wt<=wt_limit):
	        extra_baggage=baggage_wt-wt_limit
	        extra_baggage_charge=extra_baggage*100
	    return extra_baggage_charge
	
	def update_baggage_limit(new_wt_limit):
	    wt_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")
	update_baggage_limit(45)
	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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s