Python中条件判读语句if的使用详解

在Python中if系列条件语句的一般形式如下所示:(注意一点,python的缩写,python是通过缩写表示同一代码块)

if  condition_1: 
         statement_block_1  
#注意因为python中代码块不像Java等语言使用{}来约束范围,而是使用tab缩进来表示同一个代码块。
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"块语句
Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else,中间elif可以有多个。

注意:
1、每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块,只要是同一个缩进数即可,不建议用tab。
3.if-else,if ,if-elif-else可以嵌套使用
4.if可以单独使用,if-else可以一起使用,if-elif可以一起使用(可以没有else)
  if-elif-else可以一起使用,但是elif必须和if一起使用,不能一起使用。
4、在Python中没有switch – case语句。

案例演示如下:

测试if-elif-else条件语句的代码如下:

#coding=utf-8
score = input("请输入考试分数:")
if int(score) >90 :  #下面两个都是tab缩进,默认一个代码块。
    print ("excellent!")
    print("you  got the best score >90")
 #print("这是缩进测试") #如果在这里随便写一个缩进的话 ,会报错,因为if后面只能跟一个代码块。
elif int(score) >=70 :
    print("good")
    print("you got the good socre 70-90")
elif int(score) >=60 : #注意:下面这两个输出都是5个空格填充,统一缩进,也是默认同一代码块。
          print ("not bad")
          print("you got the so-so score 60-70")
else :
    print("bad socre")
    print ("you ")
print("game over!")  #只要跟最后一个else不是统一代码块的,都算条件外的代码,都会执行。
  #print("hahah") #这样写,肯定报错,因为只要不是条件里的代码块,python要求必须顶格书写代码。

执行结果如下:
请输入考试分数:90
good
you got the good socre 70-90
game over!
-----------------------------
请输入考试分数:60
not bad
you got the so-so score 60-70
game over!

-------------------------------------------------------------------------
if条件语句嵌套使用演示:注意这里子代码块的缩进
-------------------------------------------------------------------------
#coding=utf-8
chePiao = 1  # 用1代表有车票,0代表没有车票
daoLenght = 9  # 刀子的长度,单位为cm

if chePiao == 1:
    print("有车票,可以进站")
    if daoLenght < 10:
        print("通过安检")
        print("终于可以见到Ta了,美滋滋~~~")
    else:
        print("没有通过安检")
        print("刀子的长度超过规定,等待警察处理...")
else:
    print("没有车票,不能进站")
    print("亲爱的,那就下次见了,一票难求啊~~~~(>_<)~~~~")
--------------------------------
代码演示结果:
结果1:chePiao = 1;daoLenght = 20

    有车票,可以进站
    没有通过安检
    刀子的长度超过规定,等待警察处理...
结果2:chePiao = 0;daoLenght = 9

    没有车票,不能进站
    亲爱的,那就下次见了,一票难求啊~~~~(>_<)~~~~

猜你喜欢

转载自blog.csdn.net/qq_26442553/article/details/81414784