Python 条件判断教程
Let's dive in!
1. 基本的 if 语句 (if Statement)
在 Python 中,if 语句用来根据条件执行代码块。当条件为 True(真)时,代码块将被执行;否则,代码块会被跳过。
(Here, if is used to execute a block of code when the condition is true.)
示例代码:
age = 20
if age >= 18: # 如果年龄大于等于18(if age is greater than or equal to 18)
print("你已经成年啦!")
2. if-else 语句 (if-else Statement)
当我们需要在条件不满足时执行其他代码,可以使用 else 分支。
(execute an alternative block of code when the condition is false.)
示例代码:
score = 75
if score >= 60: # 如果成绩大于等于60(if score is 60 or above)
print("恭喜你,及格啦!") # 及格时打印(print message on passing)
else:
print("很遗憾,没及格哦!") # 未及格时打印(print message on failing)
3. if-elif-else 语句 (if-elif-else Statement)
当有多个条件需要判断时,使用 elif(else if)可以处理多个分支。
(Use elif to handle multiple conditions.)
示例代码:
temperature = 30
if temperature > 35: # 如果温度大于35度(if temperature is above 35°C)
print("天气太热了!") # 提示天气热(indicate it's too hot)
elif temperature >= 25: # 如果温度在25到35度之间(if temperature is between 25°C and 35°C)
print("天气很舒适!") # 提示天气舒适(indicate it's comfortable)
else:
print("天气比较凉爽。") # 温度低时提示(indicate it's cool)
4. 嵌套条件判断 (Nested Conditional Statements)
有时,我们需要在一个条件语句中再嵌套其他条件。
(Sometimes, nested conditions are required within an if statement.)
示例代码:
number = 8
if number > 0: # 判断数字是否大于0(if the number is positive)
if number % 2 == 0: # 判断是否为偶数(if it is even)
print("正偶数!") # 正偶数提示(print message for positive even number)
else:
print("正奇数!") # 正奇数提示(print message for positive odd number)
else:
print("非正数。") # 负数或零提示(print message for non-positive number)
5. 逻辑运算符:and、or、not (Logical Operators: and, or, not)
条件判断中,我们经常需要结合多个条件。Python 提供了三种逻辑运算符:
(When combining multiple conditions, Python provides logical operators.)
- and(并且): 当所有条件都为 True 时,整体表达式为 True。
(Returns True if both conditions are true.) - or(或者): 当至少一个条件为 True 时,整体表达式为 True。
(Returns True if at least one condition is true.) - not(非): 用于取反,将 True 变为 False,反之亦然。
(Negates the truth value.)
示例代码:
age = 22
has_ticket = True
if age >= 18 and has_ticket: # 年龄大于等于18并且有票(if age is at least 18 and has a ticket)
print("欢迎入场!") # 满足条件欢迎入场(welcome message)
else:
print("入场条件不满足。") # 条件不满足提示(display error message)
6. 条件表达式(Conditional Expressions / Ternary Operator)
Python 还支持单行条件表达式,可以让代码更加简洁。
(one-line conditional expressions for concise code.)
示例代码:
result = "及格" if score >= 60 else "不及格" # 条件表达式(ternary operator)
print(result) # 输出结果
★ 注意事项 (Tips & Caveats for Conditional Statements)
- 缩进非常关键 (Indentation Matters)
Python 使用缩进来标识代码块,缩进不当会导致语法错误或逻辑错误。 - 正确使用比较运算符 (Comparison Operators)
使用 == 进行相等判断,而不是 =(= 用于赋值)。
注意区分 is 和 ==。is 用于判断两个对象是否为同一个对象,而 == 判断的是值是否相等。
a = [1, 2, 3] b = [1, 2, 3]
print(a == b) # True,因为值相同
print(a is b) # False,因为是不同的对象
- 条件表达式的书写习惯 (Style in Conditional Expressions)
- 当条件较复杂时,建议使用括号明确表达式的优先级,以避免歧义。
- 切勿误写为 if a == b or c:,正确写法应为 if a == b or a == c:(或使用括号明确优先级)。
- 提示:对于多个条件,逻辑运算符 and、or 的组合一定要注意各条件之间的关系。
- 短路求值(Short-Circuit Evaluation)
- 在使用 and 和 or 时,Python 会进行短路求值:
- and 会在遇到第一个为 False 的条件时停止求值。
- or 会在遇到第一个为 True 的条件时停止求值。
- 条件中的非布尔值 (Non-Boolean Values in Conditions)
- Python 会自动将非布尔值转换为布尔值。
- 比如,空字符串 ""、空列表 []、数字 0 都会被视为 False;
非空的字符串、列表、非零数字被视为 True。
value = ""
if value: # 空字符串会被当作 False
print("非空")
else:
print("空字符串") # 正确输出:空字符串
- 避免过于复杂的条件判断 (Avoid Overly Complex Conditions)
- 当条件判断逻辑过于复杂时,可以考虑拆分成多个简单的判断,或使用函数来封装判断逻辑,从而提高代码可读性与维护性。
- 建议:编写清晰、易懂的条件判断不仅能减少 bug,也能让其他开发者更快理解你的代码。
7. 总结与拓展
通过以上示例,我们了解了 Python 中常见的条件判断语句:
- if 语句(Basic decision-making)
- if-else 语句(Binary decisions)
- if-elif-else 语句(Multiple conditions)
- 嵌套条件判断(Nested conditions)
- 逻辑运算符(Logical operators)
- 条件表达式(Ternary operator)
这些知识点构成了 Python 程序中不可或缺的部分,为你的编程逻辑打下坚实的基础。记住,多练习,多尝试,你会发现条件判断让你的代码充满了无限可能!
如果你觉得这篇教程对你有帮助,别忘了点赞、分享并关注我哦~ 让我们一起在 Python 的世界里不断探索与成长!
Happy coding!