local and global variable python code example

Example 1: global vs local variables

# in functions we use Global vs Local variables
# Global means as the name suggests it's Global (accessed anywhere in file)

def player_health():
  # Local variable 
  # Local variables can't be accessed outside of a function
  player_health = 78
  
# error
print(player_health)


# Global Variables
player_strength = 2
def increase_strength():
	player_strength = 3		# this will give you an error because the player_strength
    # is defined in the global scope so you can't modify it in a function
    
    # if you try to print the global variable in function you can do it
    print(player_strength)
    
# Local
	# only accessed/edited by the functions only
# Global
	# accessed/edited in global level not in functions
    # only accessed by functions but not editable
    
# if you got something by this example please upvote it

Example 2: global var in python

a = input('Hello: ')
if a == 'world':
  global b
  b = input('Here')
print b
#Prints the input for be as a result