Python Global Variables & Assign Multitple Values


Assigning multiple values to python variables :-

In python you can assign multiple values within same line.

following examples show how you can assign multiple, single and unpack values in python.

Run the code to see the output

# Assign multiple values to multiple python variables
a, b, c = "I", "Love", "Python"

print(a, b, c)

# Assign same value to multiple python variables
a, b, c = "I Love Python"

print(a, b, c)

#Unpack list of values
letters = ["I", "Love", "Python"]
a, b, c = letters

print(a, b, c)

In First one we are assigning multiple values to its corresponding variables, starting from left to right

In Second example single value to multiple variables

Then finally we have list of values assign to single variable, that single variable been unpacked by equal number of values.


Python global variables :-

In Python, global variables are those declared outside of any function or class and can be accessed from anywhere within the code.

They maintain their value throughout the execution of the program unless modified explicitly.

# Define a global variable
global_var = 10

def my_function():
    # Access the global variable
    print("Inside function:", global_var)

# Call the function
my_function()

In the same example if we re-assign value to global_var inside the function, it become local variable

# Define a global variable
global_var = 10

def my_function():
    # Access the global variable, become local variable
    global_var = 20
    print("Inside function:", global_var)

# Call the function
my_function()

# Access the global variable outside the function
print("Outside function:", global_var)


Global keyword :-

The global keyword in Python is used to declare a variable inside a function as a global variable. This means that the variable can be accessed and modified from outside the function as well.

def my_function():
    global x
    x = 10

my_function()

print(x)