python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。

一般形式如下所示:

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else。

注意:

  • 每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
  • 使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
  • 在Python中没有switch – case语句。

if 嵌套

在嵌套 if 语句中,可以把 if...elif...else 结构放在另外一个 if...elif...else 结构中。

if 表达式1:
    语句
    if 表达式2:
        语句
    elif 表达式3:
        语句
    else:
        语句
elif 表达式4:
    语句
else:
    语句

三目表达式

一般形式为:

val = a if 条件成立 else b

举例:

# 打印出两个数中的大者
print(x if(x>y) else y)

相关文章:

  • 2022-12-23
  • 2021-11-10
  • 2021-09-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-30
  • 2021-08-26
  • 2022-12-23
  • 2022-01-07
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案