【零基础学Python】条件语句

139 阅读2分钟
Python条件语句是通过一条或者多条语句的执行结果(True或者False)来决定执行的代码块。
可以通过下图来简单了解一下条件语句的执行过程:

Python程序语言指定任何非0和非空(null)值为true,0或者null为false。

if关键字

条件语句中最常见的类型就是if关键字。
一条if语句可以理解为“如果满足此条件,则执行该子句中的代码”
在Python中,一条if语句包含以下内容:
  • if关键字
  • 条件(即等于True或者False的表达式)
  • 冒号(:)
  • 从下一行开始,一个缩进的代码块(称为if子句)
例如:

if name == 'alex':
    print('he is alex!')
意思是如果name为alex,则输出he is alex!。

else关键字

一个if子句后可回忆选择性的加上else关键字。该else子句仅仅在if语句的条件为False时执行。
一条else语句可以理解为“如果满足此条件,则执行此代码。否则,执行该代码。”
在Python中,一条else语句包含以下内容:
  • else关键字
  • 冒号(:)
  • 从下一行开始,一个缩进的代码块(称为else子句)
例如:

if name == 'alex':
    print('he is alex!') 
else:
    print('he is not alex!')
意思是如果name为alex,则输出he is alex! 否则,输出he is not alex!’。

elif关键字

虽然只有if 或者 else子句之一可以执行,但是可能需要执行许多可能的子句。
该elif语句是“else if”语句,始终跟随一个if或者另一个elif语句,它提供了仅在所有先前条件都为False的时候才检查的另一个条件。
在Python中,一条elif语句包含以下内容:
  • elif关键字
  • 条件(即等于True或者False的表达式)
  • 冒号(:)
  • 从下一行开始,一个缩进的代码块(称为elif子句)
例如:

if name == 'alex':
    print('he is alex!') 
elif age < 10:
    print('he is not alex,he is bob!')
意思是如果name为alex,则输出he is alex!,如果name不为alex并且age小于10,则输出he is not alex,he is bob。

在实际的项目中,一般会在最后一条语句之后添加else语句,因为它保证了条件语句中至少一个(且仅一个)将被执行。下面展示一下使用if,elif和else语句一起使用的示例:

if name == 'alex':
    print('he is alex!') 
elif age < 10:
    print('he is not alex,he is bob!') 
else:
    print('he is not alex,he is not bob!')
意思是如果name为alex,则输出he is alex!,如果name不为alex并且age小于10,则输出he is not alex,he is bob,除了以上两种其他外,其他情况则输出he is not alex,he is not bob! 

参考文档:automatetheboringstuff.com/