Python 名称相同的局部变量和全局变量
例子:def spam(): egg = "spam local" print(egg) def bacon(): egg ="bacon local" print(egg) spam() print(egg) egg = "glocal" bacon() print(egg) 局部作用域的
例子:def spam(): egg = "spam local" print(egg) def bacon(): egg ="bacon local" print(egg) spam() print(egg) egg = "glocal" bacon() print(egg) 局部作用域的
例子:def spam(): print(egg) egg =42 spam() print(egg) 在def spam()自定义函数中,没有定义egg的值,在全局域中定义了一个egg=42 ,则局部作用域使用全局域中的值,所以会输出:42 42
例子:def spam(): egg = 99 bacon() print(egg) def bacon(): ham =101 egg = 0 spam() 例子中只输出了spam()的egg,而spam()中引用的bacon()没有输出结果,所以egg = 0属于另一个作用域中的赋值,使用过后就销毁了,如果在结尾在加上print(egg),也会出现报错
例:import random def getAn(answer): if answer == 1: return 'one' elif answer == 2: return 'tow' elif answer == 3: return 'three' elif answer == 4: retur
自定义函数例一:def hello(): print("K") print("J") print("I") print('\n') hello() hello() hello() 例二:def hello(name): print('hello '+name) hello("Alice
例:import syswhile True:print("Type exit to exit.") res = input("请输入:") if res == "exit": sys.exit() print("You type " + res +'.')
例一:导入随机数模块,显示5次1-10中的随机数import random for i in range(1,6): print(random.randint(1,10))