课程 5:Python语法

📚 学习目标

Python语法简介:
Python是一门简洁、易读、功能强大的编程语言。其语法接近自然语言,强调代码可读性,采用缩进来表示代码块(通常为4个空格),无需使用大括号。Python支持动态类型,无需声明变量类型,语法简洁,非常适合初学者快速上手。

1. Python基础语法规则

1.1 变量命名规范

📝 命名规则

1.2 数据类型与赋值

🔢 基本数据类型

⚡ 动态类型特性

1.3 缩进与代码块

📐 缩进规则

1.4 注释与文档

💬 注释类型

2. 基础代码示例

2.1 变量定义与数据类型

# 变量命名示例
user_age = 18                    # 整数类型
user_name = "Alice"              # 字符串类型
score = 95.5                     # 浮点数类型
is_passed = True                 # 布尔类型
hobbies = ["reading", "music"]   # 列表类型

# 动态类型示例
x = 10                           # 整数
print(f"x的类型: {type(x)}")     # 
x = "Hello"                      # 字符串
print(f"x的类型: {type(x)}")     # 
x = [1, 2, 3]                    # 列表
print(f"x的类型: {type(x)}")     # 

# 变量赋值与表达式
a = 10
b = 5
result = a + b * 2               # 表达式计算
print(f"计算结果: {result}")     # 20

2.2 输入输出与注释

# 输入输出示例
name = input("请输入你的名字:")   # 获取用户输入
age = input("请输入你的年龄:")    # 注意:input()返回字符串
age = int(age)                   # 转换为整数

print("你好,", name)             # 基本输出
print(f"你今年{age}岁")          # 格式化字符串输出
print("你的年龄是:", age, "岁")   # 多个值输出

# 注释示例
# 这是单行注释,用于说明代码功能

'''
这是多行注释
可以用于说明复杂逻辑
或者暂时注释掉多行代码
'''

"""
这也是多行注释
双引号和单引号都可以使用
"""

# 行尾注释示例
x = 5  # 设置初始值为5
y = x * 2  # 计算x的两倍

2.3 缩进与代码块

# 缩进示例 - 函数定义
def add(a, b):
    """计算两个数的和"""
    result = a + b    # 函数体必须缩进
    return result     # 返回值

def multiply(x, y):
    """计算两个数的积"""
    if x > 0 and y > 0:    # 条件语句需要缩进
        result = x * y
        print(f"{x} × {y} = {result}")
    else:
        print("请输入正数")  # else块也需要缩进
    return result

# 调用函数
sum_result = add(5, 3)
multiply(4, 6)

2.4 常见语法错误与解决方案

⚠️ 常见错误类型

# 错误示例与正确写法对比

# 1. NameError - 变量未定义
# 错误写法:
# print(age)  # NameError: name 'age' is not defined

# 正确写法:
age = 18
print(age)  # 18

# 2. IndentationError - 缩进错误
# 错误写法:
# def test():
# print("Hello")  # IndentationError: expected an indented block

# 正确写法:
def test():
    print("Hello")  # 正确缩进

# 3. TypeError - 类型不匹配
# 错误写法:
# result = "3" + 2  # TypeError: can only concatenate str (not "int") to str

# 正确写法:
result = int("3") + 2  # 先转换类型
# 或者
result = "3" + str(2)  # 都转换为字符串

# 4. SyntaxError - 语法错误
# 错误写法:
# if x > 5
#     print("x大于5")  # SyntaxError: invalid syntax

# 正确写法:
if x > 5:
    print("x大于5")  # 缺少冒号

# 5. ValueError - 值错误
# 错误写法:
# age = int("abc")  # ValueError: invalid literal for int()

# 正确写法:
try:
    age = int("abc")
except ValueError:
    print("请输入有效的数字")
    age = 0

3. 语句与运算符

3.1 语句

📝 语句(Statements)

语句是Python程序的基本执行单元,每条语句都会执行一个特定的操作。

3.2 运算符详解

算术运算符

