Python的循环机制

本网站用的阿里云ECS,推荐大家用。自己搞个学习研究也不错

<

div id=”content”>For

For 循环相信大家都很熟悉吧,在别的语言里面也经常用的到,而在Python中的用法其实在上一个章节中其实已经涉及到了,这篇文章再继续讲解这个用法,而在其他代码中经常用到的for(i=0;i<10;i++)在Python中使用却是如此简单,废话少说,从代码中去体会用法才是王道。

__author__=”Alex”
__date__ =”$2011-2-17 10:39:27$”
if __name__ == “__main__”:
    print “Hello”;
# declare a list
names = [‘Lu’, ‘Zhang’, ‘Xu’]
# print title before each name
for name in names:
  print( ‘Mr. ‘ + name )
for i in range(1,3):
    print(i)
   
for i in { ‘9.2’:5, ‘wife’:’Viki’ }:
  print( i ) # prints out consecutively: 9.2, wife
d = { ‘9.2’:5, ‘wife’:’Viki’ }
for i in d:
  print( d[i] ) # prints out consecutively: 5, Viki

控制台输出:

Hello
Mr. Lu
Mr. Zhang
Mr. Xu
1
2
9.2
wife
5
Viki

While

While循环在Python中的用法也很Easy,至此为止,我发现Python真的如官网上所说,简单高效清晰

__author__=”Alex”
__date__ =”$2011-2-17 10:39:27$”
if __name__ == “__main__”:
    print “Hello”;
# set the size of a normal drinking glass to standard 0.2 litres
glass_size = 0.2
glasses = int( input(‘How many glasses (0.2 litres) of water have you drunk today? ‘) )
# loop until user has drunk 2 litres
while glasses * glass_size < 2:
  glasses = int( input(‘How many glasses have you drunk now? ‘) )
print ( “That’s at least 2 litres.” )

Console OutPut:

Hello
How many glasses (0.2 l

未经允许不得转载:演道网 » Python的循环机制

赞 (0)
分享到:更多 ()

评论 0

评论前必须登录!

登陆 注册