python中for循环变量作用域及用法详解
在讲这个话题前,首先我们来看一道题:
代码1:
deffoo(): return[lambdax:x**iforiinrange(1,5,2)] print([f(3)forfinfoo()])
伙伴们,你们认为这里产生的结果是什么呢?我们再来看下这题的变体:
代码:2
deffoo(): functions=[] foriinrange(1,5,2): definside_fun(x): returnx**i functions.append(inside_fun) returnfunctions print([f(3)forfinfoo()])
这两题的结果是一样的:都是[27,27]。我相信大部分的伙伴也都会有个疑问,为什么不是[3,27]呢?
这里的就是我们今天要说的for循环中的变量作用域,因为for循环不是一个函数体,所以for循环中的变量i的作用域其实和for循环同级,即类似下面代码
代码3:
deffoo(): i=None foriinrange(1,5,2): pass print(i) foo()#结果为3,即循环结束i的最终值
另外因为python运行到代码行时才会去查找该变量的作用域,所以代码1和代码2中的i值在调用的时候为for循环最终值3,所以结果都是执行x**3。
ps:下面看下python中for循环的用法
Pythonfor循环可以遍历任何序列的项目,如一个列表或者一个字符串。
语法模式:foriterating_varinsequence:
in字面意思,从某个集合(列表等)里顺次取值
#遍历数字序列 the_count=[1,2,3,4,5] fornumberinthe_count: print(f"Thisiscount{number}") 输出结果: Thisiscount1 Thisiscount2 Thisiscount3 Thisiscount4 Thisiscount5 #遍历一维字符串数组 fruits=['apples','oranges','dimes','quarters'] forfruitinfruits: print(f"Afruitoftype:{fruit}") 输出结果为: Afruitoftype:apples Afruitoftype:oranges Afruitoftype:dimes Afruitoftype:quarters #遍历字符串 list_python='python' forjinlist_python: print(f"{j}") 输出结果为: p y t h o n #通过序列索引迭代 elements=[]#列表为空 foriinrange(0,6):#012345 print(f"Adding{i}tothelist.") elements.append(i)#得到elements=[0,1,2,3,4,5] #len(elements)长为6,range(len(elements))==range(6) foriinrange(len(elements)): print(f"Elemnetwas:{i}") 输出结果为: Adding0tothelist. Adding1tothelist. Adding2tothelist. Adding3tothelist. Adding4tothelist. Adding5tothelist. Elemnetwas:0 Elemnetwas:1 Elemnetwas:2 Elemnetwas:3 Elemnetwas:4 Elemnetwas:5
总结
以上所述是小编给大家介绍的python中for循环变量作用域及用法详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。