xxxxxxxxxx
# Define a global variable
my_global_var = "Hello, world!"
# Access the global variable
print(my_global_var)
# Modify the global variable
my_global_var = "Updated value"
# Access the modified global variable
print(my_global_var)
xxxxxxxxxx
# 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
xxxxxxxxxx
def my_function():
global my_variable
my_variable = 10
my_function()
print(my_variable) # Output: 10
xxxxxxxxxx
def f():
global s
print(s)
s = "Zur Zeit nicht, aber Berlin ist auch toll!"
print(s)
s = "Gibt es einen Kurs in Paris?"
f()
print(s)
xxxxxxxxxx
#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)
xxxxxxxxxx
x = "global"
def foo():
print("x inside:", x)
foo()
print("x outside:", x)
xxxxxxxxxx
def my_function():
global my_variable
my_variable = 10
# Accessing the global variable
print(my_variable)
xxxxxxxxxx
def my_function():
global my_variable
my_variable = 10
my_function()
print(my_variable) # Output: 10