Advertisement



< Prev
Next >



Python - Global Variables





In this Python tutorial, we are going to explain the concept of global variables. Global variables are variables which are declared outside all the functions of a program and are accessible from anywhere in the program. i.e. from the inside or outside of any function defined in the program. Consequently, we could say that global variables have a global scope.

In order to understand the concept of global variables, we are going to explain how we can declare, initialize, access and even modify values of global variables within a Python program. So, let us see how it is done in the upcoming programs.





To modify the values of global variables from within any function, we must use the global keyword. In the upcoming program, we are going to define some global variables and then we are going to modify their values from within a called function by using the global keyword.

# Python - Global variables



# Defining global variables 
nickname = 'Mr Blue'
age = 30
height = 180



# Defining a function which modifies values of global variables
def modify_values():

    # Using global keyword to declare the same global variables
    global nickname,age, height	
	
    # Successfully modifying values of global variables
    nickname = nickname + ' Bond'
    age = age + 3
    height = height + 5
    
	
	
	
# Defining the function show_values() 
def show_values():
    print('nicnmame : ', nickname)
    print('age : ', age)
    print('height : ', height)
    
	
	

print('Original values of global variables :')

# Calling the show_values() function
show_values()


# Calling the modify_values() function to modify global variables
modify_values()


print('Modified values of global variables :')

# Calling the show_values() function to display modified values of global variables
show_values()


Output-


Original values of global variables :
nicnmame :  Mr Blue
age :  30
height :  180
Modified values of global variables :
nicnmame :  Mr Blue Bond
age :  33
height :  185

As you can see in the output, we have used the keyword global within the called function modify_values(), which has allowed us to modify the already defined values of global variables.




Please share this article -





< Prev
Next >
< Python Global Variables
Python Tuple >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement

Notifications



Please check our latest addition

PYTHON


Advertisement