How to use global and local variable with function in Python

3 Answers

0 votes
n = 12
 
def f():
    print(n)
    x = 30
    print(x)



f()

print(n)
# print(x) # Error: name 'x' is not defined
   
   
'''
run:
   
12
30
12
   
'''

 



answered Jan 30, 2020 by avibootz
0 votes
n = 12
 
def f():
    x = 30
    print(x)
    n = 1000
    print(n)



f()

print(n)
# print(x) # Error: name 'x' is not defined
   
   
'''
run:
   
30
1000
12
   

 



answered Jan 31, 2020 by avibootz
0 votes
n = 12
 
def f():
    x = 30
    print(x)
    global n
    n = 1000
    print(n)



f()

print(n)
# print(x) # Error: name 'x' is not defined
   
   
'''
run:
   
30
1000
1000
   
'''

 



answered Jan 31, 2020 by avibootz

Related questions

1 answer 221 views
1 answer 258 views
2 answers 175 views
1 answer 152 views
1 answer 152 views
...