||
a global variable is always defined in the main function while a local one is defined in a non-main function. A global variable can be used in either the main function or the non-main function. However, the local variable can only be used in the defined function and can not be used in other functions.
Example-1
def age():
age1=10
age2=20
Age()
print(age1)
def Age():
age1=20
age2=50
age1=0
age2=1
age()
print(str(age1),str(age2))
---
outPut
10
0 1
Example-2 (the global variable can be used in a local scope if it is not defined in the local scope)
def eggs():
print(egg)
egg=1
eggs()
print(egg)
---outPut
1
1
Example-3 (define a global variable in a local scope function)
def eggs():
global egg
print(egg)
egg=2
egg=1
eggs()
print(egg)
---outPut
1
2
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-10-20 03:22
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社