文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>python_控制流

python_控制流

时间:2011-05-27  来源:邵国宝

1.if语句

#!/usr/bin/python
#
Filename: if.py
number = 23
guess
= int(raw_input('Enter an integer:'))

if guess == number:
print 'Congratulations, you guessed it' #New block starts here
print '(but you do not win any prizes!)'#New block ends here
elif guess > number:
print 'No, it is a little higher than that.'#Another block
else:
print 'No, it is a little lower than that.'
print 'Done'
#This last statement is always executed, after the if statement is executed

python中没有switch语句,可以使用if..elif..else语句来完成同样的工作。

2.while语句

#!/usr/bin/python
#
Filename:while.py
number = 23
running
= True

while running:
guess
= int(raw_input('Enter an integer:'))

if guess == number:
print 'Congratulations,you guessed it. '
print 'but you do not win any prizes.'
running
= False #this cause the while loop to stop
elif guess < number:
print 'No, it is a little lower than that'
print 'try again'
else:
print 'No, it is a little higher than that'
print 'try again'
else:
print 'The while loop is over.'
#Do anything else you want to do here
print 'Done.'

python 中while可以和else连用

3.for循环

#!/usr/bin/python
#
Filename: for.py

for i in range(1, 5):
print i
else:
print 'The for loop is over'

for i in range(1,5)相当于 for i in range [1,2,3,4],即是在c/c++中的 for (int i = 0; i < 5; i++)。

同样,for也可以和else连用,else为可选部分

4.break语句

#!/usr/bin/python
#
Filename: break.py

while True:
s
= raw_input('Enter something:')
if s == 'quit':
break;
print 'Length of the string is', len(s)
print 'Done'

break跳出for或者while循环之后,不执行与while或者for配套的else(这个比较容易理解)

5.continue语句

#!/usr/bin/python
#
Filename: break.py

while True:
s
= raw_input('Enter something:')
if s == 'quit':
break;
print 'Length of the string is', len(s)
print 'Done'
continue对for语句同样适用

我们已经学习了如何使用三种控制流语句——if、while和for以及与它们相关的break和continue语句。它们是Python中最常用的部分,熟悉这些控制流是应当掌握的基本技能。

接下来,我们将学习如何创建和使用函数
相关阅读 更多 +
排行榜 更多 +
耶小兔子2

耶小兔子2

休闲益智 下载
nba2k20豪华版

nba2k20豪华版

体育竞技 下载
画线征服火柴人安卓版

画线征服火柴人安卓版

动作格斗 下载