Python 基础教程
Python 语法简洁、生态丰富,适合脚本、数据处理、Web、自动化、AI 等场景。
检查 Python 版本
python --version
# 或
python3 --version推荐使用 Python 3.10 及以上版本。
变量与数据类型
name = "veyliss"
age = 18
height = 1.75
is_active = True| 类型 | 示例 | 说明 |
|---|---|---|
str | "hello" | 字符串 |
int | 100 | 整数 |
float | 3.14 | 浮点数 |
bool | True / False | 布尔值 |
NoneType | None | 空值 |
用 type() 查看类型:
score = 95
print(type(score))字符串
name = "Python"
# f-string 拼接
print(f"Hello, {name} 3")
# 常用方法
text = " hello python "
print(text.strip()) # 去除首尾空格
print(text.upper()) # 转大写
print(text.replace("python", "world"))
print(text.split()) # 按空白拆分列表、元组、字典、集合
列表
names = ["Alice", "Bob", "Cindy"]
names.append("David")
names.remove("Bob")
print(names[0])
for name in names:
print(name)元组
point = (10, 20) # 不可修改字典
user = {"name": "Alice", "age": 18, "city": "Shanghai"}
print(user["name"])
print(user.get("email", "未填写"))
for key, value in user.items():
print(key, value)集合
tags = {"Python", "入门", "Python"} # 自动去重
a = {"Python", "Go", "JavaScript"}
b = {"Python", "Rust"}
print(a & b) # 交集
print(a | b) # 并集
print(a - b) # 差集条件判断
score = 86
if score >= 90:
print("优秀")
elif score >= 60:
print("合格")
else:
print("不及格")逻辑运算:
if age >= 18 and has_ticket:
print("可以入场")循环
for 循环
for i in range(5):
print(i)
numbers = [1, 2, 3]
for n in numbers:
print(n)while 循环 + break/continue
count = 0
while count < 3:
print(count)
count += 1
for i in range(10):
if i == 3:
continue
if i == 7:
break
print(i)函数
def greet(name):
return f"Hello, {name}"
# 默认参数
def connect(host, port=3306):
print(f"connect to {host}:{port}")
# 返回多个值
def get_user():
return "Alice", 18
name, age = get_user()列表推导式
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers]
even = [n for n in numbers if n % 2 == 0]文件读写
# 写文件
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("Hello Python\n")
# 读文件
with open("notes.txt", "r", encoding="utf-8") as f:
content = f.read()
# 逐行读取
with open("notes.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())异常处理
try:
number = int("abc")
except ValueError:
print("转换失败")
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以 0")
except Exception as e:
print(f"未知错误: {e}")
else:
print("没有异常时执行")
finally:
print("无论是否异常都执行")模块导入
# 自定义模块
from utils import add
print(add(1, 2))
# 标准库
import datetime
now = datetime.datetime.now()
print(now)常用标准库:os(系统操作)、pathlib(路径)、json(JSON)、datetime(日期时间)、random(随机数)、re(正则表达式)。
小练习:统计词频
text = """
python is simple
python is powerful
learning python is fun
"""
words = text.split()
counter = {}
for word in words:
counter[word] = counter.get(word, 0) + 1
for word, count in counter.items():
print(word, count)输出:
python 3
is 3
simple 1
powerful 1
learning 1
fun 1总结
Python 学习路径:熟悉基础类型 → 掌握条件循环 → 用函数封装逻辑 → 用列表/字典组织数据 → 学会文件读写和异常处理 → 用模块组织代码。之后可深入学习 Web、数据分析或自动化方向。