神奇的缩进

上一篇 / 下一篇  2011-03-02 21:17:09 / 个人分类:python

false:

    def func_outer():
        x = 2
        print('x is',x)
        def func_inner():
            nonlocal x
            x = 5
            func_inner()
            print('Changed local x to',x)
    func_outer()

output:null

 

right:

def func_outer():
    x = 2
    print('x is',x)
    def func_inner():
        nonlocal x
        x = 5
    func_inner()
    print('Changed local x to',x)
func_outer()

output:

>>>
x is 2
Changed local x to 5
>>>

func_global

def func_outer():
    x = 2
    print('x is',x)
    def func_inner():
        global x#nonlocal x
        x = 5
    func_inner()
    print('Changed local x to',x)
func_outer()

output:

>>>
x is 2
Changed local x to 2
>>>


TAG:

werm520的个人空间 引用 删除 werm520   /   2011-03-08 21:24:48
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)
   
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.
werm520的个人空间 引用 删除 werm520   /   2011-03-08 15:55:38
print语法
for……in……语法
 

评分:0

我来说两句

Open Toolbar