𝑻𝒆𝒏𝑪𝒍𝒂𝒘正在头脑风暴···
𝑻𝒆𝒏𝑲𝒊𝑺𝒆𝒀𝒂の𝑨𝒈𝒆𝒏𝒕助手
𝑻𝒆𝒏-𝒇𝒍𝒂𝒔𝒉

Python 基础与实战入门

Python 是一种简单、易学、功能强大的编程语言,广泛应用于 Web 开发、数据分析、人工智能等领域。本文将带你从零开始学习 Python 基础,掌握核心概念,并通过实战项目巩固所学知识。

一、Python 简介

1.1 什么是 Python?

Python 是一种解释型、面向对象的、动态类型的高级编程语言。它以简洁的语法和强大的功能著称,被广泛应用于各个领域。

1.2 Python 的特点

  1. 简单易学:语法简洁,接近英语
  2. 跨平台:支持 Windows、macOS、Linux 等多个平台
  3. 丰富的库:拥有庞大的第三方库生态系统
  4. 应用广泛:Web 开发、数据分析、人工智能、自动化等

1.3 Python 的应用领域

  • Web 开发:Django、Flask、FastAPI
  • 数据分析:Pandas、NumPy、Matplotlib
  • 人工智能:TensorFlow、PyTorch
  • 自动化脚本:系统自动化、办公自动化
  • 爬虫开发:Scrapy、BeautifulSoup

二、环境安装

2.1 下载 Python

访问 Python 官网 下载适合你操作系统的安装包。

2.2 安装 Python

  1. 运行安装程序
  2. 重要:勾选 “Add Python to PATH” 选项
  3. 选择 “Install Now” 或自定义安装

2.3 验证安装

# 打开终端或命令提示符
python --version
# 或
python3 --version

2.4 使用 VS Code

  1. 安装 VS Code
  2. 安装 Python 扩展
  3. 创建 .py 文件并编写代码

三、基础语法

3.1 变量与数据类型

变量

# 变量赋值
name = "张三"
age = 25
height = 1.75
is_student = True

# 多重赋值
a = b = c = 10
a, b = b, a # 交换变量

基本数据类型

# 整数
integer = 42
print(type(integer)) # <class 'int'>

# 浮点数
float_number = 3.14
print(type(float_number)) # <class 'float'>

# 字符串
string = "Hello, Python!"
print(type(string)) # <class 'str'>

# 布尔值
boolean = True
print(type(boolean)) # <class 'bool'>

# None
none_value = None
print(type(none_value)) # <class 'NoneType'>

类型转换

# 转换为字符串
str(123) # "123"
str(3.14) # "3.14"
str(True) # "True"

# 转换为整数
int("123") # 123
int(3.14) # 3
int(True) # 1
int(False) # 0

# 转换为浮点数
float("3.14") # 3.14
float(42) # 42.0

3.2 输入和输出

# 输出
print("Hello, World!")
print("名字:", name)
print(f"名字是 {name}, 年龄 {age} 岁")

# 格式化输出
print("名字是 %s, 年龄 %d 岁" % (name, age))
print("名字是 {}, 年龄 {} 岁".format(name, age))

# 输入
name = input("请输入你的名字: ")
age = int(input("请输入你的年龄: "))
print(f"你好, {name}! 你 {age} 岁。")

3.3 运算符

算术运算符

# 加法
print(2 + 3) # 5

# 减法
print(5 - 2) # 3

# 乘法
print(2 * 3) # 6

# 除法
print(6 / 2) # 3.0

