x = 3 if x > 5: print("x is greater than 5") else: print("x is not greater than 5")
输出:
1
x isnotgreater than5
if-elif-else 语句
if-elif-else 语句用于处理多个条件分支。
1 2 3 4 5 6 7
x = 10 if x > 10: print("x is greater than 10") elif x == 10: print("x is equal to 10") else: print("x is less than 10")
输出:
1
x isequalto10
多个 elif 语句
你可以使用多个 elif 语句来处理更多的条件分支。
1 2 3 4 5 6 7 8 9
x = 15 if x > 20: print("x is greater than 20") elif x > 15: print("x is greater than 15 but not greater than 20") elif x == 15: print("x is equal to 15") else: print("x is less than or equal to 15")
输出:
1
x isequalto15
嵌套 if 语句
if 语句可以嵌套使用,形成多层条件判断。
1 2 3 4 5 6 7 8 9 10
x = 10 y = 5
if x > 5: if y > 3: print("Both conditions are true") else: print("First condition is true, second is false") else: print("First condition is false")
输出:
1
Both conditions aretrue
布尔表达式
在 if 语句中,布尔表达式可以包含以下运算符:
比较运算符:==, !=, <, >, <=, >=
逻辑运算符:and, or, not
成员运算符:in, not in
身份运算符:is, is not
示例
1 2 3 4 5
x = 10 y = 5
if x > 5and y > 3: print("Both conditions are true")
输出:
1
Both conditions aretrue
使用 not 运算符
1 2 3
x = 10 ifnot x > 15: print("x is not greater than 15")
输出:
1
x isnotgreater than15
成员运算符
1 2 3
fruits = ["apple", "banana", "cherry"] if"banana"in fruits: print("Banana is in the list")
输出:
1
Banana isin the list
身份运算符
1 2 3 4 5 6 7 8
a = [1, 2, 3] b = a c = [1, 2, 3]
if a is b: print("a and b are the same object") if a isnot c: print("a and c are different objects")
输出:
1 2
a and b are the same object a and c are different objects
Python While 循环简介
在编程中,循环结构用于重复执行一段代码,直到满足特定条件为止。Python 提供了两种主要的循环结构:for 循环和 while 循环。