Python基础学习之IF控制流
判断语句
基本用法
判断,基于一定的条件,决定是否要执行特定的一段代码,例如判断一个数是不是正数:
x=0.5ifx>0:print"Hey!"print"x is positive"Hey! x is positive在这里,如果x > 0为False,那么程序将不会执行两条print语句。
虽然都是用if关键词定义判断,但与C,Java等语言不同,Python不使用{}将if语句控制的区域包含起来。Python使用的是缩进方法。同时,也不需要用()将判断条件括起来。
上面例子中的这两条语句:
print"Hey!"print"x is positive"就叫做一个代码块,同一个代码块使用同样的缩进值,它们组成了这条if语句的主体。
不同的缩进值表示不同的代码块,例如:
x > 0时:
x=0.5ifx>0:print"Hey!"print"x is positive"print"This is still part of the block"print"This isn't part of the block, and will always print."Hey! x is positive This is still part of the block This isn't part of the block, and will always print.x < 0时:
x=-0.5ifx>0:print"Hey!"print"x is positive"print"This is still part of the block"print"This isn't part of the block, and will always print."This isn't part of the block, and will always print.在这两个例子中,最后一句并不是if语句中的内容,所以不管条件满不满足,它都会被执行。
一个完整的if结构通常如下所示(注意:条件后的:是必须要的,缩进值需要一样):
if <condition 1>: <statement 1> <statement 2> elif <condition 2>: <statements> else: <statements>当条件1被满足时,执行if下面的语句,当条件1不满足的时候,转到elif,看它的条件2满不满足,满足执行elif下面的语句,不满足则执行else下面的语句。
对于上面的例子进行扩展:
x=0ifx>0:print"x is positive"elifx==0:print"x is zero"else:print"x is negative"x is zeroelif的个数没有限制,可以是1个或者多个,也可以没有。
else最多只有1个,也可以没有。
可以使用and,or,not等关键词结合多个判断条件:
x=10y=-5x>0andy<0Truenotx>0Falsex<0ory<0True这里使用这个简单的例子,假如想判断一个年份是不是闰年,按照闰年的定义,这里只需要判断这个年份是不是能被4整除,但是不能被100整除,或者正好被400整除:
year=1900ifyear%400==0:print"This is a leap year!"# 两个条件都满足才执行elifyear%4==0andyear%100!=0:print"This is a leap year!"else:print"This is not a leap year."This is not a leap year.值的测试
Python不仅仅可以使用布尔型变量作为条件,它可以直接在if中使用任何表达式作为条件:
大部分表达式的值都会被当作True,但以下表达式值会被当作False:
- False
- None
- 0
- 空字符串,空列表,空字典,空集合
mylist=[3,1,4,1,5,9]ifmylist:print"The first element is:",mylist[0]else:print"There is no first element."The first element is: 3修改为空列表:
mylist=[]ifmylist:print"The first element is:",mylist[0]else:print"There is no first element."There is no first element.当然这种用法并不推荐,推荐使用if len(mylist) > 0:来判断一个列表是否为空。
