01 — 数据类型
int_num = 42
float_num = 3.14
string_var = "Hello, Python!"
bool_var = True
02 — 变量和赋值
x = 10
y = "Python"
03 — 列表和元组
my_list = [1, 2, 3, "Python"]
my_tuple = (1, 2, 3, "Tuple")
04 — 字典
my_dict = {'name': 'John', 'age': 25, 'city': 'Pythonville'}
05 — 控制流程
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
for item in my_list:
print(item)
while condition:
# code
06 — 函数
def greet(name="User"):
return f"Hello, {name}!"
result = greet("John")
07 — 类和对象
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print("Woof!")
my_dog = Dog("Buddy")
my_dog.bark()
08 — 文件处理
with open("file.txt", "r") as file:
content = file.read()
with open("new_file.txt", "w") as new_file:
new_file.write("Hello, Python!")
09 — 异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution completed.")
10 — 库和模块
import math
from datetime import datetime
result = math.sqrt(25)
current_time = datetime.now()
11 — 列表推导式
squares = [x**2 for x in range(5)]
12 — Lambda 函数
add = lambda x, y: x + y
result = add(2, 3)
13 — 虚拟环境
# Create a virtual environment
python -m venv myenv
# Activate the virtual environment
source myenv/bin/activate # On Unix or MacOS
myenv\Scripts\activate # On Windows
# Deactivate the virtual environment
deactivate
14 — 包管理
# Install a package
pip install package_name
# List installed packages
pip list
# Create requirements.txt
pip freeze > requirements.txt
# Install packages from requirements.txt
pip install -r requirements.txt
15 — 使用 JSON
import json
# Convert Python object to JSON
json_data = json.dumps({"name": "John", "age": 25})
# Convert JSON to Python object
python_obj = json.loads(json_data)
16 — 正则表达式
import re
pattern = r'\d+' # Match one or more digits
result = re.findall(pattern, "There are 42 apples and 123 oranges.")
17 — 处理日期
from datetime import datetime, timedelta
current_date = datetime.now()
future_date = current_date + timedelta(days=7)
18 — 列表操作
numbers = [1, 2, 3, 4, 5]
# Filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Map
squared = list(map(lambda x: x**2, numbers))
# Reduce (requires functools)
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
19 — 字典操作
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Get value with default
value = my_dict.get('d', 0)
# Dictionary comprehension
squared_dict = {key: value**2 for key, value in my_dict.items()}
20 — 线程并发
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
21 — 与 Asyncio 的并发
import asyncio
async def print_numbers():
for i in range(5):
print(i)
await asyncio.sleep(1)
asyncio.run(print_numbers())
22 — 用 Beautiful Soup 进行网页抓取
from bs4 import BeautifulSoup
import requests
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.text
23 — 使用 Flask 的 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)
24 — 使用 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()
25 — 数据库与 SQLite 的交互
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Execute SQL query
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
# Commit changes
conn.commit()
# Close connection
conn.close()
26 — 文件处理
# Writing to a file
with open('example.txt', 'w') as file:
file.write('Hello, Python!')
# Reading from a file
with open('example.txt', 'r') as file:
content = file.read()
27 — 错误处理
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.")
28 — 使用 JSON
import json
data = {'name': 'John', 'age': 30}
# Convert Python object to JSON
json_data = json.dumps(data)
# Convert JSON to Python object
python_object = json.loads(json_data)
29 - Python 装饰器
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()
30 — 使用枚举
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED)
31 — 使用集合
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union
union_set = set1 | set2
# Intersection
intersection_set = set1 & set2
# Difference
difference_set = set1 - set2
32 — 列表推导式
numbers = [1, 2, 3, 4, 5]
# Squares of even numbers
squares = [x**2 for x in numbers if x % 2 == 0]
33 — Lambda 函数
add = lambda x, y: x + y
result = add(3, 5)
34 — 使用 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])
35 — 使用 gettext 进行国际化 (i18n)
import gettext
# Set language
lang = 'en_US'
_ = gettext.translation('messages', localedir='locale', languages=[lang]).gettext
print(_("Hello, World!"))
36 — 虚拟环境
# Create a virtual environment
python -m venv myenv
# Activate virtual environment
source myenv/bin/activate # On Unix/Linux
myenv\Scripts\activate # On Windows
# Deactivate virtual environment
deactivate
37 — 使用日期
from datetime import datetime, timedelta
now = datetime.now()
# Format date
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# Add days to a date
future_date = now + timedelta(days=7)
38 — 使用字典
my_dict = {'name': 'John', 'age': 30}
# Get value with default
age = my_dict.get('age', 25)
# Iterate over keys and values
for key, value in my_dict.items():
print(f"{key}: {value}")
39 — 正则表达式
import re
text = "Hello, 123 World!"
# Match numbers
numbers = re.findall(r'\d+', text)
40 — 使用生成器
def square_numbers(n):
for i in range(n):
yield i**2
squares = square_numbers(5)
41 — 与 SQLite 的数据库交互
import sqlite3
# Connect to SQLite database
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
# Execute SQL query
cursor.execute('SELECT * FROM mytable')
42 — 使用 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')
43 — 使用请求和 BeautifulSoup 进行网页抓取
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Extract data from HTML
title = soup.title.text
44 — 使用 smtplib 发送电子邮件
import smtplib
from email.mime.text import MIMEText
# Set up email server
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
# Log in to email account
server.login('your_email@gmail.com', 'your_password')
# Send email
msg = MIMEText('Hello, Python!')
msg['Subject'] = 'Python Email'
server.sendmail('your_email@gmail.com', 'recipient@example.com', msg.as_string())
45 — 使用 JSON 文件
import json
data = {'name': 'John', 'age': 30}
# Write to JSON file
with open('data.json', 'w') as json_file:
json.dump(data, json_file)
# Read from JSON file
with open('data.json', 'r') as json_file:
loaded_data = json.load(json_file)