Python 基础教程

发布于:2026-05-18 #Python#教程#基础 共 384 字 约 2 分钟

Python 语法简洁、生态丰富,适合脚本、数据处理、Web、自动化、AI 等场景。

检查 Python 版本

Bash
UTF-8|3 Lines|
python --version
# 或
python3 --version

推荐使用 Python 3.10 及以上版本。

变量与数据类型

Python
UTF-8|4 Lines|
name = "veyliss"
age = 18
height = 1.75
is_active = True
类型示例说明
str"hello"字符串
int100整数
float3.14浮点数
boolTrue / False布尔值
NoneTypeNone空值

type() 查看类型:

Python
UTF-8|2 Lines|
score = 95
print(type(score))

字符串

Python
UTF-8|11 Lines|
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())        # 按空白拆分

列表、元组、字典、集合

列表

Python
UTF-8|7 Lines|
names = ["Alice", "Bob", "Cindy"]
names.append("David")
names.remove("Bob")
print(names[0])

for name in names:
    print(name)

元组

Python
UTF-8|1 Line|
point = (10, 20)  # 不可修改

字典

Python
UTF-8|6 Lines|
user = {"name": "Alice", "age": 18, "city": "Shanghai"}
print(user["name"])
print(user.get("email", "未填写"))

for key, value in user.items():
    print(key, value)

集合

Python
UTF-8|8 Lines|
tags = {"Python", "入门", "Python"}  # 自动去重

a = {"Python", "Go", "JavaScript"}
b = {"Python", "Rust"}

print(a & b)  # 交集
print(a | b)  # 并集
print(a - b)  # 差集

条件判断

Python
UTF-8|8 Lines|
score = 86

if score >= 90:
    print("优秀")
elif score >= 60:
    print("合格")
else:
    print("不及格")

逻辑运算:

Python
UTF-8|2 Lines|
if age >= 18 and has_ticket:
    print("可以入场")

循环

for 循环

Python
UTF-8|6 Lines|
for i in range(5):
    print(i)

numbers = [1, 2, 3]
for n in numbers:
    print(n)

while 循环 + break/continue

Python
UTF-8|11 Lines|
count = 0
while count < 3:
    print(count)
    count += 1

for i in range(10):
    if i == 3:
        continue
    if i == 7:
        break
    print(i)

函数

Python
UTF-8|12 Lines|
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()

列表推导式

Python
UTF-8|4 Lines|
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers]

even = [n for n in numbers if n % 2 == 0]

文件读写

Python
UTF-8|12 Lines|
# 写文件
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())

异常处理

Python
UTF-8|15 Lines|
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("无论是否异常都执行")

模块导入

Python
UTF-8|8 Lines|
# 自定义模块
from utils import add
print(add(1, 2))

# 标准库
import datetime
now = datetime.datetime.now()
print(now)

常用标准库:os(系统操作)、pathlib(路径)、json(JSON)、datetime(日期时间)、random(随机数)、re(正则表达式)。

小练习:统计词频

Python
UTF-8|14 Lines|
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)

输出:

plaintext
UTF-8|6 Lines|
python 3
is 3
simple 1
powerful 1
learning 1
fun 1

总结

Python 学习路径:熟悉基础类型 → 掌握条件循环 → 用函数封装逻辑 → 用列表/字典组织数据 → 学会文件读写和异常处理 → 用模块组织代码。之后可深入学习 Web、数据分析或自动化方向。