globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print(globvar) # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
globalvar = "flower"
def editglobalvar():
global globalvar # accesses the "globalvar" variable, so when we change it
# it won't assign the new value to a local variable,
# not changing the value of the global variable
globalvar = "good" # assigning new value
print(globalvar) # outputs "flower"
# if we didnt use the "global" keyword in the function, it would print out
# "flower"
how to acess global variables within function python
#A global variable can be accessed from any function or method.
#However, we must declare that we are using the global version and not the local one.
#To do this, at the start of your function/method write "global" and then the name of the variable.
#Example:
myVariable = 1
def myFunction():
global myVariable
print(myVariable)
myFunction()
x = 5 #Any variable outside a function is already a global variable
def GLOBAL():
global y #if a variable is inside a function, use the 'global' keyword to make it a global variable
y = 10 # now this variable (y) is global
# Python global variable
# Probably should not use this, just pass in arguments
x = 0 # variable is in outer scope
print(x) # prints x (0)
def use_global_variables():
# if using a global variable, the variable will not need to be mention while calling the function
global x # calling the x variable from a function
x += 1
print(x) # prints x after adding one in the function (1)
use_global_variables
=============================================
# Output:
0
1
#Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)