Python 基础教程
Python 是一门语法简洁、生态丰富的编程语言。它适合写脚本、做数据处理、开发 Web 服务、自动化运维、爬虫、机器学习和 AI 应用。
这篇文章整理 Python 入门阶段最常用的语法。目标不是一次性覆盖所有细节,而是先建立一套清晰的基础框架,后续再按方向深入。
一、准备环境
Section titled “一、准备环境”检查 Python 版本
Section titled “检查 Python 版本”在终端中执行:
python --version如果系统里同时存在 Python 2 和 Python 3,也可以使用:
python3 --version建议使用 Python 3.10 及以上版本。
运行 Python 文件
Section titled “运行 Python 文件”创建一个文件:
hello.py写入:
print("Hello, Python")运行:
python hello.py二、变量与基础类型
Section titled “二、变量与基础类型”变量可以理解为给数据起名字。
name = "veyliss"age = 18height = 1.75is_active = TruePython 常见基础类型:
| 类型 | 示例 | 说明 |
|---|---|---|
str | "hello" | 字符串 |
int | 100 | 整数 |
float | 3.14 | 浮点数 |
bool | True / False | 布尔值 |
NoneType | None | 空值 |
可以使用 type() 查看变量类型:
score = 95print(type(score))字符串用于表示文本。
name = "Python"message = "Hello, " + nameprint(message)更推荐使用 f-string:
name = "Python"version = 3
print(f"Hello, {name} {version}")常用字符串方法:
text = " hello python "
print(text.strip()) # 去掉两侧空格print(text.upper()) # 转大写print(text.replace("python", "world"))print(text.split()) # 按空白拆分四、列表、元组、字典和集合
Section titled “四、列表、元组、字典和集合”列表用于保存一组有顺序的数据。
names = ["Alice", "Bob", "Cindy"]
print(names[0])names.append("David")names.remove("Bob")print(names)遍历列表:
for name in names: print(name)元组和列表类似,但创建后通常不再修改。
point = (10, 20)print(point[0])适合表示坐标、固定配置等不希望随意改变的数据。
字典用于保存键值对。
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"}print(tags)集合中的重复值会被自动去掉。
a = {"Python", "Go", "JavaScript"}b = {"Python", "Rust"}
print(a & b) # 交集print(a | b) # 并集print(a - b) # 差集五、条件判断
Section titled “五、条件判断”条件判断用于根据不同情况执行不同逻辑。
score = 86
if score >= 90: print("优秀")elif score >= 60: print("及格")else: print("不及格")常见比较运算:
age = 18
print(age > 16)print(age == 18)print(age != 20)多个条件可以组合:
age = 20has_ticket = True
if age >= 18 and has_ticket: print("可以入场")for 循环
Section titled “for 循环”for 常用于遍历列表、字符串、字典等可迭代对象。
numbers = [1, 2, 3, 4, 5]
for number in numbers: print(number)使用 range() 生成数字序列:
for i in range(5): print(i)while 循环
Section titled “while 循环”while 会在条件为真时持续执行。
count = 0
while count < 3: print(count) count += 1break 和 continue
Section titled “break 和 continue”for i in range(10): if i == 3: continue if i == 7: break print(i)continue:跳过本次循环。break:结束整个循环。
函数用于封装一段可复用逻辑。
def greet(name): return f"Hello, {name}"
message = greet("Python")print(message)函数可以有默认参数:
def connect(host, port=3306): print(f"connect to {host}:{port}")
connect("localhost")connect("localhost", 5432)也可以返回多个值:
def get_user(): return "Alice", 18
name, age = get_user()print(name, age)八、列表推导式
Section titled “八、列表推导式”列表推导式可以用更简洁的方式生成列表。
numbers = [1, 2, 3, 4, 5]squares = [number * number for number in numbers]
print(squares)带条件过滤:
even_numbers = [number for number in numbers if number % 2 == 0]print(even_numbers)列表推导式适合简单转换。如果逻辑复杂,使用普通 for 循环更清晰。
九、文件读写
Section titled “九、文件读写”with open("notes.txt", "w", encoding="utf-8") as file: file.write("Hello Python\n")with open("notes.txt", "r", encoding="utf-8") as file: content = file.read() print(content)with open("notes.txt", "r", encoding="utf-8") as file: for line in file: print(line.strip())with open() 会在代码块结束后自动关闭文件,推荐优先使用。
十、异常处理
Section titled “十、异常处理”异常处理用于捕获运行时错误,避免程序直接崩溃。
try: number = int("abc")except ValueError: print("转换失败")也可以捕获多个异常:
try: result = 10 / 0except ZeroDivisionError: print("不能除以 0")except Exception as error: print(f"未知错误:{error}")常见结构:
try: print("执行可能出错的代码")except Exception as error: print(error)else: print("没有异常时执行")finally: print("无论是否异常都会执行")十一、模块与包
Section titled “十一、模块与包”模块就是一个 Python 文件。可以把常用函数放到单独文件里,然后导入使用。
假设有一个文件:
utils.py内容:
def add(a, b): return a + b在另一个文件中导入:
from utils import add
print(add(1, 2))也可以导入标准库:
import datetime
now = datetime.datetime.now()print(now)常见标准库:
os:操作系统相关功能。pathlib:路径处理。json:JSON 编码和解析。datetime:日期时间。random:随机数。re:正则表达式。
十二、一个小练习:统计文本词频
Section titled “十二、一个小练习:统计文本词频”下面写一个简单的词频统计程序。
text = """python is simplepython is powerfullearning 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 3is 3simple 1powerful 1learning 1fun 1这个例子用到了:
- 字符串拆分。
- 字典。
- 循环。
- 计数逻辑。
Python 基础阶段可以按这个顺序练习:
- 熟悉变量、字符串和容器类型。
- 熟悉
if、for、while。 - 学会把重复逻辑封装成函数。
- 学会读写文件和处理异常。
- 多写小脚本,例如文件整理、日志统计、接口请求、网页解析。
不要只看语法。Python 入门最快的方式是写一些很小但真实的小工具。
Python 基础的核心不是记住所有语法,而是掌握几个稳定的能力:
- 能用变量和数据类型表达信息。
- 能用条件和循环控制流程。
- 能用函数封装逻辑。
- 能用列表、字典等容器组织数据。
- 能读写文件、处理异常、拆分模块。
掌握这些之后,就可以继续学习爬虫、Web 开发、数据分析、自动化脚本等更具体的方向。