运算符 描述 示例 结果
+ 加法 5 + 3 8
- 减法 10 - 4 6
* 乘法 6 * 7 42
/ 除法(浮点数) 15 / 3 5.0
// 整除 17 // 5 3
% 取余 17 % 5 2
** 幂运算 2 ** 3 8

比较运算符

运算符 描述 示例 结果
== 等于 5 == 5 True
!= 不等于 5 != 3 True
> 大于 10 > 5 True
< 小于 3 < 7 True
>= 大于等于 5 >= 5 True
<= 小于等于 4 <= 6 True

逻辑运算符

运算符 描述 示例 结果
and 逻辑与 True and True True
or 逻辑或 True or False True
not 逻辑非 not True False

赋值运算符

运算符 描述 等价于 示例
= 基本赋值 x = 5 x = 5
+= 加法赋值 x = x + 3 x += 3
-= 减法赋值 x = x - 2 x -= 2
*= 乘法赋值 x = x * 4 x *= 4
/= 除法赋值 x = x / 2 x /= 2
//= 整除赋值 x = x // 3 x //= 3
%= 取余赋值 x = x % 5 x %= 5
**= 幂赋值 x = x ** 2 x **= 2
&= 按位与赋值 x = x & 3 x &= 3
|= 按位或赋值 x = x | 2 x |= 2
^= 按位异或赋值 x = x ^ 1 x ^= 1
<<= 左移赋值 x = x << 2 x <<= 2
>>= 右移赋值 x = x >> 1 x >>= 1

身份运算符

运算符 描述 示例 结果
is 判断是否为同一对象 a is b True/False
is not 判断是否不是同一对象 a is not b True/False

成员运算符

运算符 描述 示例 结果
in 判断元素是否在序列中 x in list True/False
not in 判断元素是否不在序列中 x not in list True/False

位运算符

运算符 描述 示例 结果
& 按位与 5 & 3 1 (101 & 011 = 001)
| 按位或 5 | 3 7 (101 | 011 = 111)
^ 按位异或 5 ^ 3 6 (101 ^ 011 = 110)
~ 按位取反 ~5 -6 (~101 = -110)
<< 左移 5 << 2 20 (101 << 2 = 10100)
>> 右移 5 >> 1 2 (101 >> 1 = 10)

海象运算符(Python 3.8+)

运算符 描述 示例 等价于
:= 赋值表达式 if (n := len(a)) > 10: n = len(a)
if n > 10:

3.3 运算符优先级

📊 完整优先级从高到低

  1. 括号:() - 最高优先级
  2. 索引、切片、调用:[], [:], ()
  3. 属性访问:.
  4. 幂运算:**
  5. 一元运算符:+x, -x, ~x, not x
  6. 乘除模:*, /, //, %
  7. 加减:+, -
  8. 位移:<<, >>
  9. 按位与:&
  10. 按位异或:^
  11. 按位或:|
  12. 比较:==, !=, >, <, >=, <=, is, is not, in, not in
  13. 逻辑与:and
  14. 逻辑或:or
  15. 海象运算符::=
  16. 赋值:=, +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, <<=, >>= - 最低优先级
💡 记忆口诀

括号索引属性幂,一元乘除加减移,与异或或比较,与或海象赋值

🔍 优先级示例
# 复杂表达式优先级示例
result = 2 + 3 * 4 ** 2 & 5 | 6
# 计算顺序:
# 1. 4 ** 2 = 16 (幂运算)
# 2. 3 * 16 = 48 (乘法)
# 3. 2 + 48 = 50 (加法)
# 4. 50 & 5 = 0 (按位与)
# 5. 0 | 6 = 6 (按位或)

# 使用括号改变优先级
result = (2 + 3) * (4 ** 2) & (5 | 6)
# 计算顺序:
# 1. 2 + 3 = 5 (括号内加法)
# 2. 4 ** 2 = 16 (括号内幂运算)
# 3. 5 | 6 = 7 (括号内按位或)
# 4. 5 * 16 = 80 (乘法)
# 5. 80 & 7 = 0 (按位与)

3.4 实际应用示例

# 语句与表达式示例

