函数(三)作用域之变量作用域、函数嵌套中局部函数作用域、默认值参数作用域

一、非嵌套函数下全局变量与局部变量的使用

x=200
>>> def f2():
...     print(x)
...
>>> f2()
200
x=200
>>> def f2():
...     x=100
...     print(x)
...
>>> f2()
100
在函数体外定义的变量,一定是全局变量,例如:
add = "http://c.biancheng.net/shell/"
def text():
    print("函数体内访问:",add)
text()
print('函数体外访问:',add)
运行结果为:
函数体内访问: http://c.biancheng.net/shell/
函数体外访问: http://c.biancheng.net/shell/

在函数体内定义全局变量。即使用 global 关键字对变量进行修饰后,该变量就会变为全局变量。例如:
def text():
    global add
    add= "http://c.biancheng.net/java/"
    print("函数体内访问:",add)
text()
print('函数体外访问:',add)
运行结果为:
函数体内访问: http://c.biancheng.net/java/
函数体外访问: http://c.biancheng.net/java/
>>> x=200
>>> def f2():
...     print(x)
...     x=100
...
>>> f2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in f2
UnboundLocalError: local variable 'x' referenced before assignment

x = 200
def fn():
    print(x)  报错!该步执行不了!
    x += 1    只要在该作用域内赋值定义('='),该作用域内的所有该变量都为局部变量!不管位置在哪
    print(x)
fn()
>>> x=200
>>> def f():
...     x           
...     x=x+1    x没定义
...     print(x)
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in f
UnboundLocalError: local variable 'x' referenced before assignment


x=200
>>> def f():
...     x
...     print(x)
...
>>> f()
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值