🐍 Python 学习笔记(一)
记录 Python 编程基础,适合初学者快速上手与复习。
✨ 1. 基本语法
🖋️ 注释
1 2 3 4 5
| ''' 这是多行注释 可以用于文档说明 '''
|
🧮 变量与数据类型
1 2 3 4
| x = 10 y = 3.14 name = "Alice" is_ok = True
|
📦 数据类型转换
1 2 3
| int("123") str(456) float("3.14")
|
🔁 2. 控制语句
📍 条件判断
1 2 3 4 5 6 7
| age = 18 if age >= 18: print("成年") elif age >= 12: print("青少年") else: print("儿童")
|
🔄 循环语句
1 2 3 4 5 6 7 8 9
| for i in range(5): print(i)
n = 0 while n < 5: print(n) n += 1
|
📚 3. 数据结构
📃 列表 List
1 2 3
| fruits = ["apple", "banana", "cherry"] fruits.append("orange") print(fruits[1])
|
🧩 元组 Tuple
1 2
| point = (1, 2) x, y = point
|
🗂️ 字典 Dictionary
1 2 3
| person = {"name": "Tom", "age": 20} print(person["name"]) person["city"] = "Beijing"
|
📑 集合 Set
1 2
| nums = {1, 2, 3} nums.add(4)
|
🛠️ 4. 函数与模块
🔧 定义函数
1 2 3 4
| def greet(name): return f"Hello, {name}"
print(greet("Python"))
|
📦 导入模块
1 2
| import math print(math.sqrt(16))
|
📌 5. 文件操作
1 2 3 4 5 6 7 8
| with open("example.txt", "w") as f: f.write("Hello, file!")
with open("example.txt", "r") as f: content = f.read() print(content)
|
🧪 6. 异常处理
1 2 3 4 5 6
| try: x = 10 / 0 except ZeroDivisionError: print("不能除以0") finally: print("结束")
|
📘 小结: 本节内容涵盖 Python 的基本语法、控制流程、数据结构和文件处理,是入门 Python 的基石。后续将继续学习面向对象、常用模块与实战案例。