python 全局变量与局部变量、函数递归
程序员文章站
2023-12-21 20:47:28
...
局部变量 全局变量
x = 3
y = 2 * x + 1
print(y)
name = 'sss'
def change_name():
global name # 修改全局变量
name = '帅'
print('change_name', name)
change_name()
print(name)
变量私有化只能是函数
name = 'kkk'
def change_name():
name1 = '帅'
name2 = '酷'
name3 = '美'
print('change_name', name1)
change_name()
print(name)
_global
name = 'ski'
def ssdf():
global name
name = '帅'
print('sdd', name)
def qio():
print('sdd', name)
qio()
ssdf()
如果函数内 无global关键字 优先读取局部变量,无局部变量读取全局变量,
不能重新赋值 对于可变对象可以进行内不元素进行操作
如果函数中有global关键字 可以读取或者重新给全局变量赋值
name = ['sdsd', 'sbsb']
def usus():
# global name
# name = 'sda'
name.append('sdwwww')
print('局部变量', name)
usus()
print(name)
全局变量全部大写,局部变量一律小写
NAME = 'OIU'
def oness():
name = 'poi'
print(name)
def twos():
name = 'lu'
print(name)
def threes():
name = 'iss'
print(name)
print(name)
threes()
twos()
print(name)
oness()
name = 'one'
def oness():
name = 'on1'
def twoss():
global name
name = 'two'
twoss()
print(name)
print(name)
oness()
print(name)
name = 'one'
def oness():
name = 'on1'
def twoss():
nonlocal name #修改上一级 变量
name = 'two'
twoss()
print(name)
print(name)
oness()
print(name)
风湿理论之函数即变量
def foo():
print('from foo')
bar()
foo()
def bar():
print('from bar')
def foo():
bar()
print('from foo')
def foo():
print('from foo')
bar()
def bar():
print('from bar')
foo()
风湿理论
函数即变量
name = '海风'
def huanwei():
name = '黄伟'
print(name)
def liuyang():
name = '刘洋'
print(name)
def nulige():
name = '胡志华'
print(name)
print(name)
nulige()
liuyang()
print(name)
print(name)
huanwei()
print(name)
函数递归 占用内存
def calc(n):
print(n)
calc(n)
calc(10)
一定要有一个指定的结束条件
没进入一层递归是,应该比上一次规模减少
递归效率不高 递归次数太多会导致栈的溢出
def calc(n):
print(n)
if int(n / 2) == 0:
return n
return calc(int(n / 2))
calc(10)
person_list = ['alex', 'wupeiqi', 'yuanhao', 'linhaifeng']
def ask_way(person_list):
if len(person_list) == 0:
return '没人知道'
person = person_list.pop(0)
if person == 'linhaifeng':
return '找到地址'
print('继续问下一个')
res = ask_way(person_list)
return res
way = ask_way(person_list)
print(way)
推荐阅读
-
python 全局变量与局部变量、函数递归
-
《Python 3》--三引号、math模块、cmath模块、日期和时间、转义字符、字符串运算符、字符串格式化、函数、全局变量和局部变量、匿名函数(lambda))
-
函数应用之参数、局部变量和全局变量、匿名函数
-
js函数,局部变量,全局变量,和重载的问题
-
javascript函数之局部变量和全局变量
-
python global函数/全局变量/局部变量
-
【C++实现python字符串函数库】二:字符串匹配函数startswith与endswith
-
详解Python的Lambda函数与排序
-
Python匿名函数/排序函数/过滤函数/映射函数/递归/二分法
-
Python3基础教程之递归函数简单示例