jack0he的个人博客分享 http://blog.sciencenet.cn/u/jack0he

博文

Python-Note-6-Global and local variables

已有 1967 次阅读 2017-4-11 17:56 |个人分类:Python 笔记|系统分类:科研笔记

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




https://wap.sciencenet.cn/blog-850613-1048229.html

上一篇:Python -Note-5-for-statements
下一篇:Python-note-7-data structure-lists
收藏 IP: 80.101.95.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-30 02:13

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部