Python 備忘清單,一眼掃完核心知識點
數(shù)據(jù)類型
介紹Python中的不同數(shù)據(jù)類型,包括整數(shù)、浮點數(shù)、字符串和布爾值。
int_num = 42 # 整數(shù)
float_num = 3.14 # 浮點數(shù)
string_var = "Hello, Python!" # 字符串
bool_var = True # 布爾值
變量和賦值
展示如何在Python中聲明變量并給它們賦值。
x = 10 # 變量賦值
y = "Python"
列表 & 元組
解釋了列表和元組的創(chuàng)建,它們是Python中用于存儲序列的兩種主要數(shù)據(jù)結(jié)構(gòu)。
my_list = [1, 2, 3, "Python"] # 列表
my_tuple = (1, 2, 3, "Tuple") # 元組
字典
字典是Python中用于存儲鍵值對的另一種數(shù)據(jù)結(jié)構(gòu)。
my_dict = {'name': 'John', 'age': 25, 'city': 'Pythonville'} # 字典
控制流程
控制流程語句,如if-elif-else和for循環(huán),用于控制程序的執(zhí)行流程。
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
for item in my_list:
print(item)
while condition:
# code
函數(shù)
函數(shù)定義和調(diào)用的示例,展示了如何創(chuàng)建一個簡單的函數(shù)。
def greet(name="User"):
return f"Hello, {name}!"
result = greet("John")
類 & 對象
類和對象的使用,演示了如何定義一個類并創(chuàng)建類的實例。
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print("Woof!")
my_dog = Dog("Buddy")
my_dog.bark()
文件處理
文件操作的基本示例,包括讀取和寫入文件。
with open("file.txt", "r") as file:
content = file.read()
with open("new_file.txt", "w") as new_file:
new_file.write("Hello, Python!")
異常處理
異常處理的用法,展示了如何用try-except語句來處理可能的錯誤。
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution completed.")
庫 & 模塊
展示如何導入和使用Python的內(nèi)置庫和模塊。
import math
from datetime import datetime
result = math.sqrt(25)
current_time = datetime.now()
列表推導式
列表推導式的使用,提供了一種簡潔的方法來創(chuàng)建列表。
squares = [x**2 for x in range(5)] # 列表推導式
Lambda 函數(shù)
Lambda函數(shù)的用法,展示了如何創(chuàng)建匿名函數(shù)。
add = lambda x, y: x + y
result = add(2, 3)
虛擬環(huán)境
虛擬環(huán)境的創(chuàng)建和使用,用于隔離項目依賴。
# 創(chuàng)建虛擬環(huán)境
python -m venv myenv
# 激活虛擬環(huán)境
source myenv/bin/activate # 在Unix或MacOS
myenv\Scripts\activate # 在Windows
# 停用虛擬環(huán)境
deactivate
包管理
包管理工具pip的使用,用于安裝和管理Python包。
# 安裝包
pip install package_name
# 列出已安裝的包
pip list
# 創(chuàng)建requirements.txt
pip freeze > requirements.txt
# 從requirements.txt安裝包
pip install -r requirements.txt
與JSON的交互
JSON數(shù)據(jù)格式的轉(zhuǎn)換,展示了如何將Python對象轉(zhuǎn)換為JSON格式,以及反向操作。
import json
# 將Python對象轉(zhuǎn)換為JSON
json_data = json.dumps({"name": "John", "age": 25})
# 將JSON轉(zhuǎn)換為Python對象
python_obj = json.loads(json_data)
正則表達式
正則表達式的使用,用于字符串的搜索和操作。
import re
pattern = r'\d+' # 匹配一個或多個數(shù)字
result = re.findall(pattern, "There are 42 apples and 123 oranges.")
與日期的交互
日期和時間的處理,展示了如何獲取當前日期和計算未來日期。
from datetime import datetime, timedelta
current_date = datetime.now()
future_date = current_date + timedelta(days=7)
列表操作
列表的操作,包括過濾、映射和歸約。
numbers = [1, 2, 3, 4, 5]
# 過濾
evens = list(filter(lambda x: x % 2 == 0, numbers))
# 映射
squared = list(map(lambda x: x**2, numbers))
# 歸約 (需要functools)
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
字典操作
字典的操作,包括獲取值和字典推導式。
my_dict = {'a': 1, 'b': 2, 'c': 3}
# 獲取值
value = my_dict.get('d', 0)
# 字典推導式
squared_dict = {key: value**2 for key, value in my_dict.items()}
線程并發(fā)
線程的使用,展示了如何在Python中創(chuàng)建和管理線程。
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
Asyncio并發(fā)
Asyncio的使用,展示了如何在Python中進行異步編程。
import asyncio
async def print_numbers():
for i in range(5):
print(i)
await asyncio.sleep(1)
asyncio.run(print_numbers())
Web Scraping with Beautiful Soup
使用Beautiful Soup進行網(wǎng)頁抓取。
from bs4 import BeautifulSoup
import requests
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.text
RESTful API with Flask
使用Flask框架創(chuàng)建RESTful API。
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api/data', methods=['GET'])
def get_data():
data = {'key': 'value'}
return jsonify(data)
if __name__ == '__main__':
app.run(debug=True)
單元測試 with unittest
使用unittest進行單元測試。
import unittest
def add(x, y):
return x + y
class TestAddition(unittest.TestCase):
def test_add_positive_numbers(self):
self.assertEqual(add(2, 3), 5)
if __name__ == '__main__':
unittest.main()
數(shù)據(jù)庫交互 with SQLite
使用SQLite數(shù)據(jù)庫的交互。
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 執(zhí)行SQL查詢
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name')
# 提交更改
conn.commit()
# 關(guān)閉連接
conn.close()
文件處理
文件的讀寫操作。
# 寫入文件
with open('example.txt', 'w') as file:
file.write('Hello, Python!')
# 讀取文件
with open('example.txt', 'r') as file:
content = file.read()
錯誤處理
錯誤處理的示例。
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected Error: {e}")
else:
print("No errors occurred.")
finally:
print("This block always executes.")
Python Decorators
使用裝飾器的示例。
def decorator(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper
@decorator
def my_function():
print("Inside the function")
my_function()
枚舉 with Enums
使用枚舉類型的示例。
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED)
集合操作
集合的基本操作,包括并集、交集和差集。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 并集
union_set = set1 | set2
# 交集
intersection_set = set1 & set2
# 差集
difference_set = set1 - set2
列表推導式
使用列表推導式來生成特定條件的列表。
numbers = [1, 2, 3, 4, 5]
# 偶數(shù)的平方
squares = [x**2 for x in numbers if x % 2 == 0]
Lambda 函數(shù)
使用Lambda函數(shù)進行簡單的函數(shù)定義。
add = lambda x, y: x + y
result = add(3, 5)
線程與Concurrent.futures
使用concurrent.futures進行線程池操作。
from concurrent.futures import ThreadPoolExecutor
def square(x):
return x**2
with ThreadPoolExecutor() as executor:
results = executor.map(square, [1, 2, 3, 4, 5])
國際化 (i18n) with gettext
使用gettext進行國際化。
import gettext
# 設(shè)置語言
lang = 'en_US'
_ = gettext.translation('messages', localedir='locale', languages=[lang]).gette
print(_("Hello, World!"))
虛擬環(huán)境
虛擬環(huán)境的創(chuàng)建、激活和停用。
# 創(chuàng)建虛擬環(huán)境
python -m venv myenv
# 激活虛擬環(huán)境
source myenv/bin/activate # 在Unix/Linux
myenv\Scripts\activate # 在Windows
# 停用虛擬環(huán)境
deactivate
日期操作
日期的格式化和天數(shù)的添加。
from datetime import datetime, timedelta
now = datetime.now()
# 格式化日期
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# 給日期添加天數(shù)
future_date = now + timedelta(days=7)
字典操作
字典的值獲取和遍歷。
my_dict = {'name': 'John', 'age': 30}
# 獲取值,并設(shè)置默認值
age = my_dict.get('age', 25)
# 遍歷鍵和值
for key, value in my_dict.items():
print(f"{key}: {value}")
正則表達式
使用正則表達式匹配字符串中的數(shù)字。
import re
text = "Hello, 123 World!"
# 匹配數(shù)字
numbers = re.findall(r'\d+', text)
生成器
使用生成器生成一系列值。
def square_numbers(n):
for i in range(n):
yield i**2
squares = square_numbers(5)
數(shù)據(jù)庫交互 with SQLite
使用SQLite數(shù)據(jù)庫進行查詢。
import sqlite3
# 連接SQLite數(shù)據(jù)庫
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
# 執(zhí)行SQL查詢
cursor.execute('SELECT * FROM mytable')
操作ZIP文件
使用zipfile模塊創(chuàng)建和解壓ZIP文件。
import zipfile
with zipfile.ZipFile('archive.zip', 'w') as myzip:
myzip.write('file.txt')
with zipfile.ZipFile('archive.zip', 'r') as myzip:
myzip.extractall('extracted')
Web 爬蟲 requests 和 BeautifulSoup
使用requests和BeautifulSoup進行網(wǎng)頁抓取。
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 從HTML提取數(shù)據(jù)
title = soup.title.text
發(fā)送電子郵件 with smtplib
使用smtplib發(fā)送電子郵件。
import smtplib
from email.mime.text import MIMEText
# 設(shè)置郵件服務(wù)器
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
# 登錄郵箱賬戶
server.login('your_email@gmail.com', 'your_password')
# 發(fā)送郵件
msg = MIMEText('Hello, Python!')
msg['Subject'] = 'Python Email'
server.sendmail('your_email@gmail.com', 'recipient@example.com', msg.as_string())
操作JSON文件
JSON文件的讀寫操作。
import json
data = {'name': 'John', 'age': 30}
# 寫入JSON文件
with open('data.json', 'w') as json_file:
json.dump(data, json_file)
# 從JSON文件讀取
with open('data.json', 'r') as json_file:
loaded_data = json.load(json_file)
總結(jié)
這份Python備忘請單是一個全面而實用的Python編程快速參考資源。它覆蓋了從基礎(chǔ)的數(shù)據(jù)類型、變量賦值、控制流程、函數(shù)、類與對象、文件處理、異常處理到更高級的主題,如列表推導式、Lambda函數(shù)、虛擬環(huán)境、包管理、JSON操作、正則表達式、日期處理、集合操作、線程并發(fā)、異步編程、Web抓取、RESTful API開發(fā)、單元測試、數(shù)據(jù)庫交互、裝飾器、枚舉、國際化、生成器、ZIP文件操作、電子郵件發(fā)送等多個方面。
總的來說,備忘清單是為不同水平的Python開發(fā)者設(shè)計的,幫助大家快速查找和回顧編程中的關(guān)鍵概念和實用技巧。