函数
#内部作用域想修改外部作用域的变量时,就要用到global
>>> num =1
>>> def fun1():
global num #只有用global定义之后内部作用于才可以修改外部作用域的变量
print(num)
num = 123 #内部作用域想修改了外部作用域的变量
print(num)
>>> fun1()
1
123
>>> num #被修改成功
123
如果要修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量则需要 nonlocal 关键字
>>> def outer():
num = 10
def inner():
nonlocal num
num = 100
print(num)
inner()
print(num)
>>> outer()
100
100
str.format() 的用法
>>> for x in range(1,11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site)) # 通过字典设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的 # 通过列表索引设置参数
输出结果为:
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com