Follow this example to create a variable outside functions, and use it inside the functions: MyVariable = 99 #this is a global variable def changeAndPrint_GlobalVariable(): global MyVariable #use global variable in this function with "global" keyword print('Global variable "MyVariable" before changeRead more
Follow this example to create a variable outside functions, and use it inside the functions:
MyVariable = 99 #this is a global variable
def changeAndPrint_GlobalVariable():
global MyVariable #use global variable in this function with "global" keyword
print('Global variable "MyVariable" before change = ', MyVariable) # the global variable is printed
MyVariable = 1 #change the value of the global variable is printed
print('Global variable "MyVariable" after change = ', MyVariable) # the global variable is printed
def changeAndPrint_LocalVariable():
MyVariable = 77 #this is a local variable
print('Local variable "MyVariable" = ', MyVariable) #the local variable is printed
changeAndPrint_GlobalVariable() #call the function
changeAndPrint_LocalVariable() #call the function
This code will print:
Global variable "MyVariable" before change = 99
Global variable "MyVariable" after change = 1
Local variable "MyVariable" = 77
This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Strictly Necessary Cookies
Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.
If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.
3rd Party Cookies
This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.
Keeping this cookie enabled helps us to improve our website.
Please enable Strictly Necessary Cookies first so that we can save your preferences!
How do I use a global variable inside a function using Python?
Follow this example to create a variable outside functions, and use it inside the functions: MyVariable = 99 #this is a global variable def changeAndPrint_GlobalVariable(): global MyVariable #use global variable in this function with "global" keyword print('Global variable "MyVariable" before changeRead more
Follow this example to create a variable outside functions, and use it inside the functions:
This code will print: