Objectives 学习目标
- To understand simple decision pattern using
ifstatements 理解使用if语句的简单决策模式 - To understand two-way decision pattern using
if-elsestatements 理解使用if-else语句的双向决策模式 - To understand multi-way decision pattern using
if-elif-elsestatements 理解使用if-elif-else语句的多向决策模式 - To understand exception handling and write error-catching code 理解异常处理并编写错误捕获代码
- To understand Boolean expressions and the
booldata type 理解布尔表达式和布尔数据类型 - To implement algorithms with decision structures 实现带有决策结构的算法
Control Structures 控制结构
- Sequential structure顺序结构: Linear execution 线性执行
- Decision structures决策结构: Conditional execution 条件执行
- Loops循环: Repetitive execution 重复执行
Simple Decisions 简单决策
if Statement if语句
if <condition>:
<body>One-way decision单向决策: The body either executes or not 主体要么执行要么不执行
Example: Temperature Warnings 示例:温度警告
# Modified temperature conversion with warnings
celsius = float(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees Fahrenheit.")
# Print warnings if needed
if fahrenheit > 90:
print("It's really hot out there. Be careful!")
if fahrenheit < 30:
print("Brrrrr. Be sure to dress warmly!")Forming Simple Conditions 形成简单条件
Relational Operators 关系运算符
<expr> <relop> <expr>Relational operators关系运算符:
==: Equal to 等于!=: Not equal to 不等于<: Less than 小于<=: Less than or equal to 小于等于>: Greater than 大于>=: Greater than or equal to 大于等于
Compound Conditions 复合条件
# Leap year condition 闰年条件
year % 4 == 0 and year % 100 != 0 or year % 400 == 0
# Equivalent with parentheses 带括号的等价形式
(year % 4 == 0 and year % 100 != 0) or year % 400 == 0Conditional Program Execution 条件程序执行
__name__ Variable __name__变量
- When module is imported模块被导入时:
__name__= module name 模块名 - When run directly直接运行时:
__name__='__main__'
Standard Practice 标准实践
if __name__ == '__main__':
main()Purpose目的: Prevent code execution when imported 防止导入时执行代码
Two-Way Decisions 双向决策
if-else Statement if-else语句
if <condition>:
<statements>
else:
<statements>Example: Quadratic Equation 示例:二次方程
import math
def main():
print("This program finds the real solutions to a quadratic\n")
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
discrim = b * b - 4 * a * c
if discrim >= 0:
discRoot = math.sqrt(discrim)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print("\nThe solutions are:", root1, root2)
else:
print("\nThe equation has no real roots!")Multi-Way Decisions 多向决策
if-elif-else Statement if-elif-else语句
if <condition1>:
<case1 statements>
elif <condition2>:
<case2 statements>
elif <condition3>:
<case3 statements>
...
else:
<default statements>Improved Quadratic Solver 改进的二次方程求解器
import math
def main():
print("This program finds the real solutions to a quadratic\n")
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
discrim = b * b - 4 * a * c
if discrim < 0:
print("\nThe equation has no real roots!")
elif discrim == 0:
root = -b / (2 * a)
print("\nThere is a double root at:", root)
else:
discRoot = math.sqrt(discrim)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print("\nThe solutions are:", root1, "and", root2)Exception Handling 异常处理
try-except Statement try-except语句
try:
<body>
except <ErrorType>:
<handler>Common Exception Types 常见异常类型
AttributeError: Accessing unknown object attribute 访问未知对象属性IndexError: Index out of sequence range 索引超出序列范围KeyError: Looking up non-existent dictionary key 查找不存在的字典键NameError: Accessing non-existent variable 访问不存在的变量OSError: Operating system errors (e.g., file not found) 操作系统错误SyntaxError: Python syntax errors Python语法错误TypeError: Invalid operations between types 类型间无效操作ZeroDivisionError: Division by zero 除以零
Multiple Exception Handling 多重异常处理
try:
# Code that might cause errors 可能引发错误的代码
filename = "tryexcept.txt"
f = open(filename, 'r')
dividend = float(f.readline())
divisor = float(f.readline())
result = dividend / divisor
print("Result:", result)
except FileNotFoundError:
print("Error: File not found!")
except ZeroDivisionError:
print("Error: Division by zero!")
except Exception as e:
print("An unexpected error occurred:", e)
finally:
# Cleanup code 清理代码
if 'f' in locals() and not f.closed:
f.close()Exception Objects 异常对象
try:
# Risky code 有风险的代码
x = 1 / 0
except ZeroDivisionError as e:
print("Error type:", type(e).__name__)
print("Error message:", str(e))Study in Design: Max of Three 设计研究:三个数的最大值
Strategy 1: Compare Each to All 策略1:逐个比较所有
def max_of_three_v1(x1, x2, x3):
if x1 >= x2 and x1 >= x3:
return x1
elif x2 >= x1 and x2 >= x3:
return x2
else:
return x3
# Testing
print(max_of_three_v1(5, 2, 4)) # 5
print(max_of_three_v1(1, 8, 3)) # 8
print(max_of_three_v1(2, 2, 9)) # 9Weakness弱点: Becomes complex with more numbers 数字越多越复杂
Strategy 2: Decision Tree 策略2:决策树
def max_of_three_v2(x1, x2, x3):
if x1 >= x2:
if x1 >= x3:
return x1
else:
return x3
else:
if x2 >= x3:
return x2
else:
return x3Strategy 3: Sequential Processing 策略3:顺序处理
def max_of_three_v3(x1, x2, x3):
max_val = x1
if x2 > max_val:
max_val = x2
if x3 > max_val:
max_val = x3
return max_val
# General version for n numbers n个数的通用版本
def max_of_n(numbers):
max_val = numbers[0]
for num in numbers[1:]:
if num > max_val:
max_val = num
return max_valStrategy 4: Use Python Built-in 策略4:使用Python内置函数
def max_of_three_v4(x1, x2, x3):
return max(x1, x2, x3)Programming Insights 编程见解
Key Lessons 关键经验
- Multiple solutions多解决方案: There’s usually more than one way to solve a problem 通常有多种方法解决问题
- Think before coding先思考后编码: Don’t rush to implement the first idea 不要急于实现第一个想法
- Correctness first正确性优先: First find a correct algorithm, then optimize 先找到正确算法,然后优化
- Be the computer模拟计算机: Think about how you would solve the problem manually 思考如何手动解决问题
- Generality is good通用性有益: Solve more general problems when possible 尽可能解决更通用的问题
- Don’t reinvent the wheel不要重复造轮子: Use existing solutions when available 使用现有解决方案
Decision Structure Summary 决策结构总结
1. Simple Decision 简单决策
if <condition>:
<body>2. Two-Way Decision 双向决策
if <condition>:
<body>
else:
<body>3. Multi-Way Decision 多向决策
if <condition1>:
<body1>
elif <condition2>:
<body2>
elif <condition3>:
<body3>
else:
<default_body>4. Conditional Execution 条件执行
if __name__ == '__main__':
main()5. Exception Handling 异常处理
try:
<risky_operations>
except <SpecificError> as e:
<error_handling>
except <AnotherError>:
<alternative_handling>
else:
<executes_if_no_error>
finally:
<cleanup_code>Best Practices 最佳实践
- Use meaningful condition names 使用有意义的条件名称
- Handle all possible cases 处理所有可能情况
- Use exceptions for unexpected errors 对意外错误使用异常
- Keep decision structures readable 保持决策结构可读
- Test with borderline values 使用边界值测试