您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
今天小编就为大家带来一篇有关while语法示例的文章。小编觉得挺实用的,为此分享给大家做个参考。一起跟随小编过来看看吧。
练习一,逐一显示指定列表中的所有元素;
//方法一 In [25]: l1 Out[25]: [1, 2, 3, 4] In [26]: while l1: ....: print l1[0] ....: l1.pop(0) ....: 1 2 3 4 //方法二 In [66]: count = 0 In [67]: count Out[67]: 0 In [68]: while count < len(l1): ....: print l1[count] ....: count += 1 ....: 1 2 3 4
练习二,求100以内所有偶数之和;
In [215]: sum = 0; i = 0 In [216]: while i <= 100: .....: i+=1 .....: if i % 2 == 0: .....: sum = sum +i .....: In [217]: print sum 2550
练习三,逐一显示指定字典的所有值,并于显示结果结束后说明总键数;
In [91]: print d1 {'y': 45, 'x': 2, 'z': 90} In [95]: while keylist: ....: print keylist[0] ....: keylist.pop(0) ....: else: ....: print len(d1) ....: y x z 3
练习四,创建一个包含了100以内所有奇数的列表;
In [96]: l1 = [] In [97]: x = 1 In [98]: while x < 100: ....: l1.append(x) ....: x += 2 ....: In [99]: print l1 [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
练习五,逆序逐一显示一个列表的所有元素;
In [34]: l1 = [1,2,3,4] In [35]: while l1: ....: print l1[-1] ....: l1.pop() ....: 4 3 2 1
练习六,列表l1=[0,1,2,3,4,5,6],列表l2=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] ,以第一个列表中的元素为键,以第二个列表中的元素为值生成字典d1;
In [120]: d1={} In [121]: x=0 In [122]: l1=[0,1,2,3,4,5,6] In [123]: l2=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] In [130]: while x < len(l1): d1[l1[x]] = l2[x] x += 1 .....: In [131]: print d1 {0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat'}
关于while语法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果喜欢这篇文章,不如把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。