# 1. 赋值语句
name = "Alice"
age = 25
score = 95.5

# 2. 表达式语句
print("Hello, World!")  # 函数调用表达式
result = 2 + 3 * 4      # 算术表达式
is_adult = age >= 18    # 比较表达式

# 3. 复杂表达式
# 算术运算
area = 3.14 * radius ** 2
average = (score1 + score2 + score3) / 3

# 逻辑运算
can_vote = age >= 18 and is_citizen
is_valid = username and password and email

# 条件表达式(三元运算符)
status = "成年" if age >= 18 else "未成年"
grade = "优秀" if score >= 90 else "良好" if score >= 80 else "及格"

# 4. 运算符优先级示例
result1 = 2 + 3 * 4     # 结果:14 (先乘后加)
result2 = (2 + 3) * 4   # 结果:20 (先括号后乘)
result3 = 2 ** 3 + 1    # 结果:9 (先幂后加)
result4 = 2 ** (3 + 1)  # 结果:16 (先括号后幂)

# 5. 赋值运算符
x = 10
x += 5      # x = 15
x *= 2      # x = 30
x -= 10     # x = 20
x /= 4      # x = 5.0

# 6. 字符串运算符
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name  # 字符串连接
greeting = "Hello" * 3  # 字符串重复

# 7. 成员运算符
fruits = ["apple", "banana", "orange"]
has_apple = "apple" in fruits      # True
has_grape = "grape" not in fruits  # True

# 8. 身份运算符
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a is b)    # False (不同对象)
print(a is c)    # True (同一对象)
print(a == b)    # True (值相等)

# 9. 位运算符详解
# 按位与 (&)
a = 5   # 二进制:101
b = 3   # 二进制:011
result = a & b   # 结果:1 (二进制:001)

# 按位或 (|)
result = a | b   # 结果:7 (二进制:111)

# 按位异或 (^)
result = a ^ b   # 结果:6 (二进制:110)

# 按位取反 (~)
result = ~a      # 结果:-6 (取反后加1)

# 左移 (<<)
result = a << 2  # 结果:20 (101 << 2 = 10100)

# 右移 (>>)
result = a >> 1  # 结果:2 (101 >> 1 = 10)

# 10. 位运算赋值运算符
x = 10
x &= 3   # x = x & 3 = 10 & 3 = 2
x |= 5   # x = x | 5 = 2 | 5 = 7
x ^= 3   # x = x ^ 3 = 7 ^ 3 = 4
x <<= 2  # x = x << 2 = 4 << 2 = 16
x >>= 1  # x = x >> 1 = 16 >> 1 = 8

# 11. 海象运算符 (Python 3.8+)
# 传统写法
numbers = [1, 2, 3, 4, 5]
n = len(numbers)
if n > 3:
    print(f"列表有 {n} 个元素")

# 使用海象运算符
if (n := len(numbers)) > 3:
    print(f"列表有 {n} 个元素")

# 在循环中使用
while (user_input := input("请输入数字: ")) != "quit":
    print(f"你输入了: {user_input}")

# 在列表推导式中使用
squares = [x**2 for x in range(10) if (sqrt := x**0.5) < 3]

# 12. 实际应用场景

# 身份运算符应用 - 单例模式检查
class Singleton:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

# 成员运算符应用 - 权限检查
user_roles = ["admin", "user", "guest"]
required_roles = ["admin", "moderator"]

has_permission = any(role in user_roles for role in required_roles)

# 位运算应用 - 权限管理
READ_PERMISSION = 1    # 001
WRITE_PERMISSION = 2   # 010
EXECUTE_PERMISSION = 4 # 100

user_permissions = READ_PERMISSION | WRITE_PERMISSION  # 011 (读写权限)
can_read = user_permissions & READ_PERMISSION          # True
can_execute = user_permissions & EXECUTE_PERMISSION    # False

# 海象运算符应用 - 数据处理
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 找到第一个大于5的元素并打印
if (first_large := next((x for x in data if x > 5), None)) is not None:
    print(f"第一个大于5的元素是: {first_large}")

