【Python】解析Python中的条件语句和循环语句

1.if语句

if语句有好几种格式,好比:python

if condition:
    statement

使用 if ... else ...:函数

if condition:
    statement(1)
else:
    statement(2)

使用 if ... elif ... else ...spa

if condition(1):
    statement(1)
elif condition(2):
    statement(2)
elif condition(3):
    statement(3)
...
else:
    statement

注意:在python语言是没有switch语句的。code

 

2.最简洁的条件语句判断写法

在Python程序中,常常会看见这样的代码。对象

def isLen(strString):
    if len(strString) > 6:
        return True
    else:
        return False

在Python3程序中其实有一种办法能够只用一行代码来实现上述函数:blog

def isLen(strString):
    return True if len(strString) > 6 else False

除了上面这种作法,还有一种方式,也很是简便:递归

def isLen(strString):
    return [False,True][len(strString)>6]

当len(strString)>6为真时,索引值为1,也就返回True。当len(strString)>6为假时,索引值为0,也就返回False。索引

 

3.for语句

和C/C++相比,Python语句中的for语句有很大的不一样,其它语言中的for语句须要用循环变量控制循环。而python语言中的for语句经过循环遍历某一对象来构建循环(例如:元组,列表,字典)来构建循环,循环结束的条件就是对象遍历完成。
for 格式:it

for iterating_var in sequence:
    statements

for ... else ...格式io

for iterating_var in sequence:
    statement1
else:
    statement2

iterating_var:表示循环变量
sequence:表示遍历对象,一般是元组,列表和字典等
statement1:表示for语句中的循环体,它的执行次数就是遍历对象中值的数量
statement2:else语句中的statement2,只有在循环正常退出(遍历完遍历对象中的全部值)时才会执行。

 

4.while语句

while 基本格式:

while condition:
    statements

while ... else ...格式

while condition:
    statement1
else:
    statement2

condition:表示循环判断条件
statement1:表示while中的循环体
statement2:else中的statement2,只有在循环正常退出(condition再也不为真时)后才会执行

 

5.break,continue和pass语句

break 语句的功能是终止循环语句,即便循环条件没有为False或序列尚未被递归完,也会中止执行循环。


continue 语句的功能是跳出本次循环,这和break是有区别的,break的功能是跳出整个循环。经过使用continue语句,能够告诉Python跳过当前循环的剩余语句,而后继续执行下一轮循环。


pass 语句是一个空语句,是来为了保持程序结构的完整性而退出的语句。在python程序中,pass语句不作任何事情,通常只作占位语句。

if condition:
    pass #这是一个空语句,什么也不作
else:
    statement#一些其余的语句