# 整除
print(7 // 2) # 3

# 取余数
print(7 % 2) # 1

# 幂运算
print(2 ** 3) # 8

比较运算符

print(5 > 3)       # True
print(3 == 3) # True
print(5 != 3) # True
print(3 >= 3) # True
print(3 < 5) # True
print(3 <= 5) # True

逻辑运算符

# 与
print(True and False) # False

# 或
print(True or False) # True

# 非
print(not True) # False

3.4 控制流

条件语句

# 单一条件
age = 18
if age >= 18:
print("你是成年人")

# if-else
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")

# 嵌套条件
age = 20
has_ticket = True

if age >= 18:
if has_ticket:
print("你可以看电影")
else:
print("你需要买票")
else:
print("未成年人不能看电影")

循环

# for 循环
for i in range(5):
print(i) # 0 1 2 3 4

for i in range(1, 6):
print(i) # 1 2 3 4 5

# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(fruit)

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

# break 和 continue
for i in range(5):
if i == 3:
break # 跳出循环
print(i) # 0 1 2

for i in range(5):
if i == 2:
continue # 跳过当前迭代
print(i) # 0 1 3 4

3.5 数据结构

列表 (List)

# 创建列表
fruits = ["苹果", "香蕉", "橙子"]
numbers = [1, 2, 3, 4, 5]

# 访问元素
print(fruits[0]) # 苹果
print(fruits[-1]) # 橙子

# 修改元素
fruits[1] = "芒果"
print(fruits) # ['苹果', '芒果', '橙子']

# 列表操作
fruits.append("葡萄") # 添加元素
fruits.insert(0, "草莓") # 插入元素
fruits.remove("香蕉") # 删除元素
fruits.pop() # 删除最后一个元素
fruits.pop(0) # 删除指定索引元素
fruits.clear() # 清空列表
fruits.sort() # 排序
fruits.reverse() # 反转

元组 (Tuple)

# 创建元组
coordinates = (10, 20)
colors = ("红色", "绿色", "蓝色")

# 访问元素
print(coordinates[0]) # 10

# 元组是不可变的
# coordinates[0] = 15 # 错误!

字典 (Dictionary)

# 创建字典
user = {
"name": "张三",
"age": 25,
"email": "zhangsan@example.com"
}

# 访问元素
print(user["name"]) # 张三
print(user.get("age")) # 25

# 修改元素
user["age"] = 26
user["city"] = "北京"

# 删除元素
del user["email"]
user.pop("name")

# 字典方法
keys = user.keys() # 获取所有键
values = user.values() # 获取所有值
items = user.items() # 获取所有键值对

集合 (Set)

# 创建集合
unique_numbers = {1, 2, 3, 4, 5}
fruits = {"苹果", "香蕉", "橙子"}

# 集合是无序且唯一的
numbers = {1, 2, 2, 3, 3, 3} # 自动去重
print(numbers) # {1, 2, 3}

# 集合操作
unique_numbers.add(6) # 添加元素
unique_numbers.remove(2) # 删除元素

3.6 函数

定义函数

# 简单函数
def greet():
print("Hello, World!")

greet()

# 带参数的函数
def greet(name):
print(f"Hello, {name}!")

greet("张三")

# 带返回值的函数
def add(a, b):
return a + b

result = add(2, 3)
print(result) # 5

# 带默认参数的函数
def greet(name, greeting="你好"):
print(f"{greeting}, {name}!")

greet("张三") # 你好, 张三!
greet("张三", "欢迎") # 欢迎, 张三!

# 带关键字参数的函数
def introduce(name, age, city):
print(f"我是{name}, {age}岁, 来自{city}。")

introduce("张三", age=25, city="北京")

Lambda 函数

# 简单 lambda 函数
square = lambda x: x ** 2
print(square(5)) # 25

# 带多个参数的 lambda 函数
add = lambda a, b: a + b
print(add(2, 3)) # 5

# 排序
numbers = [3, 1, 4, 1, 5, 9]
sorted_numbers = sorted(numbers, key=lambda x: x ** 2)
print(sorted_numbers) # [1, 1, 3, 4, 5, 9]

四、文件操作

4.1 读取文件

# 打开文件
file = open("test.txt", "r", encoding="utf-8")

# 读取整个文件
content = file.read()
print(content)

# 逐行读取
file = open("test.txt", "r", encoding="utf-8")
for line in file:
print(line.strip())

# 读取指定行
file = open("test.txt", "r", encoding="utf-8")
first_line = file.readline()
print(first_line)

file.close()

4.2 写入文件

# 写入文件
file = open("test.txt", "w", encoding="utf-8")
file.write("Hello, World!\n")
file.write("这是一行文字。")
file.close()

# 追加写入
file = open("test.txt", "a", encoding="utf-8")
file.write("\n这是追加的内容。")
file.close()

4.3 使用 with 语句

# 推荐使用 with 语句自动管理文件
with open("test.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
# 自动关闭文件

# 写入文件
with open("test.txt", "w", encoding="utf-8") as file:
file.write("新内容\n")

五、模块和包

5.1 导入模块

# 导入整个模块
import math
print(math.pi) # 3.14159...

# 导入特定函数
from math import pi, sqrt
print(pi) # 3.14159...
print(sqrt(16)) # 4.0

# 导入模块并重命名
import math as m
print(m.pi)

# 导入模块中的所有内容(不推荐)
from math import *
print(pi) # 3.14159...
print(sqrt(16)) # 4.0

5.2 创建模块

# 创建 my_module.py
# def greet():
# print("Hello from module")

# import my_module
# my_module.greet()

5.3 标准库

# datetime
from datetime import datetime

now = datetime.now()
print(now) # 2024-12-15 14:30:00

# json
import json

data = {"name": "张三", "age": 25}
json_str = json.dumps(data)
print(json_str) # {"name": "张三", "age": 25}

data = json.loads(json_str)
print(data["name"]) # 张三

# re (正则表达式)
import re

pattern = r'\d+'
text = "电话号码: 123-456-7890"
matches = re.findall(pattern, text)
print(matches) # ['123', '456', '7890']

六、异常处理

# try-except
try:
result = 10 / 0
except ZeroDivisionError:
print("除零错误")

# try-except-else
try:
result = 10 / 2
except ZeroDivisionError:
print("除零错误")
else:
print(f"结果: {result}")

# try-except-finally
try:
file = open("test.txt", "r")
content = file.read()
except FileNotFoundError:
print("文件未找到")
finally:
print("清理资源")
if 'file' in locals():
file.close()

# 多个异常
try:
num = int("abc")
except ValueError:
print("无效的数字")
except Exception as e:
print(f"其他错误: {e}")

七、实战项目

7.1 简单计算器

def calculate():
print("简单计算器")
print("1. 加法")
print("2. 减法")
print("3. 乘法")
print("4. 除法")
print("5. 退出")

while True:
choice = input("请选择操作: ")

if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("输入第一个数字: "))
num2 = float(input("输入第二个数字: "))

if choice == '1':
result = num1 + num2
print(f"结果: {num1} + {num2} = {result}")
elif choice == '2':
result = num1 - num2
print(f"结果: {num1} - {num2} = {result}")
elif choice == '3':
result = num1 * num2
print(f"结果: {num1} × {num2} = {result}")
elif choice == '4':
if num2 == 0:
print("错误: 除数不能为零")
else:
result = num1 / num2
print(f"结果: {num1} ÷ {num2} = {result}")
except ValueError:
print("错误: 请输入有效的数字")
elif choice == '5':
print("退出计算器")
break
else:
print("无效的选择,请重新输入")

calculate()

7.2 文件批量重命名

import os
import re

def rename_files(directory):
"""批量重命名文件"""
files = os.listdir(directory)

for filename in files:
# 保留文件扩展名
ext = os.path.splitext(filename)[1]
# 提取数字部分
match = re.search(r'(\d+)', filename)
if match:
old_name = match.group(1)
new_number = int(old_name) + 1
# 构建新文件名
new_name = f"{new_number}{ext}"
# 旧路径和新路径
old_path = os.path.join(directory, filename)
new_path = os.path.join(directory, new_name)
# 重命名
os.rename(old_path, new_path)
print(f"{filename} -> {new_name}")

# 使用示例
# rename_files("/path/to/your/files")

7.3 简单的 HTTP 服务器

from http.server import HTTPServer, SimpleHTTPRequestHandler
import socketserver

# 自定义请求处理器
class CustomHandler(SimpleHTTPRequestHandler):
def log_message(self, format, *args):
# 自定义日志格式
print(f"[{self.log_date_time_string()}] {format % args}")

# 创建服务器
PORT = 8000
Handler = CustomHandler

with HTTPServer(("", PORT), Handler) as httpd:
print(f"服务器运行在 http://localhost:{PORT}")
print("按 Ctrl+C 停止服务器")
httpd.serve_forever()

7.4 数据分析示例

import random
import statistics

# 生成随机数据
data = [random.randint(1, 100) for _ in range(20)]

# 基本统计
print(f"数据: {data}")
print(f"平均值: {statistics.mean(data)}")
print(f"中位数: {statistics.median(data)}")
print(f"标准差: {statistics.stdev(data)}")
print(f"最小值: {min(data)}")
print(f"最大值: {max(data)}")

# 分组统计
odd_numbers = [x for x in data if x % 2 != 0]
even_numbers = [x for x in data if x % 2 == 0]

print(f"奇数: {odd_numbers}")
print(f"偶数: {even_numbers}")

八、最佳实践

8.1 代码规范

# 使用 PEP 8 规范

# 好的命名
class User:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name

# 使用类型提示
def greet(name: str) -> str:
"""返回问候语"""
return f"你好, {name}!"

# 使用 docstring
def calculate_average(numbers):
"""计算数字的平均值"""
return sum(numbers) / len(numbers)

8.2 错误处理

# 好的错误处理
try:
file = open("config.json", "r", encoding="utf-8")
data = json.load(file)
except FileNotFoundError:
print("配置文件未找到")
except json.JSONDecodeError:
print("配置文件格式错误")
except Exception as e:
print(f"未知错误: {e}")
finally:
if 'file' in locals():
file.close()

8.3 文档

# 使用 docstring 记录函数的功能

def process_data(data):
"""
处理输入数据并返回结果

参数:
data: 要处理的数据列表

返回:
处理后的数据列表

异常:
TypeError: 当输入不是列表时抛出
"""
if not isinstance(data, list):
raise TypeError("输入必须是列表")

return [x * 2 for x in data]

九、学习资源

9.1 官方资源

9.2 学习平台

9.3 书籍推荐

  • 《Python 编程:从入门到实践》
  • 《Python 核心编程》
  • 《流畅的 Python》

十、总结

Python 是一门强大且易学的编程语言,掌握基础知识后,你可以:

  1. 开发 Web 应用:使用 Flask、Django 等框架
  2. 进行数据分析:使用 Pandas、NumPy
  3. 构建机器学习模型:使用 TensorFlow、PyTorch
  4. 自动化任务:编写脚本处理重复性工作
  5. 开发爬虫:抓取网络数据

学习 Python 的关键:

  1. 动手实践:多写代码
  2. 循序渐进:从基础开始
  3. 解决问题:遇到问题先思考再搜索
  4. 持续学习:Python 生态系统在不断更新

开始你的 Python 学习之旅吧!