# 在正则表达式中使用
import re
text = "Hello World"
if (match := re.search(r'World', text)):
    print(f"找到匹配: {match.group()}")

# 13. 运算符优先级实际应用
# 复杂的数学表达式
result = (2 + 3) * 4 ** 2 - 10 / 2
# 计算顺序:
# 1. (2 + 3) = 5
# 2. 4 ** 2 = 16
# 3. 5 * 16 = 80
# 4. 10 / 2 = 5
# 5. 80 - 5 = 75

# 逻辑表达式
is_valid_user = (age >= 18 and 
                username and 
                password and 
                email and 
                (role in ["admin", "user", "guest"]))

# 14. 高级位运算技巧
# 检查是否为2的幂
def is_power_of_two(n):
    return n > 0 and (n & (n - 1)) == 0

# 计算二进制中1的个数
def count_ones(n):
    count = 0
    while n:
        count += n & 1
        n >>= 1
    return count

# 交换两个数(不使用临时变量)
a, b = 5, 10
a ^= b
b ^= a
a ^= b
print(f"交换后: a={a}, b={b}")  # a=10, b=5

4. 表达式

📝 表达式概述

表达式是Python程序的基本构建块,能够计算并返回一个值。表达式可以包含变量、常量、运算符、函数调用等元素。

🔢 表达式基本类型

表达式是能够计算并返回值的代码片段。

4.1 算术表达式

🔢 基本算术表达式

算术表达式用于数学计算,包含数字、变量和算术运算符。

# 基本算术表达式
a = 10
b = 3

# 加法表达式
sum_result = a + b                    # 13

# 减法表达式
diff_result = a - b                   # 7

# 乘法表达式
product = a * b                       # 30

# 除法表达式(浮点数)
quotient = a / b                      # 3.333...

# 整除表达式
floor_division = a // b               # 3

# 取余表达式
remainder = a % b                     # 1

# 幂运算表达式
power = a ** b                        # 1000

# 复杂算术表达式
complex_expr = (a + b) * 2 - (a / b)  # 使用括号控制优先级

# 数学函数表达式
import math
sqrt_expr = math.sqrt(a)              # 平方根
sin_expr = math.sin(math.pi / 2)      # 正弦函数
log_expr = math.log(a, 2)             # 对数

4.2 比较表达式

🔍 比较表达式

比较表达式用于比较两个值,返回布尔值(True或False)。

# 数值比较表达式
x = 10
y = 5

# 相等比较
is_equal = x == y                     # False

# 不等比较
is_not_equal = x != y                 # True

# 大于比较
is_greater = x > y                    # True

# 小于比较
is_less = x < y                       # False

# 大于等于比较
is_greater_equal = x >= y             # True

# 小于等于比较
is_less_equal = x <= y                # False

# 字符串比较表达式
name1 = "Alice"
name2 = "Bob"

# 字符串按字典序比较
name_compare = name1 < name2          # True ("Alice" < "Bob")

# 链式比较表达式
age = 25
is_adult = 18 <= age <= 65            # True (18 <= 25 <= 65)

# 复杂比较表达式
score = 85
is_passing = 60 <= score <= 100 and score != 0  # True

4.3 逻辑表达式

🧠 逻辑表达式

逻辑表达式使用逻辑运算符组合多个条件,返回布尔值。

# 基本逻辑表达式
a = True
b = False

# 逻辑与表达式
logical_and = a and b                 # False

# 逻辑或表达式
logical_or = a or b                   # True

# 逻辑非表达式
logical_not = not a                   # False

# 复杂逻辑表达式
age = 25
has_id = True
is_citizen = True

# 多重条件逻辑表达式
can_vote = age >= 18 and has_id and is_citizen  # True

# 短路求值示例
def expensive_function():
    print("执行昂贵操作")
    return True

# 由于短路求值,expensive_function不会被调用
result = False and expensive_function()  # False,不打印

# 条件逻辑表达式
is_student = True
has_scholarship = False

# 使用or的默认值模式
status = is_student or "非学生"        # True (短路求值)

