您的位置:首页 > 编程语言 > Python开发

Python流程语句:缩进与 if、while、for

2017-10-12 00:00 786 查看
摘要: 对于Python而言代码缩进是一种语法,Python没有像其他语言一样采用{}或者begin…end分隔代码块,而是采用代码缩进和冒号来区分代码之间的层次。

缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。



if[条件] … elif[条件] … else 条件控制语句:执行相应的条件语句。

while [条件] … else 循环控制语句(无边界):当条件为真时,则执行;条件为假,则不执行。

for [条件] … else 循环控制语句(有边界):同While。

break/continue :用于循环控制语句中。break为跳出当前循环,并结束循环;continue为重新进入循环条件判断。

#!/usr/bin/env python
# Filename: expression

running = True
number = int(input('Enter an integer: '))
again = 0

while running:
if number == area:
print 'Congratulations,you number it.' #New block starts here.
print "(but you do not win any prizes!)" #New block ends here.
running = False # this cause the while loop to stop
elif number < area:
print 'No, it is a little higher than that.' #Another block.
# You can do whatever you want in a block ...
number = number + 1
again = again + 1
print 'while running again, this',again,'agains.'
else:
print 'NO, it is a little lower than that.'
# You must have number > aera to reach here.
number = number - 1
again = again + 1
print 'while running again, this',again,'agains.'
else:
print 'The while loop is over.'
# Do anything else you want to do here .

pt = 0
fu = 0
# range(a,b,c).
# a is first print number .
# b is max number , but print number  not eq b .
# c is the print number length .
# eg: print number = a + c , and a =< print number < b .

# break and continue for loop.
for i in range(0,again,1):
pt = pt +1
fu = fu + 2
print 'The' , pt , "print number of 'for loop' is" , i ,'.'
if pt > 3 :
print "The loop of for will end to break stop."
break
elif pt == 3 :
print "The loop of for will end last for again."
continue
else:
print 'The loop of for will end to normal.'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python
相关文章推荐