



条件语句是一种根据条件执行不同代码的语句,如果条件满足则执行一段代码,否则执行其他代码。
Python中条件语句的基本格式如下。
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
说明:上面的条件语句的实现过程如下。
如果“condition_1”为True将执行“statement_block_1”语句块;
如果“condition_1”为False,将判断“condition_2”;
如果“condition_2”为True将执行“statement_block_2”语句块;
如果“condition_2”为False,将执行statement_block_3”语句块。
此外,需要注意:每个条件后面都要使用冒号(:),表示接下来是满足条件后要执行的语句块;使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
【实例4-1】输入考试分数,根据考试分数输出优、良、中、及格和不及格5个等级。
程序代码如下。
score=int(input("please input your score:"))
上面代码首先使用输入函数提示用户输入考试成绩,其次执行下面的条件语句,根据条件进行判断。
if score<60:
print ("考试成绩不及格")
elif score>=60 and score<70:
print ("考试成绩及格")
elif score>=70 and score<80:
print ("考试成绩中")
elif score>=80 and score<90:
print ("考试成绩良")
else:
print ("考试成绩优")
程序运行及实现过程如下图所示。
当然,也可以事先将代码输入一个脚本文件中进行调试和运行。
此外。在条件语句中还可以再嵌套其他的条件语句。基本格式如下。
if 表达式1:
语句1
if 表达式2:
语句2
elif 表达式3:
语句3
else:
语句4
elif 表达式4:
语句5
else:
语句6
使用嵌套时,一定要注意各段代码的缩进行数,确保不同代码块前面的缩进行数一样。