zoukankan      html  css  js  c++  java
  • Python Special Syntax 1: Python的局部变量和全局变量

    #!/usr/bin/python
    # Filename: for.py
    
    for i in range(1, 5):
        print i
    else:
        print 'The for loop is over'

    for循环在这个范围内递归——for i in range(1,5)等价于for i in [1, 2, 3, 4]

    如果包含else,它总是在for循环结束后执行一次,除非遇到break语句。

    关于局部变量:这个绝对让人震惊!

    #!/usr/bin/python
    # Filename: func_local.py
    
    def func(x):
        print 'x is', x
        x = 2
        print 'Changed local x to', x
    
    x = 50
    func(x)
    print 'x is still', x

    结果是:

    x is 50
    Changed local x to 2
    x is still 50

    当然可以使用global关键字:

    #!/usr/bin/python
    # Filename: func_global.py
    
    def func():
        global x
    
        print 'x is', x
        x = 2
        print 'Changed local x to', x
    
    x = 50
    func()
    print 'Value of x is', x

    输出结果为:

    x is 50
    Changed global x to 2
    Value of x is 2

    转自:http://woodpecker.org.cn/abyteofpython_cn/chinese/ch07s04.html

  • 相关阅读:
    绘制程序流程图笔记
    强软弱虚引用
    安全点和安全区域
    垃圾回收算法
    垃圾回收相关算法
    内存访问全过程
    多级页表与快表
    分页
    虚拟内存
    内存分段机制
  • 原文地址:https://www.cnblogs.com/yanyuge/p/3819716.html
Copyright © 2011-2022 走看看