百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

【Python备忘单】Python编程的快速参考指南

itomcoil 2025-03-14 18:04 25 浏览

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)

相关推荐

python创建文件夹,轻松搞定,喝咖啡去了

最近经常在录视频课程,一个课程下面往往有许多小课,需要分多个文件夹来放视频、PPT和案例,这下可好了,一个一个手工创建,手酸了都做不完。别急,来段PYTHON代码,轻松搞定,喝咖啡去了!import...

如何编写第一个Python程序_pycharm写第一个python程序

一、第一个python程序[掌握]python:python解释器,将python代码解释成计算机认识的语言pycharm:IDE(集成开发环境),写代码的一个软件,集成了写代码,...

Python文件怎么打包为exe程序?_python3.8打包成exe文件

PyInstaller是一个Python应用程序打包工具,它可以将Python程序打包为单个独立可执行文件。要使用PyInstaller打包Python程序,需要在命令行中使用py...

官方的Python环境_python环境版本

Python是一种解释型编程开发语言,根据Python语法编写出来的程序,需要经过Python解释器来进行执行。打开Python官网(https://www.python.org),找到下载页面,选择...

[编程基础] Python配置文件读取库ConfigParser总结

PythonConfigParser教程显示了如何使用ConfigParser在Python中使用配置文件。文章目录1介绍1.1PythonConfigParser读取文件1.2Python...

Python打包exe软件,用这个库真的很容易

初学Python的人会觉得开发一个exe软件非常复杂,其实不然,从.py到.exe文件的过程很简单。你甚至可以在一天之内用Python开发一个能正常运行的exe软件,因为Python有专门exe打包库...

2025 PyInstaller 打包说明(中文指南),python 打包成exe 都在这里

点赞标记,明天就能用上这几个技巧!linux运维、shell、python、网络爬虫、数据采集等定定做,请私信。。。PyInstaller打包说明(中文指南)下面按准备→基本使用→常用...

Python自动化办公应用学习笔记40—文件路径2

4.特殊路径操作用户主目录·获取当前用户的主目录路径非常常用:frompathlibimportPathhome_dir=Path.home()#返回当前用户主目录的Path对象...

Python内置tempfile模块: 生成临时文件和目录详解

1.引言在Python开发中,临时文件和目录的创建和管理是一个常见的需求。Python提供了内置模块tempfile,用于生成临时文件和目录。本文将详细介绍tempfile模块的使用方法、原理及相关...

python代码实现读取文件并生成韦恩图

00、背景今天战略解码,有同学用韦恩图展示各个产品线的占比,效果不错。韦恩图(Venndiagram),是在集合论数学分支中,在不太严格的意义下用以表示集合的一种图解。它们用于展示在不同的事物群组之...

Python技术解放双手,一键搞定海量文件重命名,一周工作量秒搞定

摘要:想象一下,周五傍晚,办公室的同事们纷纷准备享受周末,而你,面对着堆积如山的文件,需要将它们的文件名从美国日期格式改为欧洲日期格式,这似乎注定了你将与加班为伍。但别担心,Python自动化办公来...

Python路径操作的一些基础方法_python路径文件

带你走进@机器人时代Discover点击上面蓝色文字,关注我们Python自动化操作文件避开不了路径操作方法,今天我们来学习一下路径操作的一些基础。Pathlib库模块提供的路径操作包括路径的...

Python爬取下载m3u8加密视频,原来这么简单

1.前言爬取视频的时候发现,现在的视频都是经过加密(m3u8),不再是mp4或者avi链接直接在网页显示,都是经过加密形成ts文件分段进行播放。今天就教大家如果通过python爬取下载m3u8加密视频...

探秘 shutil:Python 高级文件操作的得力助手

在Python的标准库中,shutil模块犹如一位技艺精湛的工匠,为我们处理文件和目录提供了一系列高级操作功能。无论是文件的复制、移动、删除,还是归档与解压缩,shutil都能以简洁高效的方式完成...

怎么把 Python + Flet 开发的程序,打包为 exe ?这个方法很简单!

前面用Python+Flet开发的“我的计算器v3”,怎么打包为exe文件呢?这样才能分发给他人,直接“双击”运行使用啊!今天我给大家分享一个简单的、可用的,把Flet开发的程序打包为...