Python 详细教程
目录
Python简介
安装与环境配置
基础语法和数据类型
数据结构
控制流程
函数编程
文件操作
面向对象编程
错误和异常处理
模块和包
数据科学库
Web开发
自动化脚本
最佳实践
1. Python简介
什么是Python?
Python是一种高级、解释型、通用的编程语言,由Guido van Rossum于1991年创建。它以简洁的语法和强大的功能而闻名。
Python的特点
简单易学,语法清晰
跨平台(Windows, macOS, Linux)
丰富的第三方库
面向对象和函数式编程支持
强大的社区支持
广泛应用于Web开发、数据科学、人工智能等领域
Python应用领域
Web开发(Django, Flask)
数据科学与机器学习(Pandas, NumPy, Scikit-learn)
自动化脚本
网络爬虫
游戏开发
科学计算
2. 安装与环境配置
安装Python
访问官网:https://www.python.org/
下载对应操作系统的安装包
安装时勾选"Add Python to PATH"
验证安装
1 2 3 4 5 6 python --version python3 --version python
安装开发工具
推荐IDE:
PyCharm(专业版)
VS Code(免费)
Jupyter Notebook(数据科学)
包管理工具pip
1 2 3 4 5 6 7 8 9 10 11 12 13 14 pip install package_name pip install --upgrade package_name pip uninstall package_name pip list pip install -r requirements.txt
3. 基础语法和数据类型
第一个Python程序
运行程序:
变量和赋值
1 2 3 4 5 6 7 8 9 10 11 12 name = "Alice" age = 25 height = 1.65 is_student = True x, y, z = 1 , 2 , 3 a = b = c = 0 x, y = y, x
基本数据类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 age = 25 print (type (age)) price = 19.99 print (type (price)) name = "Alice" message = 'Hello, World!' print (type (name)) is_active = True is_admin = False print (type (is_active)) result = None print (type (result))
基本运算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 a = 10 + 5 b = 10 - 5 c = 10 * 5 d = 10 / 3 e = 10 // 3 f = 10 % 3 g = 2 ** 3 print (10 > 5 ) print (10 == 5 ) print (10 != 5 ) print (10 <= 10 ) print (True and False ) print (True or False ) print (not True ) s1 = "Hello" s2 = "World" print (s1 + " " + s2) print (s1 * 3 )
输入输出
1 2 3 4 5 6 7 8 name = input ("请输入你的名字: " ) age = int (input ("请输入你的年龄: " )) print ("你好," , name)print (f"你今年{age} 岁了" ) print ("你今年{}岁了" .format (age))
4. 数据结构
字符串(String)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 s = "Hello, Python!" print (s.lower()) print (s.upper()) print (s.title()) print (s.strip()) print (s.replace("Python" , "World" )) print (s.split("," )) print ("," .join(["a" , "b" , "c" ])) print (s[0 ]) print (s[7 :13 ]) print (s[-7 :-1 ]) print (s[::-1 ]) name = "Alice" age = 25 print (f"姓名: {name} , 年龄: {age} " )print ("姓名: {}, 年龄: {}" .format (name, age))
列表(List)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 fruits = ["apple" , "banana" , "orange" ] numbers = [1 , 2 , 3 , 4 , 5 ] mixed = [1 , "hello" , 3.14 , True ] fruits.append("grape" ) fruits.insert(1 , "pear" ) fruits.remove("banana" ) popped = fruits.pop() fruits.sort() fruits.reverse() print (numbers[1 :3 ]) print (numbers[:3 ]) print (numbers[2 :]) print (numbers[::2 ]) squares = [x**2 for x in range (10 )] even_squares = [x**2 for x in range (10 ) if x % 2 == 0 ]
元组(Tuple)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 coordinates = (10 , 20 ) person = ("Alice" , 25 , "Engineer" ) single_tuple = (5 ,) print (coordinates[0 ]) print (coordinates[1 ]) x, y = coordinates print (len (coordinates))
字典(Dictionary)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 person = { "name" : "Alice" , "age" : 25 , "city" : "Beijing" } print (person["name" ]) person["job" ] = "Engineer" del person["city" ] print (person.get("age" )) print ("name" in person) print (person.keys()) print (person.values()) print (person.items()) squares = {x: x**2 for x in range (5 )}
集合(Set)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 fruits = {"apple" , "banana" , "orange" } numbers = set ([1 , 2 , 3 , 4 , 5 ]) fruits.add("grape" ) fruits.remove("banana" ) set1 = {1 , 2 , 3 } set2 = {2 , 3 , 4 } print (set1 | set2) print (set1 & set2) print (set1 - set2) print (set1 ^ set2)
5. 控制流程
条件语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 age = 18 if age < 13 : print ("儿童" ) elif age < 18 : print ("青少年" ) elif age < 60 : print ("成年人" ) else : print ("老年人" ) status = "成年" if age >= 18 else "未成年" print (status)score = 85 if score >= 90 and score <= 100 : grade = "A" elif score >= 80 : grade = "B" else : grade = "C"
循环语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 fruits = ["apple" , "banana" , "orange" ] for fruit in fruits: print (fruit) for i in range (5 ): print (i) for i in range (1 , 6 ): print (i) for i in range (0 , 10 , 2 ): print (i) count = 0 while count < 5 : print (count) count += 1 for i in range (10 ): if i == 3 : continue if i == 7 : break print (i)
枚举和zip
1 2 3 4 5 6 7 8 9 10 fruits = ["apple" , "banana" , "orange" ] for index, fruit in enumerate (fruits): print (f"{index} : {fruit} " ) names = ["Alice" , "Bob" , "Charlie" ] ages = [25 , 30 , 35 ] for name, age in zip (names, ages): print (f"{name} is {age} years old" )
6. 函数编程
函数定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 def greet (): print ("Hello, World!" ) def greet_name (name ): print (f"Hello, {name} !" ) def add (a, b ): return a + b greet() greet_name("Alice" ) result = add(5 , 3 )
参数类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 def greet (name, message="Hello" ): print (f"{message} , {name} !" ) greet(message="Hi" , name="Bob" ) def sum_all (*numbers ): return sum (numbers) print (sum_all(1 , 2 , 3 , 4 , 5 ))def print_info (**info ): for key, value in info.items(): print (f"{key} : {value} " ) print_info(name="Alice" , age=25 , city="Beijing" )
函数高级特性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 def apply_operation (x, y, operation ): return operation(x, y) def multiply (a, b ): return a * b result = apply_operation(5 , 3 , multiply) square = lambda x: x ** 2 result = apply_operation(5 , 3 , lambda a, b: a + b) def make_multiplier (n ): def multiplier (x ): return x * n return multiplier double = make_multiplier(2 ) print (double(5 ))
装饰器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 def my_decorator (func ): def wrapper (): print ("函数执行前" ) func() print ("函数执行后" ) return wrapper @my_decorator def say_hello (): print ("Hello!" ) say_hello() def repeat (n ): def decorator (func ): def wrapper (*args, **kwargs ): for _ in range (n): result = func(*args, **kwargs) return result return wrapper return decorator @repeat(3 ) def greet (name ): print (f"Hello, {name} !" ) greet("Alice" )
7. 文件操作
文件读写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 with open ("example.txt" , "w" , encoding="utf-8" ) as file: file.write("Hello, World!\n" ) file.write("这是第二行\n" ) with open ("example.txt" , "r" , encoding="utf-8" ) as file: content = file.read() print (content) with open ("example.txt" , "r" , encoding="utf-8" ) as file: for line in file: print (line.strip()) with open ("example.txt" , "r" , encoding="utf-8" ) as file: lines = file.readlines() for line in lines: print (line.strip())
CSV文件操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import csvwith open ("data.csv" , "w" , newline="" , encoding="utf-8" ) as file: writer = csv.writer(file) writer.writerow(["姓名" , "年龄" , "城市" ]) writer.writerow(["Alice" , 25 , "Beijing" ]) writer.writerow(["Bob" , 30 , "Shanghai" ]) with open ("data.csv" , "r" , encoding="utf-8" ) as file: reader = csv.reader(file) for row in reader: print (row) with open ("data.csv" , "r" , encoding="utf-8" ) as file: reader = csv.DictReader(file) for row in reader: print (f"{row['姓名' ]} - {row['年龄' ]} - {row['城市' ]} " )
JSON文件操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import jsondata = { "name" : "Alice" , "age" : 25 , "hobbies" : ["reading" , "swimming" ], "address" : { "city" : "Beijing" , "street" : "Main St" } } with open ("data.json" , "w" , encoding="utf-8" ) as file: json.dump(data, file, ensure_ascii=False , indent=2 ) with open ("data.json" , "r" , encoding="utf-8" ) as file: loaded_data = json.load(file) print (loaded_data)
8. 面向对象编程
类和对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class Person : species = "人类" def __init__ (self, name, age ): self.name = name self.age = age def introduce (self ): return f"我叫{self.name} ,今年{self.age} 岁" @classmethod def get_species (cls ): return cls.species @staticmethod def is_adult (age ): return age >= 18 person1 = Person("Alice" , 25 ) person2 = Person("Bob" , 30 ) print (person1.name)print (person1.introduce())print (Person.get_species())print (Person.is_adult(20 ))
继承和多态
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class Animal : def __init__ (self, name ): self.name = name def speak (self ): raise NotImplementedError("子类必须实现此方法" ) class Dog (Animal ): def speak (self ): return f"{self.name} 说: 汪汪!" class Cat (Animal ): def speak (self ): return f"{self.name} 说: 喵喵!" def animal_sound (animal ): print (animal.speak()) dog = Dog("旺财" ) cat = Cat("咪咪" ) animal_sound(dog) animal_sound(cat)
封装和属性控制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class BankAccount : def __init__ (self, owner, balance=0 ): self.owner = owner self._balance = balance self.__account_id = "12345" @property def balance (self ): return self._balance @balance.setter def balance (self, amount ): if amount < 0 : raise ValueError("余额不能为负" ) self._balance = amount def deposit (self, amount ): if amount > 0 : self._balance += amount return True return False def withdraw (self, amount ): if 0 < amount <= self._balance: self._balance -= amount return True return False account = BankAccount("Alice" , 1000 ) account.deposit(500 ) account.withdraw(200 ) print (account.balance)
9. 错误和异常处理
异常处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 try : number = int (input ("请输入一个数字: " )) result = 10 / number print (f"结果是: {result} " ) except ValueError: print ("输入的不是有效数字!" ) except ZeroDivisionError: print ("不能除以零!" ) except Exception as e: print (f"发生错误: {e} " ) else : print ("计算成功!" ) finally : print ("程序执行完毕" ) def validate_age (age ): if age < 0 : raise ValueError("年龄不能为负数" ) if age > 150 : raise ValueError("年龄不能超过150" ) return True try : validate_age(-5 ) except ValueError as e: print (f"验证失败: {e} " )
自定义异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class InsufficientFundsError (Exception ): def __init__ (self, balance, amount ): self.balance = balance self.amount = amount super ().__init__(f"余额不足。当前余额: {balance} , 需要: {amount} " ) class BankAccount : def __init__ (self, balance=0 ): self.balance = balance def withdraw (self, amount ): if amount > self.balance: raise InsufficientFundsError(self.balance, amount) self.balance -= amount return self.balance account = BankAccount(100 ) try : account.withdraw(200 ) except InsufficientFundsError as e: print (e)
10. 模块和包
创建和使用模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 def add (a, b ): return a + b def subtract (a, b ): return a - b def multiply (a, b ): return a * b def divide (a, b ): if b == 0 : raise ValueError("不能除以零" ) return a / b import math_operations as mofrom math_operations import add, multiplyprint (mo.add(5 , 3 ))print (add(10 , 2 ))print (multiply(4 , 5 ))
创建包
1 2 3 4 5 6 7 my_package/ __init__.py math_ops.py string_ops.py utils/ __init__.py helpers.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 def factorial (n ): if n == 0 : return 1 return n * factorial(n - 1 ) def is_prime (n ): if n < 2 : return False for i in range (2 , int (n**0.5 ) + 1 ): if n % i == 0 : return False return True def reverse_string (s ): return s[::-1 ] def count_vowels (s ): vowels = "aeiouAEIOU" return sum (1 for char in s if char in vowels) from my_package import math_ops, string_opsprint (math_ops.factorial(5 ))print (string_ops.reverse_string("hello" ))
常用内置模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 import mathimport randomimport datetimeimport osimport sysprint (math.sqrt(16 ))print (math.pi)print (math.sin(math.pi/2 ))print (random.random()) print (random.randint(1 , 10 )) print (random.choice(["a" , "b" , "c" ])) now = datetime.datetime.now() print (now)print (now.strftime("%Y-%m-%d %H:%M:%S" ))print (os.getcwd()) print (os.listdir("." )) print (sys.version) print (sys.path)
11. 数据科学库
NumPy - 数值计算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import numpy as nparr1 = np.array([1 , 2 , 3 , 4 , 5 ]) arr2 = np.zeros((3 , 3 )) arr3 = np.ones((2 , 4 )) arr4 = np.arange(0 , 10 , 2 ) print (arr1.shape) print (arr1.dtype) print (arr1 + 2 ) print (np.dot(arr1, arr1)) matrix = np.array([[1 , 2 , 3 ], [4 , 5 , 6 ], [7 , 8 , 9 ]]) print (matrix[1 , 2 ]) print (matrix[:, 1 ])
Pandas - 数据分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import pandas as pddata = { 'Name' : ['Alice' , 'Bob' , 'Charlie' , 'David' ], 'Age' : [25 , 30 , 35 , 28 ], 'City' : ['Beijing' , 'Shanghai' , 'Guangzhou' , 'Shenzhen' ], 'Salary' : [50000 , 60000 , 70000 , 55000 ] } df = pd.DataFrame(data) print (df)print (df.head(2 )) print (df.describe()) print (df[df['Age' ] > 28 ]) print (df.groupby('City' )['Salary' ].mean())
Matplotlib - 数据可视化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 import matplotlib.pyplot as pltimport numpy as npx = np.linspace(0 , 10 , 100 ) y = np.sin(x) plt.figure(figsize=(10 , 6 )) plt.plot(x, y, label='sin(x)' ) plt.title('正弦函数' ) plt.xlabel('x' ) plt.ylabel('sin(x)' ) plt.legend() plt.grid(True ) plt.show() categories = ['A' , 'B' , 'C' , 'D' ] values = [23 , 45 , 56 , 78 ] plt.figure(figsize=(8 , 6 )) plt.bar(categories, values, color='skyblue' ) plt.title('柱状图示例' ) plt.xlabel('类别' ) plt.ylabel('数值' ) plt.show() x = np.random.randn(100 ) y = np.random.randn(100 ) colors = np.random.rand(100 ) sizes = 1000 * np.random.rand(100 ) plt.figure(figsize=(8 , 6 )) plt.scatter(x, y, c=colors, s=sizes, alpha=0.5 ) plt.title('散点图示例' ) plt.xlabel('X' ) plt.ylabel('Y' ) plt.colorbar() plt.show()
12. Web开发
Flask Web框架
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 from flask import Flask, render_template, request, jsonifyapp = Flask(__name__) @app.route('/' ) def home (): return '欢迎来到首页!' @app.route('/hello/<name>' ) def hello (name ): return f'Hello, {name} !' @app.route('/user' , methods=['GET' , 'POST' ] ) def user (): if request.method == 'POST' : name = request.form['name' ] return f'用户 {name} 已创建!' return ''' <form method="post"> <input type="text" name="name"> <input type="submit" value="提交"> </form> ''' @app.route('/api/data' ) def api_data (): data = { 'name' : 'Alice' , 'age' : 25 , 'city' : 'Beijing' } return jsonify(data) if __name__ == '__main__' : app.run(debug=True )
网络请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import requestsresponse = requests.get('https://api.github.com/users/octocat' ) data = response.json() print (data['login' ], data['public_repos' ])payload = {'key1' : 'value1' , 'key2' : 'value2' } response = requests.post('https://httpbin.org/post' , data=payload) print (response.json())headers = {'User-Agent' : 'my-app/0.0.1' } response = requests.get('https://api.github.com/users/octocat' , headers=headers)
13. 自动化脚本
文件批量处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import osimport shutilfor root, dirs, files in os.walk('.' ): for file in files: if file.endswith('.txt' ): file_path = os.path.join(root, file) print (f"找到文本文件: {file_path} " ) def batch_rename (directory, prefix ): for i, filename in enumerate (os.listdir(directory)): if filename.endswith('.txt' ): new_name = f"{prefix} _{i+1 } .txt" 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} " )
发送邮件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartdef send_email (to_email, subject, message ): smtp_server = "smtp.gmail.com" port = 587 sender_email = "your_email@gmail.com" password = "your_password" msg = MIMEMultipart() msg['From' ] = sender_email msg['To' ] = to_email msg['Subject' ] = subject msg.attach(MIMEText(message, 'plain' )) try : server = smtplib.SMTP(smtp_server, port) server.starttls() server.login(sender_email, password) text = msg.as_string() server.sendmail(sender_email, to_email, text) print ("邮件发送成功!" ) except Exception as e: print (f"邮件发送失败: {e} " ) finally : server.quit()
14. 最佳实践
代码风格(PEP 8)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 def calculate_area (length, width ): """ 计算矩形面积 Args: length (float): 长度 width (float): 宽度 Returns: float: 面积 """ if length <= 0 or width <= 0 : raise ValueError("长度和宽度必须为正数" ) area = length * width return area from typing import List , Dict , Optional def process_data ( data: List [Dict [str , int ]], threshold: Optional [int ] = None ) -> List [Dict [str , int ]]: """处理数据,过滤掉值小于阈期的项目""" if threshold is None : return data filtered_data = [ item for item in data if all (value >= threshold for value in item.values()) ] return filtered_data
单元测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import unittestdef add (a, b ): return a + b class TestMathOperations (unittest.TestCase): def test_add_positive_numbers (self ): self.assertEqual(add(2 , 3 ), 5 ) def test_add_negative_numbers (self ): self.assertEqual(add(-1 , -1 ), -2 ) def test_add_zero (self ): self.assertEqual(add(5 , 0 ), 5 ) def test_add_floats (self ): self.assertAlmostEqual(add(1.1 , 2.2 ), 3.3 , places=1 ) if __name__ == '__main__' : unittest.main()
虚拟环境
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 python -m venv myenv myenv\Scripts\activate source myenv/bin/activatepip install requests pandas numpy pip freeze > requirements.txt pip install -r requirements.txt deactivate
性能优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 def read_large_file (file_path ): with open (file_path, 'r' ) as file: for line in file: yield line.strip() squares = [x**2 for x in range (1000 )] def calculate_sum (numbers ): total = 0 add = total += for num in numbers: add(num) return total numbers = [1 , 2 , 3 , 4 , 5 ] total = sum (numbers) maximum = max (numbers)
学习资源推荐
官方文档
在线学习平台
实践项目
计算器应用
待办事项列表
网络爬虫
数据可视化仪表板
简单的Web应用
进阶学习
《Python编程:从入门到实践》
《流畅的Python》
《Effective Python》
这个Python教程涵盖了从基础到高级的主要知识点。建议按照顺序学习,每个章节都动手实践代码。Python的学习最重要的是多写代码、多解决问题,通过实际项目来巩固所学知识。祝各位学习顺利!