Python基础学习之IF控制流

📅 2026/7/28 14:46:08
Python基础学习之IF控制流
判断语句基本用法判断基于一定的条件决定是否要执行特定的一段代码例如判断一个数是不是正数x0.5ifx0:printHey!printx is positiveHey! x is positive在这里如果x 0为False那么程序将不会执行两条print语句。虽然都是用if关键词定义判断但与CJava等语言不同Python不使用{}将if语句控制的区域包含起来。Python使用的是缩进方法。同时也不需要用()将判断条件括起来。上面例子中的这两条语句printHey!printx is positive就叫做一个代码块同一个代码块使用同样的缩进值它们组成了这条if语句的主体。不同的缩进值表示不同的代码块例如x 0时x0.5ifx0:printHey!printx is positiveprintThis is still part of the blockprintThis isnt part of the block, and will always print.Hey! x is positive This is still part of the block This isnt part of the block, and will always print.x 0时x-0.5ifx0:printHey!printx is positiveprintThis is still part of the blockprintThis isnt part of the block, and will always print.This isnt 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下面的语句。对于上面的例子进行扩展x0ifx0:printx is positiveelifx0:printx is zeroelse:printx is negativex is zeroelif的个数没有限制可以是1个或者多个也可以没有。else最多只有1个也可以没有。可以使用andor,not等关键词结合多个判断条件x10y-5x0andy0Truenotx0Falsex0ory0True这里使用这个简单的例子假如想判断一个年份是不是闰年按照闰年的定义这里只需要判断这个年份是不是能被4整除但是不能被100整除或者正好被400整除year1900ifyear%4000:printThis is a leap year!# 两个条件都满足才执行elifyear%40andyear%100!0:printThis is a leap year!else:printThis is not a leap year.This is not a leap year.值的测试Python不仅仅可以使用布尔型变量作为条件它可以直接在if中使用任何表达式作为条件大部分表达式的值都会被当作True但以下表达式值会被当作FalseFalseNone0空字符串空列表空字典空集合mylist[3,1,4,1,5,9]ifmylist:printThe first element is:,mylist[0]else:printThere is no first element.The first element is: 3修改为空列表mylist[]ifmylist:printThe first element is:,mylist[0]else:printThere is no first element.There is no first element.当然这种用法并不推荐推荐使用if len(mylist) 0:来判断一个列表是否为空。