跳转至

if 语句

if 语句可使程序按照一定条件执行特定语句。

分支控制 #card

  1. if语句后面的条件判断表达式使用 : 结束。
  2. 可以使用elifelse进行组合判断。
  3. else后不能加判断条件。
  4. if语句可以嵌套。 ^1662290197379

if-else

Python 使用if-else进行控制声明。语法如下:

if boolean-expression:
   #statements
else:
   #statements

在每一个 if 程序块中,必须使用相同数量的缩进,否则会产生语法错误。这是 Python 和其他语言非常不同的一点。

现在我们看一个例子:

i = 11
if i % 2 == 0:
    print("偶数")
else:
    print("奇数")

运行结果将根据 i的值发生变化。

if-elif-else #card

当需要判断多个条件,可使用if-elif-else 控制声明。 ^1662390699990

today = "monday"

if today == "monday":
   print("this is monday")
elif today == "tuesday":
   print("this is tuesday")
elif today == "wednesday":
   print("this is wednesday")
elif today == "thursday":
   print("this is thursday")
elif today == "friday":
   print("this is friday")
elif today == "saturday":
   print("this is saturday")
elif today == "sunday":
   print("this is sunday")
else:
   print("something else")

我们可以根据实际需求,添加对应的多个 elif 条件。

分支嵌套

我们可以在 if 声明语句块中嵌套使用 if 声明。例如:

today = "holiday"
bank_balance = 25000
if today == "holiday":
    if bank_balance > 20000:
        print("Go for shopping")
    else:
        print("Watch TV")
else:
    print("normal working day")

三元运算符 #card

true if condition else false

^1662390700000

例如:

def b(a):
    return a+2 if a > 10 else 5

print(b(11), b(4))

上面的代码将输出13 5


最后更新: 2022年10月15日 01:02:48
创建日期: 2022年5月18日 23:06:39
Contributers: yangjh