# 使用and的条件执行
message = has_scholarship and "获得奖学金"  # False (短路求值)

4.4 条件表达式(三元运算符)

🎯 条件表达式

条件表达式提供了一种简洁的方式来根据条件选择不同的值。

# 基本条件表达式
age = 20
status = "成年" if age >= 18 else "未成年"  # "成年"

# 嵌套条件表达式
score = 85
grade = "优秀" if score >= 90 else "良好" if score >= 80 else "及格" if score >= 60 else "不及格"

# 条件表达式与函数调用
def get_discount(is_member):
    return 0.1 if is_member else 0.0

discount = get_discount(True)  # 0.1

# 条件表达式与列表
numbers = [1, 2, 3, 4, 5]
filtered = [x if x > 2 else 0 for x in numbers]  # [0, 0, 3, 4, 5]

# 条件表达式与字符串格式化
name = "Alice"
greeting = f"你好,{name}!" if name else "你好,陌生人!"

# 条件表达式与类型检查
value = 42
result = "字符串" if isinstance(value, str) else "数字" if isinstance(value, (int, float)) else "其他类型"

# 条件表达式与异常处理
def safe_divide(a, b):
    return a / b if b != 0 else "除数不能为零"

# 条件表达式与字典
user_type = "admin"
permissions = {
    "admin": "完全权限",
    "user": "基本权限",
    "guest": "只读权限"
}
user_permission = permissions.get(user_type, "未知权限")

4.5 函数调用表达式

📞 函数调用表达式

函数调用表达式执行函数并返回结果,是表达式的重要组成部分。

# 基本函数调用表达式
def greet(name):
    return f"你好,{name}!"

# 函数调用表达式
message = greet("Alice")              # "你好,Alice!"

# 内置函数调用表达式
length = len("Python")                # 6
maximum = max(1, 2, 3, 4, 5)          # 5
minimum = min([10, 20, 30])           # 10
sum_result = sum([1, 2, 3, 4, 5])     # 15

# 方法调用表达式
text = "  Hello World  "
cleaned = text.strip()                # "Hello World"
upper_text = text.upper()             # "  HELLO WORLD  "
split_result = text.split()           # ['Hello', 'World']

# 链式函数调用表达式
result = "  hello world  ".strip().upper().replace("WORLD", "PYTHON")

# 函数调用作为参数
def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

# 嵌套函数调用表达式
complex_result = multiply(add(2, 3), add(4, 1))  # 5 * 5 = 25

# 带关键字参数的函数调用
def create_user(name, age, email=None):
    return {"name": name, "age": age, "email": email}

user = create_user(name="Alice", age=25, email="alice@example.com")

# 解包参数的函数调用
def calculate_stats(*numbers):
    return {
        "sum": sum(numbers),
        "average": sum(numbers) / len(numbers),
        "count": len(numbers)
    }

stats = calculate_stats(1, 2, 3, 4, 5)

# 匿名函数(lambda)表达式
square = lambda x: x ** 2
square_result = square(5)             # 25

# 高阶函数调用表达式
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))  # [1, 4, 9, 16, 25]
filtered = list(filter(lambda x: x > 2, numbers))  # [3, 4, 5]

4.6 属性访问表达式

🔗 属性访问表达式

属性访问表达式用于访问对象的属性和方法。

# 对象属性访问表达式
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"你好,我是{self.name}"

# 创建对象
person = Person("Alice", 25)

# 属性访问表达式
name = person.name                     # "Alice"
age = person.age                       # 25

# 方法调用表达式
greeting = person.greet()              # "你好,我是Alice"

# 模块属性访问表达式
import math
pi_value = math.pi                     # 3.141592653589793
sqrt_func = math.sqrt                  # 

# 列表属性访问表达式
numbers = [1, 2, 3, 4, 5]
list_length = len(numbers)             # 5
first_element = numbers[0]             # 1

# 字典属性访问表达式
user_info = {"name": "Bob", "age": 30}
user_name = user_info["name"]          # "Bob"
user_age = user_info.get("age", 0)     # 30

