python条件语句怎么使用
原创Python条件语句的使用
在Python中,条件语句用于基于不同的条件执行不同的代码块。核心的条件语句包括if
,elif
和else
。
1. 基本的if语句
一个基本的if语句结构如下:
if condition:
# 执行的代码块
例如,检查一个数是否大于0:
num = 10
if num > 0:
print("num is greater than 0")
2. if-else语句
if-else语句允许在条件不满足时执行另一段代码块:
if condition:
# 条件为真时执行的代码块
else:
# 条件为假时执行的代码块
例如,判断一个数是正数、负数还是零:
num = 0
if num > 0:
print("num is positive")
else:
if num < 0:
print("num is negative")
else:
print("num is zero")
3. if-elif-else语句
if-elif-else语句允许在多个条件中选择一个执行:
if condition1:
# condition1为真时执行的代码块
elif condition2:
# condition2为真时执行的代码块
else:
# 所有条件都不真时执行的代码块
例如,判断一个数属于哪个区间:
num = 15
if num < 0:
print("num is negative")
elif 0 <= num < 10:
print("num is between 0 and 10")
elif 10 <= num < 20:
print("num is between 10 and 20")
else:
print("num is greater than or equal to 20")
这些就是Python中条件语句的基本使用方法。