1. if 语句:
# 示例 1
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
# 示例 2
x = 5
if x > 0:
print("x is positive.")
elif x == 0:
print("x is zero.")
else:
print("x is negative.")
2. and、or、not 运算符:
# 使用 and 运算符
name = "Alice"
age = 25
if name == "Alice" and age == 25:
print("Alice is 25 years old.")
# 使用 or 运算符
city = "New York"
if city == "New York" or city == "Los Angeles":
print("You are in a major city.")
# 使用 not 运算符
is_adult = True
if not is_adult:
print("You are a minor.")
3. in 和 not in 运算符:
# 使用 in 运算符
fruits = ["apple", "banana", "orange"]
if "banana" in fruits:
print("Banana is in the list.")
# 使用 not in 运算符
if "grape" not in fruits:
print("Grape is not in the list.")
4. 三元运算符:
# 三元运算符
x = 10
y = 20
result = x if x > y else y
print(result)
5. pass 语句:
在 Python 中,如果你希望有一个空的代码块,可以使用 pass 语句占位。
x = 5
if x > 0:
pass # 此处可以是空代码块,防止语法错误
else:
print("x is not positive.")
条件语句允许你根据不同的条件执行不同的代码块。通过理解这些基本的条件语句结构,你可以更好地进行逻辑控制和决策流程的编程。
转载请注明出处:http://www.zyzy.cn/article/detail/13314/Python 基础