# 字符串属性访问表达式
text = "Hello World"
text_length = len(text)                # 11
first_char = text[0]                   # "H"
last_char = text[-1]                   # "d"

# 嵌套属性访问表达式
class Address:
    def __init__(self, city, country):
        self.city = city
        self.country = country

class Employee:
    def __init__(self, name, address):
        self.name = name
        self.address = address

# 创建嵌套对象
address = Address("北京", "中国")
employee = Employee("张三", address)

# 嵌套属性访问
city = employee.address.city           # "北京"
country = employee.address.country     # "中国"

# 条件属性访问
def get_user_info(user):
    return user.name if hasattr(user, 'name') else "未知用户"

# 动态属性访问
attribute_name = "age"
age_value = getattr(person, attribute_name, 0)  # 25

4.7 集合表达式

📦 集合表达式

集合表达式用于创建和操作列表、元组、集合、字典等数据结构。

# 列表表达式
numbers = [1, 2, 3, 4, 5]             # 列表字面量
squares = [x**2 for x in numbers]     # 列表推导式
filtered = [x for x in numbers if x > 2]  # 条件列表推导式

# 元组表达式
coordinates = (10, 20)                # 元组字面量
point_3d = (x, y, z) = (1, 2, 3)     # 元组解包

# 集合表达式
unique_numbers = {1, 2, 2, 3, 3, 4}   # 集合字面量(自动去重)
squares_set = {x**2 for x in numbers} # 集合推导式

# 字典表达式
user_dict = {"name": "Alice", "age": 25}  # 字典字面量
squares_dict = {x: x**2 for x in numbers} # 字典推导式

# 生成器表达式
squares_gen = (x**2 for x in numbers) # 生成器表达式(惰性求值)

# 嵌套集合表达式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  # 二维列表
flattened = [item for row in matrix for item in row]  # 展平列表

# 条件集合表达式
even_squares = [x**2 for x in numbers if x % 2 == 0]  # 偶数的平方

# 集合操作表达式
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2                   # 并集
intersection = set1 & set2            # 交集
difference = set1 - set2              # 差集

# 字典合并表达式(Python 3.9+)
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = dict1 | dict2                # 字典合并

# 切片表达式
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
first_three = numbers[:3]             # [0, 1, 2]
last_three = numbers[-3:]             # [7, 8, 9]
every_second = numbers[::2]           # [0, 2, 4, 6, 8]
reversed_list = numbers[::-1]         # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

# 字符串切片表达式
text = "Hello World"
first_word = text[:5]                 # "Hello"
last_word = text[6:]                  # "World"
reversed_text = text[::-1]            # "dlroW olleH"

4.8 表达式求值规则

⚖️ 表达式求值规则

理解表达式的求值规则对于编写正确的代码至关重要。

📋 求值顺序规则
  1. 括号优先:最内层括号先计算
  2. 运算符优先级:按运算符优先级顺序计算
  3. 左结合性:相同优先级从左到右计算
  4. 短路求值:逻辑运算符可能跳过部分计算
# 表达式求值示例

# 1. 括号优先
result1 = (2 + 3) * 4                 # 先计算括号:5 * 4 = 20
result2 = 2 + (3 * 4)                 # 先计算括号:2 + 12 = 14

# 2. 运算符优先级
result3 = 2 + 3 * 4                   # 先乘后加:2 + 12 = 14
result4 = 2 ** 3 + 1                  # 先幂后加:8 + 1 = 9

# 3. 左结合性
result5 = 10 - 3 - 2                  # 从左到右:(10 - 3) - 2 = 5
result6 = 2 ** 3 ** 2                 # 从右到左:2 ** (3 ** 2) = 512

# 4. 短路求值
def expensive_operation():
    print("执行昂贵操作")
    return True

# 由于短路求值,expensive_operation不会被调用
result7 = False and expensive_operation()  # False
result8 = True or expensive_operation()    # True

