Using Global Variable in a Function in Python

Source code :

# Set a Value to global variable
Power = '100%'

# Create a function to use global variable
def func():
    global Power

    print('Power is', Power)
# Change global variable value
    Power = '50%'
    print('Changed global Power to', Power)

print('Value of Power is', Power)

Output :

Power is 100%
Changed global Power to 50%
Value of Power is 50%

Notes :

  • If a varible declared outside a function, it is called global variable. And within a function is called Local Variable.
  • Functions cannot access the global variable if they are not set as global.

Output :


Comments :