0
Q:

how to declare global variable in python

#it is best not to use global variables in a function
#(pass it as an argument)
a = 'This is global a'
def yourFunction():
    global a
    return a[0:2]
5
global variable
variable = 'whatever'
10
global var1
var1 = 'whatever'
21
a = 0

def testFor():
  global a 
  if(a == 0):
    	#run code
3
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
4
global n
n = 'whatever'
7
a = input('Hello: ')
if a == 'world':
  global b
  b = input('Here')
print b
#Prints the input for be as a result
0
# Python program showing no need to 
# use global keyword for accessing 
# a global value 
  
# global variable 
a = 15
b = 10
  
# function to perform addition 
def add(): 
    c = a + b 
    print(c) 
  
# calling a function 
add() 
0

New to Communities?

Join the community