# 5. 复杂表达式求值
complex_expr = (2 + 3) * 4 ** 2 - 10 / 2
# 计算步骤:
# 1. (2 + 3) = 5
# 2. 4 ** 2 = 16
# 3. 5 * 16 = 80
# 4. 10 / 2 = 5
# 5. 80 - 5 = 75

# 6. 条件表达式求值
age = 25
status = "成年" if age >= 18 else "未成年"
# 求值步骤:
# 1. 计算条件:age >= 18 → True
# 2. 选择真值:"成年"

# 7. 函数调用表达式求值
def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

result9 = multiply(add(2, 3), add(4, 1))
# 求值步骤:
# 1. add(2, 3) = 5
# 2. add(4, 1) = 5
# 3. multiply(5, 5) = 25

5. 语法要点总结

✅ Python语法核心要点

⚠️ 常见陷阱与注意事项

🔢 表达式要点总结

温馨提示:多练习各种Python语法和表达式,注意缩进一致性和命名规范。建议使用IDE或编辑器,它们能帮助发现语法错误。
作业5:Python语法综合练习

基础语法练习:
1. 编写一个程序,定义不同类型的变量(整数、浮点数、字符串、布尔值、列表、元组、字典),并打印它们的类型和值。

2. 创建一个函数,接受用户输入的名字、年龄和爱好,使用正确的缩进和注释,返回格式化的介绍信息。要求: - 使用适当的变量命名规范 - 添加详细的注释说明 - 处理输入验证(年龄必须为正数) - 使用字符串格式化输出

语法错误修正:
3. 找出以下代码中的语法错误并修正:
def calculate_area(radius)
area = 3.14 * radius ** 2
return area
print(calculate_area(5)


运算符练习:
4. 编写一个程序,演示各种运算符的使用: - 算术运算符:计算圆的面积和周长 - 比较运算符:比较两个数字的大小 - 逻辑运算符:判断用户是否满足登录条件(年龄≥18且密码正确) - 位运算符:实现两个数的交换(不使用临时变量) - 成员运算符:检查元素是否在列表中

表达式练习:
5. 使用条件表达式(三元运算符)完成以下任务: - 判断一个数字是正数、负数还是零 - 根据成绩返回等级(优秀≥90,良好≥80,及格≥60,不及格<60) - 判断年份是否为闰年

6. 创建各种推导式: - 列表推导式:生成1到20中所有偶数的平方 - 字典推导式:创建数字及其平方的映射 - 集合推导式:生成1到50中所有质数的集合 - 条件推导式:过滤出列表中大于10的元素

高级语法练习:
7. 使用海象运算符(Python 3.8+)优化以下代码: - 在循环中同时获取和检查用户输入 - 在列表推导式中避免重复计算 - 在条件判断中同时赋值和使用变量

8. 编写一个程序,演示表达式求值规则: - 创建复杂的数学表达式,展示运算符优先级 - 使用括号改变求值顺序 - 演示短路求值的效果 - 展示链式比较的用法

综合应用:
9. 创建一个学生成绩管理系统,包含以下功能: - 使用字典存储学生信息(姓名、年龄、成绩) - 使用列表推导式计算平均分、最高分、最低分 - 使用条件表达式判断学生等级 - 使用位运算进行权限管理(读、写、执行权限) - 使用成员运算符检查学生是否在特定班级

10. 编写一个简单的计算器程序,要求: - 支持基本的算术运算(+、-、*、/、//、%、**) - 使用函数调用表达式处理不同运算 - 使用条件表达式处理除零错误 - 使用逻辑运算符验证输入的有效性 - 使用字符串格式化输出结果

代码规范练习:
11. 按照PEP 8编码规范,重新格式化以下代码:
def bad_formatting(x,y,z):
if x>0 and y>0:
result=x+y*z
return result
else:
return None


调试练习:
12. 分析以下代码可能出现的错误,并提供解决方案:
def process_data(data):
total = 0
for item in data:
total += item
average = total / len(data)
return average


提交要求:
- 所有代码必须包含详细的注释 - 遵循Python命名规范 - 使用适当的缩进和格式 - 提供测试用例和运行结果 - 说明每个程序的设计思路和实现方法