Python 作为一门功能强大且易于学习的编程语言,其应用范围非常广泛。下面我将列举 30 个常用的 Python 代码片段,涵盖基本语法、数据处理、网络请求、文件操作等多个方面python好玩又简单的代码。

废话不多,列代码:
-
打印输出 print('Hello, World!')
-
变量赋值
-
条件判断
-
循环
-
定义函数
-
列表推导式 squares = [x * x for x in range(10)]
-
字典操作 person = {'name': 'Alice', 'age': 25}
-
集合操作 c = a.union(b) # {1, 2, 3, 4, 5}
-
文件读取 with open('example.txt', 'r') as file:
-
文件写入 with open('example.txt', 'w') as file: file.write('Hello, Python!')
-
错误和异常处理 except ZeroDivisionError: print('Cannot divide by zero')
-
类定义 def __init__(self, name):
-
模块导入
-
列表分片 numbers = [0, 1, 2, 3, 4, 5]
-
字符串格式化 message = f'{greeting}, {name}!'
-
Lambda 函数
-
列表排序 nums = [3, 1, 4, 1, 5, 9, 2, 6]
-
生成器
-
列表去重 duplicates = [1, 2, 2, 3, 3, 3] unique = list(set(duplicates))
-
JSON 处理 person_json = json.dumps(person) # 序列化 person_dict = json.loads(person_json) # 反序列化
-
日期和时间 from datetime import datetime
-
正则表达式 matches = re.findall(pattern, '12 drummers drumming, 11 pipers piping')
-
文件路径操作 current_directory = os.getcwd()
-
环境变量获取 path = os.environ.get('PATH')
-
命令行参数 first_argument = sys.argv[1]
-
字节和字符串转换
_s = bytes_s.decode() ```
-
创建临时文件 temp_file = tempfile.TemporaryFile()
-
发送 HTTP 请求 response = requests.get('https://www.')
-
解析 HTML from bs4 import BeautifulSoup soup = BeautifulSoup('<p>Some<b>bad<i>HTML')
-
数据库连接 conn = sqlite3.connect('example.db')
这些代码片段展示了 Python 在各种常见任务中的基本用法,适用于多种场景,包括数据处理、文件操作、网络请求等。由于 Python 的灵活性和广泛的库支持,你可以根据具体需求随意调用。

再贴几个比较进阶的代码:
1. 发送 HTTP 请求
response = requests.get('https://api./data')
2. 使用 Pandas 处理数据
df = pd.read_csv('data.csv') df_filtered = df[df['column_name'] > 0]
3. 使用 Matplotlib 绘图
import matplotlib.pyplot as plt plt.ylabel('some numbers')
4. 使用 SQLite3 访问数据库
conn = sqlite3.connect('example.db') c.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''')
5. 使用正则表达式
text = 'Example text with 'email@'' email = re.findall(r'[\w\.-]+@[\w\.-]+', text)
6. 多线程编程
t = threading.Thread(target=print_numbers)
7. 使用 Flask 创建简单的 Web 应用
if __name__ == '__main__':
8. 爬虫
from bs4 import BeautifulSoup page = requests.get('http://') soup = BeautifulSoup(page.content, 'html.parser')
9. 使用 NumPy 进行数值计算
10. 使用 Pygame 开发游戏
screen = pygame.display.set_mode((400, 300)) for event in pygame.event.get(): if event.type == pygame.QUIT:
|