分享

python常用代码大全,python代码大全简单

 自用书屋 2024-07-17 发布于河南

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

废话不多,列代码:

  1. 打印输出

    print('Hello, World!')
    
  2. 变量赋值

    1. x = 10
    2. y = 'Python'
  3. 条件判断

    1. if x < 10:
    2. print('Less than 10')
    3. elif x == 10:
    4. print('Equal to 10')
    5. else:
    6. print('Greater than 10')
  4. 循环

    1. for i in range(5):
    2. print(i)
  5. 定义函数

    1. def greet(name):
    2. return f'Hello, {name}!'
  6. 列表推导式

    squares = [x * x for x in range(10)]
    
  7. 字典操作

    1. person = {'name': 'Alice', 'age': 25}
    2. person['age'] = 26 # 更新
  8. 集合操作

    1. a = {1, 2, 3}
    2. b = {3, 4, 5}
    3. c = a.union(b) # {1, 2, 3, 4, 5}
  9. 文件读取

    1. with open('example.txt', 'r') as file:
    2. content = file.read()
  10. 文件写入

    1. with open('example.txt', 'w') as file:
    2. file.write('Hello, Python!')
  11. 错误和异常处理

    1. try:
    2. result = 10 / 0
    3. except ZeroDivisionError:
    4. print('Cannot divide by zero')
  12. 类定义

    1. class Dog:
    2. def __init__(self, name):
    3. self.name = name
    4. def speak(self):
    5. return 'Woof!'
  13. 模块导入

    1. import math
    2. print(math.sqrt(16))
  14. 列表分片

    1. numbers = [0, 1, 2, 3, 4, 5]
    2. first_two = numbers[:2]
  15. 字符串格式化

    1. greeting = 'Hello'
    2. name = 'Alice'
    3. message = f'{greeting}, {name}!'
  16. Lambda 函数

    1. square = lambda x: x * x
    2. print(square(5))
  17. 列表排序

    1. nums = [3, 1, 4, 1, 5, 9, 2, 6]
    2. nums.sort()
  18. 生成器

    1. def count_down(n):
    2. while n > 0:
    3. yield n
    4. n -= 1
  19. 列表去重

    1. duplicates = [1, 2, 2, 3, 3, 3]
    2. unique = list(set(duplicates))
  20. JSON 处理

    1. import json
    2. person_json = json.dumps(person) # 序列化
    3. person_dict = json.loads(person_json) # 反序列化
  21. 日期和时间

    1. from datetime import datetime
    2. now = datetime.now()
  22. 正则表达式

    1. import re
    2. pattern = r'(\d+)'
    3. matches = re.findall(pattern, '12 drummers drumming, 11 pipers piping')
  23. 文件路径操作

    1. import os
    2. current_directory = os.getcwd()
  24. 环境变量获取

    1. import os
    2. path = os.environ.get('PATH')
  25. 命令行参数

    1. import sys
    2. first_argument = sys.argv[1]
  26. 字节和字符串转换

    1. s = 'hello'
    2. bytes_s = s.encode()
    3. str

_s = bytes_s.decode()
```

  1. 创建临时文件

    1. import tempfile
    2. temp_file = tempfile.TemporaryFile()
  2. 发送 HTTP 请求

    1. import requests
    2. response = requests.get('https://www.')
  3. 解析 HTML

    1. from bs4 import BeautifulSoup
    2. soup = BeautifulSoup('<p>Some<b>bad<i>HTML')
    3. print(soup.prettify())
  4. 数据库连接

    1. import sqlite3
    2. conn = sqlite3.connect('example.db')
    3. cursor = conn.cursor()

这些代码片段展示了 Python 在各种常见任务中的基本用法,适用于多种场景,包括数据处理、文件操作、网络请求等。由于 Python 的灵活性和广泛的库支持,你可以根据具体需求随意调用。
在这里插入图片描述

再贴几个比较进阶的代码:

1. 发送 HTTP 请求

  1. - 用途:发送网络请求。
  2. - 示例:
  3. ```python
  4. import requests
  5. response = requests.get('https://api./data')
  6. data = response.json()
  7. ```

2. 使用 Pandas 处理数据

  1. - 用途:数据分析和处理。
  2. - 示例:
  3. ```python
  4. import pandas as pd
  5. df = pd.read_csv('data.csv')
  6. df_filtered = df[df['column_name'] > 0]
  7. ```

3. 使用 Matplotlib 绘图

  1. - 用途:数据可视化。
  2. - 示例:
  3. ```python
  4. import matplotlib.pyplot as plt
  5. plt.plot([1, 2, 3, 4])
  6. plt.ylabel('some numbers')
  7. plt.show()
  8. ```

4. 使用 SQLite3 访问数据库

  1. - 用途:数据库操作。
  2. - 示例:
  3. ```python
  4. import sqlite3
  5. conn = sqlite3.connect('example.db')
  6. c = conn.cursor()
  7. c.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''')
  8. conn.commit()
  9. conn.close()
  10. ```

5. 使用正则表达式

  1. - 用途:文本匹配和处理。
  2. - 示例:
  3. ```python
  4. import re
  5. text = 'Example text with 'email@''
  6. email = re.findall(r'[\w\.-]+@[\w\.-]+', text)
  7. ```

6. 多线程编程

  1. - 用途:并发执行。
  2. - 示例:
  3. ```python
  4. import threading
  5. def print_numbers():
  6. for i in range(1, 6):
  7. print(i)
  8. t = threading.Thread(target=print_numbers)
  9. t.start()
  10. t.join()
  11. ```

7. 使用 Flask 创建简单的 Web 应用

  1. - 用途:Web 开发。
  2. - 示例:
  3. ```python
  4. from flask import Flask
  5. app = Flask(__name__)
  6. @app.route('/')
  7. def hello_world():
  8. return 'Hello, World!'
  9. if __name__ == '__main__':
  10. app.run()
  11. ```

8. 爬虫

  1. - 用途:抓取网络数据。
  2. - 示例:
  3. ```python
  4. import requests
  5. from bs4 import BeautifulSoup
  6. page = requests.get('http://')
  7. soup = BeautifulSoup(page.content, 'html.parser')
  8. print(soup.prettify())
  9. ```

9. 使用 NumPy 进行数值计算

  1. - 用途:科学计算。
  2. - 示例:
  3. ```python
  4. import numpy as np
  5. a = np.array([1, 2, 3])
  6. print(np.mean(a))
  7. ```

10. 使用 Pygame 开发游戏

  1. - 用途:游戏开发。
  2. - 示例:
  3. ```python
  4. import pygame
  5. pygame.init()
  6. screen = pygame.display.set_mode((400, 300))
  7. done = False
  8. while not done:
  9. for event in pygame.event.get():
  10. if event.type == pygame.QUIT:
  11. done = True
  12. pygame.display.flip()
  13. ```

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多