第二章 Python基础语法与数据类型

第二章 Python基础语法与数据类型

2.1 基础语法规范

2.1.1 代码结构

# 模块级代码
import sys

def main():
    # 函数级代码块(4空格缩进)
    print("标准缩进结构")

# 空行分隔逻辑块
if __name__ == "__main__":
    main()

2.1.2 注释系统

# 单行注释

'''
多行注释
(三个单引号实现)
'''

"""
文档字符串
(函数/模块说明,可用__doc__访问)
"""

def sample():
    """这是函数的文档字符串"""
    pass

2.2 变量与数据类型

2.2.1 动态类型系统(核心特性)

Python采用动态类型机制,具有以下特点:

  1. 类型关联值而非变量

    var = 10       # 初始为整型
    var = "hello"  # 合法,变为字符串类型
    var = [1,2,3]  # 合法,变为列表类型
    
  2. 运行时类型推断

    # 自动根据赋值确定类型
    price = 19.99          # 自动识别为float
    product = "Keyboard"   # 自动识别为str
    
  3. 类型检查发生在运行时

    def add(a, b):
        return a + b  # 实际运行才能确定是否支持相加操作
    
    print(add(3,5))    # 正确 → 8
    print(add("a","b") # 正确 → "ab"
    print(add(3,"a"))  # 运行时报错(TypeError)
    

动态类型优势:

# 灵活的数据处理
def process_data(data):
    if isinstance(data, list):
        return sum(data)
    elif isinstance(data, str):
        return data.upper()
    else:
        return data

print(process_data([1,2,3]))  # 6
print(process_data("text"))   # TEXT

动态类型注意事项:

# 需要类型验证的场景
def calculate_area(r):
    if not isinstance(r, (int, float)):
        raise TypeError("需要数值类型")
    return 3.14 * r ** 2

# 类型可能变化的陷阱
values = [10, 20, 30]
total = 0

for item in values:
    # 如果values包含字符串元素会导致错误
    total += item  

2.2.2 类型查询与验证

# 使用type()查看类型
num = 10
print(type(num))  # <class 'int'>

# 使用isinstance()验证类型
data = 3.14
if isinstance(data, float):
    print("浮点型数据")

# 类型注解(Python3.5+)
def greeting(name: str) -> str:
    return "Hello " + name

2.2.3 变量定义

counter = 100          # 整型变量
miles = 1000.0         # 浮点型变量
name = "Python"        # 字符串
numbers = [1, 2, 3]    # 列表
is_valid = True        # 布尔型

# 多变量赋值
a, b, c = 1, 2, "three"

2.2.4 核心数据类型

数值类型
# 整型(任意精度)
big_num = 123456789012345678901234567890

# 浮点型
pi = 3.1415926535
sci_num = 1.23e-4      # 科学计数法

# 复数
complex_num = 3 + 4j
字符串操作
s = "Python Programming"

print(s[0])       # 'P'(正向索引)
print(s[-1])      # 'g'(反向索引)
print(s[7:10])    # 'Pro'(切片操作)
print(len(s))     # 18(长度获取)
print(s.upper())  # 转大写
print("py" in s)  # 成员检测
列表详解
# 创建与修改
fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"            # 修改元素
fruits.append("orange")        # 添加元素
fruits.insert(0, "peach")      # 插入元素
last = fruits.pop()            # 移除末元素

# 列表切片
sub_list = fruits[1:3]         # ['mango', 'cherry']
reverse_list = fruits[::-1]    # 反转列表
元组特性
# 不可变序列
dimensions = (1920, 1080)
# dimensions[0] = 2560  # 会引发TypeError

# 元组解包
width, height = dimensions
字典操作
student = {
    "name": "Alice",
    "age": 22,
    "courses": ["Math", "CS"]
}

# 增删改查
student["grade"] = "A"         # 添加新键
del student["age"]             # 删除键
print(student.get("name"))     # 安全获取值
print(student.keys())          # 输出所有键
集合运算
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A | B)  # 并集 {1,2,3,4,5,6}
print(A & B)  # 交集 {3,4}
print(A - B)  # 差集 {1,2}

2.2.5 类型转换

num_str = "123"
num_int = int(num_str)       # 字符串转整型
num_float = float("3.14")    # 字符串转浮点型
str_num = str(123)           # 数值转字符串

list_num = list("Python")    # 字符串转列表 → ['P','y','t','h','o','n']
tuple_num = tuple([1,2,3])   # 列表转元组 → (1,2,3)

类型变化演示

# 动态类型工作流程示例
variable = 10          # 创建int对象,变量指向该对象
print(type(variable))  # <class 'int'>

variable = "Text"      # 创建新str对象,变量改变指向
print(type(variable))  # <class 'str'>

variable = [variable]  # 创建包含字符串的列表
print(type(variable))  # <class 'list'>

类型系统补充说明:

  1. 对象引用机制
    Python变量本质是对对象的引用,类型信息存储在对象中而非变量

  2. 内存管理特点

    a = 10  # 创建对象10,a指向它
    b = a   # b与a指向同一对象
    a = 20  # 创建新对象20,a改变指向
    print(b)  # 仍输出10
    
  3. 类型强转示例

    # 自动类型转换
    print(3 + 5.0)    # int自动转float → 8.0
    
    # 需要显式转换
    age = "25"
    real_age = int(age) + 1  # 必须显式转换
    

2.3 流程控制

2.3.1 条件语句

# 基础if结构
age = 18
if age < 12:
    print("儿童")
elif 12 <= age < 18:
    print("青少年")
else:
    print("成年人")

# 嵌套条件示例
score = 85
if score >= 90:
    grade = "A"
else:
    if score >= 80:
        grade = "B"
    else:
        grade = "C"

2.3.2 循环结构

while循环
# 基础while
count = 0
while count < 5:
    print(count)
    count += 1  # 等效于 count = count + 1

# break/continue使用
while True:
    user_input = input("输入q退出:")
    if user_input == 'q':
        break
    elif not user_input.isdigit():
        print("请输入数字!")
        continue
    print("输入的是:", user_input)
for循环
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit.upper())

# 遍历字典
for key, value in student.items():
    print(f"{key}: {value}")

# range函数应用
for i in range(5):         # 0-4
    print(i)

for i in range(2, 10, 2):  # 2,4,6,8
    print(i)
循环控制
# else子句(循环正常结束执行)
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(f"{n} = {x}*{n//x}")
            break
    else:
        print(f"{n}是质数")

# 列表推导式(特殊循环结构)
squares = [x**2 for x in range(10) if x%2==0]
# 结果:[0,4,16,36,64]

2.4 综合应用示例

# 成绩评级系统
scores = [85, 92, 78, 90, 82]

for score in scores:
    if score >= 90:
        grade = "A"
    elif 80 <= score < 90:
        grade = "B"
    elif 70 <= score < 80:
        grade = "C"
    else:
        grade = "D"
    print(f"分数:{score} → 等级:{grade}")

# 统计数字出现次数
numbers = [3,1,4,1,5,9,2,6,5,3]
count_dict = {}

for num in numbers:
    if num in count_dict:
        count_dict[num] += 1
    else:
        count_dict[num] = 1

print("数字统计结果:", count_dict)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值