一、Python概述
Python是一种高级、通用、解释型编程语言,以其简洁的语法、强大的库生态和广泛的应用场景而闻名。
1.1 Python特点
- 简单易学:语法简洁,代码可读性高
- 跨平台:支持Windows、Linux、macOS等
- 丰富的库:拥有强大的标准库和第三方库
- 面向对象:支持面向对象编程
- 动态类型:无需声明变量类型
- 解释执行:无需编译,直接运行
1.2 Python版本
| 版本 | 发布时间 | 支持状态 |
|---|---|---|
| Python 2.7 | 2010年 | 已停止支持 |
| Python 3.6 | 2016年 | 安全更新中 |
| Python 3.8 | 2019年 | 安全更新中 |
| Python 3.10 | 2021年 | 活跃支持 |
| Python 3.12 | 2023年 | 最新版本 |
二、环境搭建
2.1 安装Python
# Windows安装
1. 访问 https://www.python.org/downloads/
2. 下载对应版本的安装包
3. 运行安装程序,勾选"Add Python to PATH"
4. 点击"Install Now"
5. 验证安装:cmd中运行 `python --version`
# Linux安装
# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip
# CentOS/RHEL
sudo yum install python3 python3-pip
# 验证安装
python3 --version
pip3 --version
# macOS安装
# 方法1:使用Homebrew
brew install python
# 方法2:下载安装包
访问 https://www.python.org/downloads/ 下载并安装
# 验证安装
python3 --version
pip3 --version
2.2 虚拟环境
# 创建虚拟环境
# Windows
python -m venv venv
# Linux/macOS
python3 -m venv venv
# 激活虚拟环境
# Windows
venv\Scripts\activate
# Linux/macOS
source venv/bin/activate
# 退出虚拟环境
deactivate
# 使用虚拟环境
# 激活后安装包
pip install requests
# 导出依赖
pip freeze > requirements.txt
# 安装依赖
pip install -r requirements.txt
三、Python基础语法
3.1 基本数据类型
# 数值类型
# 整数
x = 10
print(x) # 10
# 浮点数
y = 3.14
print(y) # 3.14
# 复数
z = 1 + 2j
print(z) # (1+2j)
# 字符串
# 单引号
s1 = 'Hello'
print(s1) # Hello
# 双引号
s2 = "World"
print(s2) # World
# 三引号(多行字符串)
s3 = '''
Hello
World
'''
print(s3)
# 字符串操作
s = "Hello, World!"
print(len(s)) # 13
print(s[0]) # H
print(s[7:12]) # World
print(s.upper()) # HELLO, WORLD!
print(s.lower()) # hello, world!
print(s.replace("World", "Python")) # Hello, Python!
# 布尔值
b1 = True
b2 = False
print(b1 and b2) # False
print(b1 or b2) # True
print(not b1) # False
# 空值
x = None
print(x) # None
3.2 变量与运算符
# 变量赋值
x = 10
y = "Hello"
z = 3.14
# 多重赋值
x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3
# 算术运算符
print(10 + 3) # 13
print(10 - 3) # 7
print(10 * 3) # 30
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3
print(10 % 3) # 1
print(10 ** 3) # 1000
# 比较运算符
print(10 > 3) # True
print(10 < 3) # False
print(10 == 3) # False
print(10 != 3) # True
print(10 >= 3) # True
print(10 <= 3) # False
# 逻辑运算符
print(True and False) # False
print(True or False) # True
print(not True) # False
# 成员运算符
print('a' in 'abc') # True
print('x' not in 'abc') # True
# 身份运算符
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # False
print(x is not y) # True
3.3 控制结构
# if语句
x = 10
if x > 0:
print("正数")
elif x < 0:
print("负数")
else:
print("零")
# for循环
for i in range(5):
print(i) # 0 1 2 3 4
for i in range(1, 10, 2):
print(i) # 1 3 5 7 9
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# while循环
i = 0
while i < 5:
print(i)
i += 1
# break和continue
for i in range(10):
if i == 5:
break
print(i)
for i in range(10):
if i % 2 == 0:
continue
print(i)
# 列表推导式
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares) # [1, 4, 9, 16, 25]
# 条件列表推导式
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
3.4 函数
# 定义函数
def greet(name):
"""问候函数"""
print(f"Hello, {name}!")
# 调用函数
greet("Alice") # Hello, Alice!
# 带返回值的函数
def add(a, b):
"""加法函数"""
return a + b
result = add(3, 5)
print(result) # 8
# 带默认参数的函数
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Bob") # Hello, Bob!
greet("Bob", "Hi") # Hi, Bob!
# 可变参数
def sum_numbers(*args):
total = 0
for num in args:
total += num
return total
print(sum_numbers(1, 2, 3, 4, 5)) # 15
# 关键字参数
def person_info(name, age, **kwargs):
print(f"Name: {name}")
print(f"Age: {age}")
for key, value in kwargs.items():
print(f"{key}: {value}")
person_info("Alice", 30, city="New York", job="Engineer")
# 匿名函数
double = lambda x: x * 2
print(double(5)) # 10
# 高阶函数
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]
# 过滤
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]
四、数据结构
4.1 列表 (List)
# 创建列表
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
# 访问元素
print(numbers[0]) # 1
print(numbers[-1]) # 5
# 切片
print(numbers[1:3]) # [2, 3]
print(numbers[:3]) # [1, 2, 3]
print(numbers[2:]) # [3, 4, 5]
# 修改元素
numbers[0] = 10
print(numbers) # [10, 2, 3, 4, 5]
# 添加元素
numbers.append(6)
print(numbers) # [10, 2, 3, 4, 5, 6]
numbers.insert(0, 0)
print(numbers) # [0, 10, 2, 3, 4, 5, 6]
# 移除元素
numbers.remove(10)
print(numbers) # [0, 2, 3, 4, 5, 6]
numbers.pop()
print(numbers) # [0, 2, 3, 4, 5]
# 列表方法
print(len(numbers)) # 5
print(max(numbers)) # 5
print(min(numbers)) # 0
print(sum(numbers)) # 14
numbers.sort()
print(numbers) # [0, 2, 3, 4, 5]
numbers.reverse()
print(numbers) # [5, 4, 3, 2, 0]
# 列表复制
numbers_copy = numbers.copy()
print(numbers_copy) # [5, 4, 3, 2, 0]
4.2 元组 (Tuple)
# 创建元组
numbers = (1, 2, 3, 4, 5)
fruits = ("apple", "banana", "cherry")
# 访问元素
print(numbers[0]) # 1
print(numbers[-1]) # 5
# 切片
print(numbers[1:3]) # (2, 3)
# 元组不可修改
# numbers[0] = 10 # 会报错
# 元组方法
print(len(numbers)) # 5
print(max(numbers)) # 5
print(min(numbers)) # 1
print(sum(numbers)) # 15
# 元组转换
list_from_tuple = list(numbers)
print(list_from_tuple) # [1, 2, 3, 4, 5]
tuple_from_list = tuple([1, 2, 3])
print(tuple_from_list) # (1, 2, 3)
4.3 字典 (Dictionary)
# 创建字典
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# 访问元素
print(person["name"]) # Alice
print(person.get("age")) # 30
print(person.get("job", "Unknown")) # Unknown
# 修改元素
person["age"] = 31
print(person) # {'name': 'Alice', 'age': 31, 'city': 'New York'}
# 添加元素
person["job"] = "Engineer"
print(person) # {'name': 'Alice', 'age': 31, 'city': 'New York', 'job': 'Engineer'}
# 移除元素
person.pop("city")
print(person) # {'name': 'Alice', 'age': 31, 'job': 'Engineer'}
# 字典方法
print(len(person)) # 3
print(person.keys()) # dict_keys(['name', 'age', 'job'])
print(person.values()) # dict_values(['Alice', 31, 'Engineer'])
print(person.items()) # dict_items([('name', 'Alice'), ('age', 31), ('job', 'Engineer')])
# 遍历字典
for key in person:
print(key, person[key])
for key, value in person.items():
print(key, value)
# 字典复制
person_copy = person.copy()
print(person_copy) # {'name': 'Alice', 'age': 31, 'job': 'Engineer'}
# 清空字典
person.clear()
print(person) # {}
4.4 集合 (Set)
# 创建集合
numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "cherry"}
# 添加元素
numbers.add(6)
print(numbers) # {1, 2, 3, 4, 5, 6}
# 移除元素
numbers.remove(1)
print(numbers) # {2, 3, 4, 5, 6}
# 集合运算
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# 并集
print(set1 | set2) # {1, 2, 3, 4, 5, 6}
print(set1.union(set2)) # {1, 2, 3, 4, 5, 6}
# 交集
print(set1 & set2) # {3, 4}
print(set1.intersection(set2)) # {3, 4}
# 差集
print(set1 - set2) # {1, 2}
print(set1.difference(set2)) # {1, 2}
# 对称差集
print(set1 ^ set2) # {1, 2, 5, 6}
print(set1.symmetric_difference(set2)) # {1, 2, 5, 6}
# 集合方法
print(len(numbers)) # 5
print(3 in numbers) # True
print(10 in numbers) # False
# 集合转换
set_from_list = set([1, 2, 3, 3, 4])
print(set_from_list) # {1, 2, 3, 4}
list_from_set = list({1, 2, 3})
print(list_from_set) # [1, 2, 3]
五、面向对象编程
5.1 类和对象
# 定义类
class Person:
# 类属性
species = "Homo sapiens"
# 初始化方法
def __init__(self, name, age):
# 实例属性
self.name = name
self.age = age
# 实例方法
def greet(self):
return f"Hello, my name is {self.name}"
def get_age(self):
return self.age
# 类方法
@classmethod
def get_species(cls):
return cls.species
# 静态方法
@staticmethod
def is_adult(age):
return age >= 18
# 创建对象
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# 访问属性
print(person1.name) # Alice
print(person2.age) # 25
print(Person.species) # Homo sapiens
# 调用方法
print(person1.greet()) # Hello, my name is Alice
print(person2.get_age()) # 25
print(Person.get_species()) # Homo sapiens
print(Person.is_adult(18)) # True
# 修改属性
person1.age = 31
print(person1.age) # 31
5.2 继承
# 父类
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
# 子类
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# 创建对象
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.name) # Buddy
print(dog.speak()) # Woof!
print(cat.name) # Whiskers
print(cat.speak()) # Meow!
# 多重继承
class A:
def method(self):
print("A.method")
class B:
def method(self):
print("B.method")
class C(A, B):
pass
c = C()
c.method() # A.method (MRO - Method Resolution Order)
5.3 多态
def animal_speak(animal):
print(animal.speak())
dog = Dog("Buddy")
cat = Cat("Whiskers")
animal_speak(dog) # Woof!
animal_speak(cat) # Meow!
5.4 封装
class Person:
def __init__(self, name, age):
self._name = name # 受保护属性
self.__age = age # 私有属性
def get_name(self):
return self._name
def set_name(self, name):
self._name = name
def get_age(self):
return self.__age
def set_age(self, age):
if age > 0:
self.__age = age
person = Person("Alice", 30)
print(person.get_name()) # Alice
print(person.get_age()) # 30
person.set_name("Bob")
person.set_age(25)
print(person.get_name()) # Bob
print(person.get_age()) # 25
# 访问私有属性(不推荐)
print(person._Person__age) # 25
六、模块与包
6.1 模块
# 创建模块 (mymodule.py)
"""我的模块"""
def greet(name):
"""问候函数"""
return f"Hello, {name}!"
def add(a, b):
"""加法函数"""
return a + b
# 导入模块
import mymodule
print(mymodule.greet("Alice")) # Hello, Alice!
print(mymodule.add(3, 5)) # 8
# 导入指定函数
from mymodule import greet, add
print(greet("Bob")) # Hello, Bob!
print(add(2, 4)) # 6
# 导入所有函数
from mymodule import *
print(greet("Charlie")) # Hello, Charlie!
print(add(1, 1)) # 2
# 别名
import mymodule as mm
print(mm.greet("David")) # Hello, David!
from mymodule import greet as g
print(g("Eve")) # Hello, Eve!
6.2 包
# 创建包
# mypackage/
# ├── __init__.py
# ├── module1.py
# └── module2.py
# __init__.py
"""我的包"""
# module1.py
def func1():
return "Function 1"
# module2.py
def func2():
return "Function 2"
# 导入包
import mypackage
# 导入模块
from mypackage import module1, module2
print(module1.func1()) # Function 1
print(module2.func2()) # Function 2
# 直接导入函数
from mypackage.module1 import func1
from mypackage.module2 import func2
print(func1()) # Function 1
print(func2()) # Function 2
七、异常处理
7.1 基本异常处理
# try-except
try:
x = 10 / 0
except ZeroDivisionError:
print("除数不能为零")
except Exception as e:
print(f"发生错误: {e}")
else:
print("没有发生错误")
finally:
print("无论是否发生错误都会执行")
# 捕获多个异常
try:
x = int(input("请输入一个整数: "))
y = 10 / x
except ValueError:
print("输入的不是整数")
except ZeroDivisionError:
print("除数不能为零")
except Exception as e:
print(f"发生错误: {e}")
# 抛出异常
def divide(a, b):
if b == 0:
raise ZeroDivisionError("除数不能为零")
return a / b
try:
result = divide(10, 0)
except ZeroDivisionError as e:
print(f"错误: {e}")
# 自定义异常
class MyError(Exception):
pass
try:
raise MyError("自定义错误")
except MyError as e:
print(f"捕获到自定义错误: {e}")
八、文件操作
8.1 文件读写
# 写入文件
with open("example.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("This is a test.\n")
# 读取文件
with open("example.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 逐行读取
with open("example.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
# 追加文件
with open("example.txt", "a", encoding="utf-8") as f:
f.write("Append line.\n")
# 读取所有行
with open("example.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
print(lines)
# 二进制文件
with open("image.jpg", "rb") as f:
data = f.read()
with open("copy.jpg", "wb") as f:
f.write(data)
8.2 文件路径操作
import os
import os.path
import pathlib
# 当前目录
print(os.getcwd())
# 列出目录内容
print(os.listdir("."))
# 创建目录
os.makedirs("mydir", exist_ok=True)
# 删除目录
os.rmdir("mydir")
# 文件重命名
os.rename("old.txt", "new.txt")
# 删除文件
os.remove("example.txt")
# 检查文件是否存在
print(os.path.exists("example.txt"))
# 检查是否是文件
print(os.path.isfile("example.txt"))
# 检查是否是目录
print(os.path.isdir("mydir"))
# 获取绝对路径
print(os.path.abspath("."))
# 路径拼接
print(os.path.join("dir", "file.txt"))
# 使用pathlib
path = pathlib.Path(".")
print(path.absolute())
print(list(path.glob("*.py")))
九、常用库
9.1 标准库
# math库
import math
print(math.pi) # 3.1415926535897693
print(math.sqrt(16)) # 4.0
print(math.sin(math.pi/2)) # 1.0
# random库
import random
print(random.random()) # 0-1之间的随机数
print(random.randint(1, 10)) # 1-10之间的随机整数
print(random.choice([1, 2, 3, 4, 5])) # 随机选择
# datetime库
import datetime
now = datetime.datetime.now()
print(now)
print(now.year, now.month, now.day)
# 时间差
delta = datetime.timedelta(days=1)
tomorrow = now + delta
print(tomorrow)
# 格式化时间
print(now.strftime("%Y-%m-%d %H:%M:%S"))
# time库
import time
print(time.time()) # 时间戳
time.sleep(1) # 休眠1秒
# json库
import json
# 字典转JSON
data = {"name": "Alice", "age": 30}
json_str = json.dumps(data)
print(json_str)
# JSON转字典
json_data = json.loads(json_str)
print(json_data)
# 读写JSON文件
with open("data.json", "w") as f:
json.dump(data, f)
with open("data.json", "r") as f:
loaded_data = json.load(f)
print(loaded_data)
9.2 第三方库
# 安装第三方库
# pip install requests
# pip install numpy
# pip install pandas
# pip install matplotlib
# requests库
import requests
response = requests.get("https://api.github.com/users/octocat")
print(response.status_code)
print(response.json())
# numpy库
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(arr.mean())
print(arr.sum())
# pandas库
import pandas as pd
# 创建DataFrame
df = pd.DataFrame({
"name": ["Alice", "Bob", "Charlie"],
"age": [30, 25, 35],
"city": ["New York", "London", "Paris"]
})
print(df)
# 读取CSV
# df = pd.read_csv("data.csv")
# 写入CSV
# df.to_csv("output.csv", index=False)
# matplotlib库
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Line Plot")
plt.savefig("plot.png")
# plt.show()
十、最佳实践
| 编程规范 | 建议 |
|---|---|
| 代码风格 | 遵循PEP 8规范 |
| 命名规范 | 变量和函数用小写,类名用驼峰式 |
| 注释 | 添加适当的注释和文档字符串 |
| 异常处理 | 合理使用try-except |
| 文件操作 | 使用with语句管理文件 |
| 虚拟环境 | 使用虚拟环境隔离依赖 |
| 代码组织 | 合理组织模块和包 |
| 测试 | 编写单元测试 |
注意事项:
- 使用4空格缩进,不要使用Tab
- 行长度不要超过79个字符
- 使用有意义的变量和函数名
- 避免使用全局变量
- 模块化代码,提高复用性
- 定期更新依赖包
- 使用版本控制管理代码
十一、总结
Python是一门功能强大且易于学习的编程语言。通过本培训文档,您应该掌握了:
from 培训视频:www.itpux.com
- Python环境搭建
- 基本语法和数据类型
- 控制结构和函数
- 数据结构(列表、元组、字典、集合)
- 面向对象编程
- 模块与包管理
- 异常处理
- 文件操作
- 常用库的使用
- 编程最佳实践
IT运维培训文档系列 | 第86篇 | Python编程基础培训
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
