🐍 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 循环
for i in range(5):
print(i)

# while 循环
n = 0
while n < 5:
print(n)
n += 1

📚 3. 数据结构

📃 列表 List

1
2
3
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits[1]) # banana

🧩 元组 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)) # 输出:4.0

📌 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 的基石。后续将继续学习面向对象、常用模块与实战案例。