Answers for "global vs local variables"

3

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
Posted by: Guest on January-07-2021
1

local vs global variables

Local variables:
These variables can be used or exist 
only inside the function. These variables
are not used or referred by any other function.

Global variables:
These variables are the variables which
can be accessed throughout the program.
Global variables cannot be created
whenever that function is called.
Posted by: Guest on January-28-2021

Code answers related to "global vs local variables"

Python Answers by Framework

Browse Popular Code Answers by Language