1.Python 基础语法教程
引言
Python 是一门简洁、优雅、易学的编程语言。本教程将带你系统地学习 Python 的基础语法,每个概念都配有可直接运行的代码示例。你可以将代码复制到自己的机器上运行测试,通过实践来掌握 Python 编程。
学习建议:
- 阅读每个示例代码
- 复制代码到 Python 解释器或 IDE 中运行
- 尝试修改代码,观察结果变化
- 完成每个部分的练习
第一部分:Python 环境准备
安装 Python
Windows:
- 访问 Python 官网
- 下载最新版本的 Python
- 运行安装程序,勾选 "Add Python to PATH"
- 完成安装
验证安装:
# 打开命令行(CMD 或 PowerShell),输入:
python --version
# 应该显示 Python 版本号,如:Python 3.11.0
运行 Python 代码
方法 1:交互式解释器
# 在命令行输入:
python
# 进入交互式环境,可以直接输入代码
方法 2:Python 文件
# 创建文件 hello.py,写入代码
# 然后运行:
python hello.py
方法 3:使用 IDE
- PyCharm
- VS Code
- Jupyter Notebook
第二部分:基本语法规则
1. 注释
注释用于解释代码,不会被执行。
# 这是单行注释
"""
这是多行注释
可以写多行内容
用于文档说明
"""
# 示例:计算两个数的和
a = 10
b = 20
result = a + b # 结果是 30
print(result) # 输出:30
运行测试:
# 复制以下代码到 Python 解释器运行
print("Hello, Python!") # 这是注释,不会执行
# print("这行被注释了,不会执行")
2. 缩进
Python 使用缩进来表示代码块,这是 Python 最重要的特性之一。
# 正确的缩进
if True:
print("这是 if 块内的代码")
print("需要缩进 4 个空格")
print("这是 if 块外的代码,不需要缩进")
# 错误的缩进会导致 IndentationError
# if True:
# print("错误:没有缩进") # 这会导致错误
运行测试:
# 复制运行以下代码
x = 10
if x > 5:
print("x 大于 5")
print("这是 if 块内的第二行")
print("这是 if 块外的代码")
3. 语句和换行
# 单行语句
x = 10
y = 20
# 多行语句(使用反斜杠)
total = x + \
y + \
30
# 多行语句(使用括号,更推荐)
total = (x +
y +
30)
# 一行多个语句(不推荐,但可以)
x = 10; y = 20; z = 30
运行测试:
# 测试多行语句
result = (10 +
20 +
30)
print(result) # 输出:60
第三部分:变量和数据类型
1. 变量
变量用于存储数据,Python 中的变量不需要声明类型。
# 创建变量
name = "Python"
age = 30
height = 1.75
is_student = True
# 打印变量
print(name) # Python
print(age) # 30
print(height) # 1.75
print(is_student) # True
# 变量可以重新赋值
age = 31
print(age) # 31
# 变量命名规则
# - 只能包含字母、数字和下划线
# - 不能以数字开头
# - 区分大小写
# - 不能使用 Python 关键字
运行测试:
# 创建并打印变量
my_name = "Alice"
my_age = 25
print(f"我的名字是 {my_name},年龄是 {my_age}")
2. 数据类型
Python 有几种基本数据类型:
2.1 整数(int)
# 整数
x = 10
y = -5
z = 0
# 大整数
big_number = 12345678901234567890
# 进制表示
binary = 0b1010 # 二进制:10
octal = 0o755 # 八进制:493
hexadecimal = 0xFF # 十六进制:255
print(x, y, z)
print(big_number)
print(binary, octal, hexadecimal)
运行测试:
# 测试整数运算
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.3333333333333335
print(a // b) # 3(整除)
print(a % b) # 1(取余)
print(a ** b) # 1000(幂运算)
2.2 浮点数(float)
# 浮点数
x = 3.14
y = -0.5
z = 1.0
# 科学计数法
scientific = 1.23e4 # 12300.0
small = 1.23e-4 # 0.000123
print(x, y, z)
print(scientific, small)
# 浮点数精度问题(注意)
result = 0.1 + 0.2
print(result) # 0.30000000000000004(不是 0.3)
运行测试:
# 测试浮点数运算
pi = 3.14159
radius = 5.0
area = pi * radius ** 2
print(f"圆的面积:{area}")
2.3 字符串(str)
# 字符串可以用单引号或双引号
name1 = 'Python'
name2 = "Python"
print(name1 == name2) # True
# 多行字符串
multiline = """这是第一行
这是第二行
这是第三行"""
# 字符串转义
escaped = "他说:\"你好\""
newline = "第一行\n第二行"
tab = "列1\t列2"
print(multiline)
print(escaped)
print(newline)
print(tab)
# 字符串格式化
name = "Alice"
age = 25
# 方法 1:f-string(推荐)
message = f"我的名字是 {name},年龄是 {age}"
print(message)
# 方法 2:format()
message = "我的名字是 {},年龄是 {}".format(name, age)
print(message)
# 方法 3:% 格式化(旧方法)
message = "我的名字是 %s,年龄是 %d" % (name, age)
print(message)
运行测试:
# 字符串操作
text = "Hello, Python!"
print(len(text)) # 14(长度)
print(text.upper()) # HELLO, PYTHON!
print(text.lower()) # hello, python!
print(text.replace("Python", "World")) # Hello, World!
print(text.split(",")) # ['Hello', ' Python!']
print("Python" in text) # True
2.4 布尔值(bool)
# 布尔值
is_true = True
is_false = False
print(is_true) # True
print(is_false) # False
# 布尔运算
print(True and False) # False
print(True or False) # True
print(not True) # False
# 比较运算返回布尔值
print(10 > 5) # True
print(10 == 5) # False
print(10 != 5) # True
运行测试:
# 测试布尔运算
age = 20
is_adult = age >= 18
can_vote = age >= 18 and age < 100
print(f"是成年人:{is_adult}")
print(f"可以投票:{can_vote}")
2.5 空值(None)
# None 表示空值
value = None
print(value) # None
print(value is None) # True
# 检查变量是否为空
name = None
if name is None:
print("名字未设置")
运行测试:
# 测试 None
result = None
if result is None:
print("结果为空")
else:
print(f"结果是:{result}")
3. 类型转换
# 类型转换函数
x = 10
y = "20"
z = 3.14
# 转换为字符串
str_x = str(x) # "10"
# 转换为整数
int_y = int(y) # 20
int_z = int(z) # 3(截断小数部分)
# 转换为浮点数
float_x = float(x) # 10.0
float_y = float(y) # 20.0
# 转换为布尔值
bool_x = bool(x) # True
bool_0 = bool(0) # False
bool_empty = bool("") # False
print(str_x, int_y, float_x)
运行测试:
# 类型转换示例
age_str = "25"
age_int = int(age_str)
age_next_year = age_int + 1
print(f"明年年龄:{age_next_year}")
4. 类型检查
# 使用 type() 检查类型
x = 10
y = "hello"
z = 3.14
print(type(x)) # <class 'int'>
print(type(y)) # <class 'str'>
print(type(z)) # <class 'float'>
# 使用 isinstance() 检查类型
print(isinstance(x, int)) # True
print(isinstance(y, str)) # True
print(isinstance(z, float)) # True
运行测试:
# 检查变量类型
value = 42
if isinstance(value, int):
print(f"{value} 是整数")
elif isinstance(value, str):
print(f"{value} 是字符串")
第四部分:运算符
1. 算术运算符
a = 10
b = 3
print(a + b) # 13(加法)
print(a - b) # 7(减法)
print(a * b) # 30(乘法)
print(a / b) # 3.3333333333333335(除法)
print(a // b) # 3(整除)
print(a % b) # 1(取余)
print(a ** b) # 1000(幂运算)
# 字符串和列表的运算
text = "Hello"
print(text * 3) # HelloHelloHello
numbers = [1, 2, 3]
print(numbers * 2) # [1, 2, 3, 1, 2, 3]
运行测试:
# 计算圆的周长和面积
radius = 5
pi = 3.14159
circumference = 2 * pi * radius
area = pi * radius ** 2
print(f"半径:{radius}")
print(f"周长:{circumference:.2f}")
print(f"面积:{area:.2f}")
2. 比较运算符
a = 10
b = 5
print(a == b) # False(等于)
print(a != b) # True(不等于)
print(a > b) # True(大于)
print(a < b) # False(小于)
print(a >= b) # True(大于等于)
print(a <= b) # False(小于等于)
# 字符串比较
print("apple" < "banana") # True(按字典序)
运行测试:
# 比较两个数
x = 15
y = 20
if x > y:
print(f"{x} 大于 {y}")
elif x < y:
print(f"{x} 小于 {y}")
else:
print(f"{x} 等于 {y}")
3. 逻辑运算符
x = True
y = False
print(x and y) # False(逻辑与)
print(x or y) # True(逻辑或)
print(not x) # False(逻辑非)
# 实际应用
age = 20
has_license = True
can_drive = age >= 18 and has_license
print(f"可以开车:{can_drive}") # True
运行测试:
# 判断成绩等级
score = 85
if score >= 90:
grade = "优秀"
elif score >= 80:
grade = "良好"
elif score >= 60:
grade = "及格"
else:
grade = "不及格"
print(f"分数:{score},等级:{grade}")
4. 赋值运算符
x = 10
x += 5 # x = x + 5,结果是 15
x -= 3 # x = x - 3,结果是 12
x *= 2 # x = x * 2,结果是 24
x /= 4 # x = x / 4,结果是 6.0
x //= 2 # x = x // 2,结果是 3.0
x %= 2 # x = x % 2,结果是 1.0
x **= 3 # x = x ** 3,结果是 1.0
print(x)
运行测试:
# 计数器示例
count = 0
count += 1 # 增加 1
count += 1 # 再增加 1
print(f"计数:{count}") # 2
5. 成员运算符
# in 和 not in
text = "Hello, Python!"
print("Python" in text) # True
print("Java" not in text) # True
numbers = [1, 2, 3, 4, 5]
print(3 in numbers) # True
print(10 not in numbers) # True
运行测试:
# 检查用户名是否有效
username = "admin"
forbidden = ["admin", "root", "test"]
if username in forbidden:
print("用户名不可用")
else:
print("用户名可用")
6. 身份运算符
# is 和 is not(比较对象身份,不是值)
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x == y) # True(值相等)
print(x is y) # False(不是同一个对象)
print(x is z) # True(是同一个对象)
# 小整数和字符串会被缓存
a = 100
b = 100
print(a is b) # True(小整数被缓存)
运行测试:
# 测试身份运算符
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(f"list1 == list2: {list1 == list2}") # True
print(f"list1 is list2: {list1 is list2}") # False
print(f"list1 is list3: {list1 is list3}") # True
第五部分:数据结构
1. 列表(List)
列表是有序、可变的集合。
# 创建列表
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# 访问元素
print(fruits[0]) # apple(第一个元素)
print(fruits[-1]) # orange(最后一个元素)
# 修改元素
fruits[0] = "grape"
print(fruits) # ['grape', 'banana', 'orange']
# 添加元素
fruits.append("mango") # 末尾添加
fruits.insert(1, "pear") # 指定位置插入
print(fruits)
# 删除元素
fruits.remove("banana") # 删除指定值
popped = fruits.pop() # 删除并返回最后一个元素
del fruits[0] # 删除指定索引的元素
print(fruits)
# 列表切片
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # [2, 3, 4](索引 2 到 4)
print(numbers[:3]) # [0, 1, 2](前 3 个)
print(numbers[5:]) # [5, 6, 7, 8, 9](从索引 5 开始)
print(numbers[::2]) # [0, 2, 4, 6, 8](步长为 2)
# 列表方法
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(len(numbers)) # 8(长度)
print(numbers.count(1)) # 2(计数)
print(numbers.index(4)) # 2(索引)
numbers.sort() # 排序(原地)
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
numbers.reverse() # 反转
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
运行测试:
# 创建一个购物清单
shopping_list = []
shopping_list.append("苹果")
shopping_list.append("香蕉")
shopping_list.append("橙子")
print("购物清单:", shopping_list)
# 检查是否购买完成
if "苹果" in shopping_list:
print("已购买苹果")
2. 元组(Tuple)
元组是有序、不可变的集合。
# 创建元组
coordinates = (10, 20)
colors = ("red", "green", "blue")
single = (42,) # 单个元素的元组需要逗号
# 访问元素
print(coordinates[0]) # 10
print(colors[1]) # green
# 元组不可修改
# coordinates[0] = 15 # 错误!元组不可变
# 元组解包
x, y = coordinates
print(f"x = {x}, y = {y}")
# 元组方法
numbers = (1, 2, 3, 2, 4, 2)
print(numbers.count(2)) # 3(计数)
print(numbers.index(3)) # 2(索引)
运行测试:
# 使用元组存储坐标
point1 = (3, 4)
point2 = (6, 8)
# 计算两点距离
import math
distance = math.sqrt((point2[0] - point1[0])**2 +
(point2[1] - point1[1])**2)
print(f"两点距离:{distance:.2f}")
3. 字典(Dictionary)
字典是键值对的集合,无序、可变。
# 创建字典
student = {
"name": "Alice",
"age": 20,
"grade": "A"
}
# 访问元素
print(student["name"]) # Alice
print(student.get("age")) # 20
print(student.get("email", "未设置")) # 未设置(默认值)
# 修改和添加
student["age"] = 21 # 修改
student["email"] = "alice@example.com" # 添加
print(student)
# 删除元素
del student["grade"]
email = student.pop("email")
print(student)
# 字典方法
print(student.keys()) # dict_keys(['name', 'age'])
print(student.values()) # dict_values(['Alice', 21])
print(student.items()) # dict_items([('name', 'Alice'), ('age', 21)])
# 遍历字典
for key, value in student.items():
print(f"{key}: {value}")
运行测试:
# 创建一个简单的通讯录
contacts = {
"Alice": "123-456-7890",
"Bob": "234-567-8901",
"Charlie": "345-678-9012"
}
# 查找联系人
name = "Alice"
if name in contacts:
print(f"{name} 的电话:{contacts[name]}")
else:
print(f"未找到 {name}")
4. 集合(Set)
集合是无序、唯一元素的集合。
# 创建集合
fruits = {"apple", "banana", "orange"}
numbers = {1, 2, 3, 4, 5}
# 添加元素
fruits.add("mango")
fruits.update(["grape", "kiwi"])
print(fruits)
# 删除元素
fruits.remove("banana") # 如果不存在会报错
fruits.discard("pear") # 如果不存在不会报错
popped = fruits.pop() # 删除并返回任意元素
print(fruits)
# 集合运算
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8}(并集)
print(set1 & set2) # {4, 5}(交集)
print(set1 - set2) # {1, 2, 3}(差集)
print(set1 ^ set2) # {1, 2, 3, 6, 7, 8}(对称差集)
运行测试:
# 找出两个列表的共同元素
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
set1 = set(list1)
set2 = set(list2)
common = set1 & set2
print(f"共同元素:{common}")
第六部分:控制流
1. if 语句
# 基本 if 语句
age = 20
if age >= 18:
print("已成年")
# if-else 语句
age = 15
if age >= 18:
print("已成年")
else:
print("未成年")
# if-elif-else 语句
score = 85
if score >= 90:
grade = "优秀"
elif score >= 80:
grade = "良好"
elif score >= 60:
grade = "及格"
else:
grade = "不及格"
print(f"等级:{grade}")
# 嵌套 if
age = 20
has_license = True
if age >= 18:
if has_license:
print("可以开车")
else:
print("需要驾照")
else:
print("年龄不够")
运行测试:
# 判断数字的正负
number = -5
if number > 0:
print("正数")
elif number < 0:
print("负数")
else:
print("零")
2. for 循环
# 遍历列表
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# 遍历字符串
text = "Python"
for char in text:
print(char)
# 使用 range()
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(2, 5):
print(i) # 2, 3, 4
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# 遍历字典
student = {"name": "Alice", "age": 20, "grade": "A"}
for key in student:
print(f"{key}: {student[key]}")
for key, value in student.items():
print(f"{key}: {value}")
# enumerate() 获取索引
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
运行测试:
# 计算 1 到 10 的和
total = 0
for i in range(1, 11):
total += i
print(f"1 到 10 的和:{total}")
3. while 循环
# 基本 while 循环
count = 0
while count < 5:
print(count)
count += 1
# 无限循环(需要 break)
while True:
user_input = input("输入 'quit' 退出:")
if user_input == "quit":
break
print(f"你输入了:{user_input}")
# continue 跳过当前迭代
for i in range(10):
if i % 2 == 0:
continue # 跳过偶数
print(i) # 只打印奇数
运行测试:
# 猜数字游戏
import random
target = random.randint(1, 10)
guess = 0
attempts = 0
while guess != target:
guess = int(input("猜一个 1-10 的数字:"))
attempts += 1
if guess < target:
print("太小了")
elif guess > target:
print("太大了")
else:
print(f"恭喜!你用了 {attempts} 次猜对了")
4. 循环控制语句
# break:跳出循环
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# continue:跳过当前迭代
for i in range(10):
if i % 2 == 0:
continue
print(i) # 1, 3, 5, 7, 9
# else:循环正常结束时执行
for i in range(5):
print(i)
else:
print("循环正常结束")
# 如果 break,else 不执行
for i in range(5):
if i == 3:
break
print(i)
else:
print("这不会执行")
运行测试:
# 查找列表中的第一个偶数
numbers = [1, 3, 5, 8, 9, 11]
for num in numbers:
if num % 2 == 0:
print(f"找到第一个偶数:{num}")
break
else:
print("没有找到偶数")
第七部分:函数
1. 定义函数
# 基本函数
def greet():
print("Hello, World!")
greet() # 调用函数
# 带参数的函数
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Hello, Alice!
# 多个参数
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
# 默认参数
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Hi") # Hi, Bob!
# 关键字参数
def introduce(name, age, city):
print(f"我是 {name},{age} 岁,来自 {city}")
introduce(name="Alice", age=20, city="Beijing")
introduce(city="Shanghai", name="Bob", age=25)
# 可变参数
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15
# 关键字可变参数
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=20, city="Beijing")
运行测试:
# 定义一个计算面积的函数
def calculate_area(length, width):
return length * width
area = calculate_area(5, 3)
print(f"面积:{area}")
2. 返回值
# 返回单个值
def square(x):
return x ** 2
result = square(5)
print(result) # 25
# 返回多个值(实际上是元组)
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder
q, r = divide(10, 3)
print(f"商:{q},余数:{r}")
# 无返回值(返回 None)
def do_nothing():
pass
result = do_nothing()
print(result) # None
运行测试:
# 计算圆的面积和周长
import math
def circle_info(radius):
area = math.pi * radius ** 2
circumference = 2 * math.pi * radius
return area, circumference
r = 5
area, circ = circle_info(r)
print(f"半径:{r}")
print(f"面积:{area:.2f}")
print(f"周长:{circ:.2f}")
3. Lambda 函数
# Lambda 函数(匿名函数)
square = lambda x: x ** 2
print(square(5)) # 25
# 与 map() 一起使用
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# 与 filter() 一起使用
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]
# 与 sorted() 一起使用
students = [("Alice", 20), ("Bob", 18), ("Charlie", 22)]
sorted_by_age = sorted(students, key=lambda x: x[1])
print(sorted_by_age) # [('Bob', 18), ('Alice', 20), ('Charlie', 22)]
运行测试:
# 使用 lambda 函数过滤列表
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
greater_than_5 = list(filter(lambda x: x > 5, numbers))
print(f"大于 5 的数:{greater_than_5}")
4. 作用域
# 全局变量和局部变量
x = 10 # 全局变量
def func():
x = 20 # 局部变量
print(f"局部 x: {x}")
func()
print(f"全局 x: {x}") # 全局变量不变
# 使用 global 关键字
x = 10
def func():
global x
x = 20 # 修改全局变量
print(f"函数内 x: {x}")
func()
print(f"函数外 x: {x}") # 全局变量被修改
运行测试:
# 计数器函数
def create_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
my_counter = create_counter()
print(my_counter()) # 1
print(my_counter()) # 2
print(my_counter()) # 3
第八部分:字符串操作
1. 字符串方法
text = " Hello, Python! "
# 大小写转换
print(text.upper()) # " HELLO, PYTHON! "
print(text.lower()) # " hello, python! "
print(text.title()) # " Hello, Python! "
print(text.capitalize()) # " hello, python! "
# 去除空白
print(text.strip()) # "Hello, Python!"
print(text.lstrip()) # "Hello, Python! "
print(text.rstrip()) # " Hello, Python!"
# 查找和替换
text = "Hello, Python!"
print(text.find("Python")) # 7(索引)
print(text.replace("Python", "World")) # "Hello, World!"
# 分割和连接
text = "apple,banana,orange"
fruits = text.split(",")
print(fruits) # ['apple', 'banana', 'orange']
fruits = ["apple", "banana", "orange"]
text = ",".join(fruits)
print(text) # "apple,banana,orange"
# 检查内容
text = "Hello123"
print(text.isalpha()) # False(不全是字母)
print(text.isdigit()) # False(不全是数字)
print(text.isalnum()) # True(字母或数字)
print(text.startswith("Hello")) # True
print(text.endswith("123")) # True
运行测试:
# 处理用户输入
user_input = " alice@example.com "
email = user_input.strip().lower()
print(f"清理后的邮箱:{email}")
2. 字符串格式化
name = "Alice"
age = 20
# f-string(推荐)
message = f"我的名字是 {name},年龄是 {age}"
print(message)
# 格式化数字
pi = 3.14159
print(f"π ≈ {pi:.2f}") # π ≈ 3.14
# format() 方法
message = "我的名字是 {},年龄是 {}".format(name, age)
print(message)
message = "我的名字是 {name},年龄是 {age}".format(name=name, age=age)
print(message)
# % 格式化(旧方法)
message = "我的名字是 %s,年龄是 %d" % (name, age)
print(message)
运行测试:
# 格式化输出表格
students = [
("Alice", 20, 85.5),
("Bob", 19, 92.0),
("Charlie", 21, 78.5)
]
for name, age, score in students:
print(f"{name:10} {age:3} 岁 分数:{score:5.1f}")
第九部分:文件操作
1. 读取文件
# 读取整个文件
with open("example.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 逐行读取
with open("example.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip()) # strip() 去除换行符
# 读取所有行
with open("example.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
print(line.strip())
运行测试:
# 创建测试文件并读取
# 首先创建文件
with open("test.txt", "w", encoding="utf-8") as f:
f.write("第一行\n")
f.write("第二行\n")
f.write("第三行\n")
# 然后读取
with open("test.txt", "r", encoding="utf-8") as f:
content = f.read()
print("文件内容:")
print(content)
2. 写入文件
# 写入文件(覆盖)
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("这是第二行\n")
# 追加到文件
with open("output.txt", "a", encoding="utf-8") as f:
f.write("这是追加的内容\n")
# 写入多行
lines = ["第一行\n", "第二行\n", "第三行\n"]
with open("output.txt", "w", encoding="utf-8") as f:
f.writelines(lines)
运行测试:
# 保存数据到文件
data = [
"姓名,年龄,城市",
"Alice,20,Beijing",
"Bob,25,Shanghai",
"Charlie,30,Guangzhou"
]
with open("data.csv", "w", encoding="utf-8") as f:
for line in data:
f.write(line + "\n")
print("数据已保存到 data.csv")
3. 文件操作模式
# 模式说明
# "r" - 只读(默认)
# "w" - 写入(覆盖)
# "a" - 追加
# "x" - 创建(文件不存在时)
# "b" - 二进制模式
# "t" - 文本模式(默认)
# "+" - 读写模式
# 示例
with open("file.txt", "r") as f: # 只读
content = f.read()
with open("file.txt", "w") as f: # 写入(覆盖)
f.write("新内容")
with open("file.txt", "a") as f: # 追加
f.write("追加内容")
with open("file.txt", "r+") as f: # 读写
content = f.read()
f.write("新内容")
运行测试:
# 复制文件
source_file = "source.txt"
target_file = "target.txt"
# 创建源文件
with open(source_file, "w", encoding="utf-8") as f:
f.write("这是源文件的内容\n")
# 复制文件
with open(source_file, "r", encoding="utf-8") as src:
with open(target_file, "w", encoding="utf-8") as dst:
dst.write(src.read())
print("文件复制完成")
第十部分:异常处理
1. try-except
# 基本异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零!")
# 捕获多个异常
try:
number = int(input("输入一个数字:"))
result = 10 / number
except ValueError:
print("输入的不是有效数字")
except ZeroDivisionError:
print("不能除以零")
except Exception as e:
print(f"发生错误:{e}")
# else:没有异常时执行
try:
result = 10 / 2
except ZeroDivisionError:
print("错误")
else:
print(f"结果:{result}")
# finally:无论是否异常都执行
try:
file = open("test.txt", "r")
content = file.read()
except FileNotFoundError:
print("文件不存在")
finally:
print("清理工作")
# file.close() # 如果文件打开,关闭它
运行测试:
# 安全的除法函数
def safe_divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("错误:除数不能为零")
return None
except TypeError:
print("错误:参数类型不正确")
return None
print(safe_divide(10, 2)) # 5.0
print(safe_divide(10, 0)) # None(错误)
print(safe_divide(10, "2")) # None(错误)
2. 抛出异常
# raise 抛出异常
def check_age(age):
if age < 0:
raise ValueError("年龄不能为负数")
if age > 150:
raise ValueError("年龄不合理")
return True
try:
check_age(-5)
except ValueError as e:
print(f"错误:{e}")
# 自定义异常
class CustomError(Exception):
pass
def test():
raise CustomError("这是自定义异常")
try:
test()
except CustomError as e:
print(f"捕获自定义异常:{e}")
运行测试:
# 验证密码强度
class PasswordTooShortError(Exception):
pass
def validate_password(password):
if len(password) < 8:
raise PasswordTooShortError("密码长度至少 8 位")
return True
try:
validate_password("123")
except PasswordTooShortError as e:
print(f"密码验证失败:{e}")
第十一部分:面向对象编程基础
1. 类和对象
# 定义类
class Dog:
# 类属性
species = "Canis familiaris"
# 初始化方法
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
# 实例方法
def bark(self):
return f"{self.name} 在叫:汪汪!"
def get_info(self):
return f"{self.name} 是一只 {self.age} 岁的狗"
# 创建对象
dog1 = Dog("旺财", 3)
dog2 = Dog("小黑", 5)
print(dog1.bark())
print(dog2.get_info())
print(f"种类:{Dog.species}")
运行测试:
# 创建一个简单的银行账户类
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
return f"存款 {amount},余额:{self.balance}"
def withdraw(self, amount):
if amount > self.balance:
return "余额不足"
self.balance -= amount
return f"取款 {amount},余额:{self.balance}"
def get_balance(self):
return f"账户余额:{self.balance}"
# 使用
account = BankAccount("Alice", 1000)
print(account.deposit(500))
print(account.withdraw(200))
print(account.get_balance())
2. 继承
# 父类
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} 发出声音"
# 子类
class Dog(Animal):
def speak(self):
return f"{self.name} 在叫:汪汪!"
class Cat(Animal):
def speak(self):
return f"{self.name} 在叫:喵喵!"
# 使用
dog = Dog("旺财")
cat = Cat("小花")
print(dog.speak())
print(cat.speak())
运行测试:
# 形状类继承示例
class Shape:
def __init__(self, color):
self.color = color
def area(self):
raise NotImplementedError("子类必须实现 area 方法")
class Rectangle(Shape):
def __init__(self, color, width, height):
super().__init__(color)
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
def area(self):
import math
return math.pi * self.radius ** 2
# 使用
rect = Rectangle("红色", 5, 3)
circle = Circle("蓝色", 4)
print(f"矩形面积:{rect.area()}")
print(f"圆形面积:{circle.area():.2f}")
3. 特殊方法
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
# 使用
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p1) # Point(1, 2)
print(p3) # Point(4, 6)
print(p1 == p2) # False
运行测试:
# 创建一个简单的分数类
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return f"{self.numerator}/{self.denominator}"
def __add__(self, other):
new_num = self.numerator * other.denominator + other.numerator * self.denominator
new_den = self.denominator * other.denominator
return Fraction(new_num, new_den)
def __mul__(self, other):
return Fraction(self.numerator * other.numerator,
self.denominator * other.denominator)
# 使用
f1 = Fraction(1, 2)
f2 = Fraction(1, 3)
print(f"{f1} + {f2} = {f1 + f2}")
print(f"{f1} * {f2} = {f1 * f2}")
第十二部分:模块和包
1. 导入模块
# 导入整个模块
import math
print(math.pi)
print(math.sqrt(16))
# 导入特定函数
from math import sqrt, pi
print(pi)
print(sqrt(16))
# 导入所有(不推荐)
from math import *
print(sin(pi/2))
# 使用别名
import numpy as np
import pandas as pd
运行测试:
# 使用 datetime 模块
from datetime import datetime, timedelta
now = datetime.now()
print(f"当前时间:{now}")
tomorrow = now + timedelta(days=1)
print(f"明天:{tomorrow}")
# 格式化时间
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"格式化时间:{formatted}")
2. 创建模块
# 创建文件 my_module.py
# 内容:
"""
这是一个示例模块
"""
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
PI = 3.14159
# 在另一个文件中使用
# import my_module
# print(my_module.greet("Alice"))
# print(my_module.add(3, 5))
运行测试:
# 创建一个工具模块 utils.py
# 保存以下代码到 utils.py 文件:
def factorial(n):
"""计算阶乘"""
if n <= 1:
return 1
return n * factorial(n - 1)
def is_prime(n):
"""判断是否为质数"""
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
# 然后在主文件中使用:
# from utils import factorial, is_prime
# print(factorial(5)) # 120
# print(is_prime(7)) # True
第十三部分:综合练习
练习 1:计算器
def calculator():
"""简单的计算器"""
print("简单计算器")
print("支持操作:+, -, *, /")
try:
num1 = float(input("输入第一个数字:"))
operator = input("输入运算符:")
num2 = float(input("输入第二个数字:"))
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 == 0:
print("错误:除数不能为零")
return
result = num1 / num2
else:
print("不支持的运算符")
return
print(f"结果:{result}")
except ValueError:
print("错误:请输入有效数字")
# 运行
# calculator()
练习 2:学生成绩管理
class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
self.scores = []
def add_score(self, score):
self.scores.append(score)
def get_average(self):
if not self.scores:
return 0
return sum(self.scores) / len(self.scores)
def get_grade(self):
avg = self.get_average()
if avg >= 90:
return "A"
elif avg >= 80:
return "B"
elif avg >= 70:
return "C"
elif avg >= 60:
return "D"
else:
return "F"
def __str__(self):
return f"学生:{self.name}(学号:{self.student_id}),平均分:{self.get_average():.2f},等级:{self.get_grade()}"
# 使用示例
student = Student("Alice", "2024001")
student.add_score(85)
student.add_score(90)
student.add_score(78)
print(student)
练习 3:文件处理工具
def count_words(filename):
"""统计文件中的单词数"""
try:
with open(filename, "r", encoding="utf-8") as f:
content = f.read()
words = content.split()
return len(words)
except FileNotFoundError:
print(f"错误:文件 {filename} 不存在")
return 0
def find_longest_word(filename):
"""找出文件中最长的单词"""
try:
with open(filename, "r", encoding="utf-8") as f:
content = f.read()
words = content.split()
if not words:
return None
return max(words, key=len)
except FileNotFoundError:
print(f"错误:文件 {filename} 不存在")
return None
# 使用示例
# 首先创建测试文件
with open("test.txt", "w", encoding="utf-8") as f:
f.write("Python is a great programming language")
print(f"单词数:{count_words('test.txt')}")
print(f"最长单词:{find_longest_word('test.txt')}")
总结
通过本教程,你已经学习了 Python 的基础语法:
核心概念
- ✅ 基本语法:注释、缩进、变量
- ✅ 数据类型:整数、浮点数、字符串、布尔值
- ✅ 数据结构:列表、元组、字典、集合
- ✅ 控制流:if、for、while
- ✅ 函数:定义、调用、参数、返回值
- ✅ 字符串操作:方法、格式化
- ✅ 文件操作:读取、写入
- ✅ 异常处理:try-except
- ✅ 面向对象:类、对象、继承
- ✅ 模块:导入、创建
学习建议
- 多练习:复制代码运行,理解结果
- 多修改:尝试修改代码,观察变化
- 多实践:完成练习题,解决实际问题
- 多阅读:阅读 Python 官方文档和优秀代码
下一步学习
- 进阶主题:装饰器、生成器、上下文管理器
- 标准库:os、sys、collections、itertools
- 第三方库:NumPy、Pandas、Matplotlib
- 项目实践:Web 开发、数据分析、自动化脚本
记住:编程是一门实践性很强的技能,多写代码才能真正掌握!