第1章:Python基础
一、导读
1.1 本章学习目标
第1章讲解 Python 的基础语法:变量、数据类型、控制流、函数。
本章核心学习目标:
- 掌握 Python 基本语法:变量、类型、操作符
- 理解控制流:if/elif/else、for、while
- 掌握函数定义和调用
- 理解 Python 的动态类型特性
1.2 为什么本章如此重要
Python 语法简洁易读,是自动化脚本的理想选择。掌握基础语法是后续所有章节的前提。
1.3 核心问题引导
Python 的变量和类型有什么关系?
for 循环和 while 循环各适合什么场景?
函数参数有哪些传递方式?
二、核心概念详解
2.1 变量与类型
python
# 动态类型
x = 42 # int
x = "hello" # str (类型可以改变)
x = [1, 2, 3] # list
# 类型转换
num_str = "42"
num = int(num_str)
pi_str = str(3.14)
is_true = bool(1) # True
# 多重赋值
a, b, c = 1, 2, 3
a = b = c = 0 # 三个变量指向同一个对象2.2 控制流
python
# if/elif/else
age = 25
if age < 18:
print("Minor")
elif age < 65:
print("Adult")
else:
print("Senior")
# for 循环
for i in range(5):
print(i)
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# while 循环
count = 0
while count < 5:
print(count)
count += 1
# 列表推导
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]2.3 函数
python
def greet(name, greeting="Hello"):
"""向某人问好"""
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Hi")) # Hi, Bob!
# 可变参数
def total(*args):
return sum(args)
print(total(1, 2, 3, 4)) # 10
# 关键字参数
def build_profile(**kwargs):
return kwargs
profile = build_profile(name="Alice", age=30, city="NYC")
# Lambda
square = lambda x: x ** 2
print(square(5)) # 25
# 排序用 lambda
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
students.sort(key=lambda s: s[1], reverse=True)三、实战案例
3.1 案例一:简单的密码生成器
python
import random
import string
def generate_password(length=12, use_upper=True, use_digits=True, use_special=True):
chars = string.ascii_lowercase
if use_upper:
chars += string.ascii_uppercase
if use_digits:
chars += string.digits
if use_special:
chars += string.punctuation
password = ''.join(random.choice(chars) for _ in range(length))
return password
# 生成不同强度的密码
print("Simple:", generate_password(8, use_special=False))
print("Medium:", generate_password(12))
print("Strong:", generate_password(16))四、本章小结
Python 是动态类型语言,变量不需要声明类型
for 循环适合遍历序列,while 循环适合条件循环
函数支持默认参数、可变参数、关键字参数
五、思考与练习
Python 的 list 和 tuple 有什么区别?
如何实现一个带默认参数的函数?