Answers for "global and local variables in python"

4

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
11

python access global variable

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1
Posted by: Guest on August-14-2020
4

how to set global variable in python function

#A global variable can be accessed from the hole program.

global var = "Text"
Posted by: Guest on August-05-2021
4

how to make a variable global in python

x = 5 #Any variable outside a function is already a global variable

def GLOBAL():
	global y #if a variable is inside a function, use the 'global' keyword to make it a global variable
    y = 10 # now this variable (y) is global
Posted by: Guest on May-04-2021
0

global python variablen

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)
Posted by: Guest on May-27-2021
-2

how to global variables in python

def Takenin():
  global ans 
  ans = "This is the coorect way to do it"

def Return():
    Takenin()
    print(f"ans :{ans}")
Posted by: Guest on April-07-2021

Code answers related to "global and local variables in python"

Python Answers by Framework

Browse Popular Code Answers by Language