赞
踩
大家好,给大家分享一下python常用代码大全,很多人还不知道这一点。下面详细解释一下。现在让我们来看看!
Python 作为一门功能强大且易于学习的编程语言,其应用范围非常广泛。下面我将列举 30 个常用的 Python 代码片段,涵盖基本语法、数据处理、网络请求、文件操作等多个方面python好玩又简单的代码。
废话不多,列代码:
打印输出
print("Hello, World!")
'运行
变量赋值
- x = 10
- y = "Python"
'运行
条件判断
- if x < 10:
- print("Less than 10")
- elif x == 10:
- print("Equal to 10")
- else:
- print("Greater than 10")
循环
- for i in range(5):
- print(i)
'运行
定义函数
- def greet(name):
- return f"Hello, {name}!"
'运行
列表推导式
squares = [x * x for x in range(10)]
'运行
字典操作
- person = {"name": "Alice", "age": 25}
- person["age"] = 26 # 更新
'运行
集合操作
- a = {1, 2, 3}
- b = {3, 4, 5}
- c = a.union(b) # {1, 2, 3, 4, 5}
'运行
文件读取
- with open("example.txt", "r") as file:
- content = file.read()
'运行
文件写入
- with open("example.txt", "w") as file:
- file.write("Hello, Python!")
'运行
错误和异常处理
- try:
- result = 10 / 0
- except ZeroDivisionError:
- print("Cannot divide by zero")
'运行
类定义
- class Dog:
- def __init__(self, name):
- self.name = name
- def speak(self):
- return "Woof!"
'运行
模块导入
- import math
- print(math.sqrt(16))
'运行
列表分片
- numbers = [0, 1, 2, 3, 4, 5]
- first_two = numbers[:2]
'运行
字符串格式化
- greeting = "Hello"
- name = "Alice"
- message = f"{greeting}, {name}!"
'运行
Lambda 函数
- square = lambda x: x * x
- print(square(5))
'运行
列表排序
- nums = [3, 1, 4, 1, 5, 9, 2, 6]
- nums.sort()
'运行
生成器
- def count_down(n):
- while n > 0:
- yield n
- n -= 1
'运行
列表去重
- duplicates = [1, 2, 2, 3, 3, 3]
- unique = list(set(duplicates))
'运行
JSON 处理
- import json
- person_json = json.dumps(person) # 序列化
- person_dict = json.loads(person_json) # 反序列化
日期和时间
- from datetime import datetime
- now = datetime.now()
'运行
正则表达式
- import re
- pattern = r"(\d+)"
- matches = re.findall(pattern, "12 drummers drumming, 11 pipers piping")
'运行
文件路径操作
- import os
- current_directory = os.getcwd()
'运行
环境变量获取
- import os
- path = os.environ.get("PATH")
'运行
命令行参数
- import sys
- first_argument = sys.argv[1]
字节和字符串转换
- s = "hello"
- bytes_s = s.encode()
- str
-
'运行
_s = bytes_s.decode()
```
创建临时文件
- import tempfile
- temp_file = tempfile.TemporaryFile()
'运行
发送 HTTP 请求
- import requests
- response = requests.get("https://www.example.com")
解析 HTML
- from bs4 import BeautifulSoup
- soup = BeautifulSoup("<p>Some<b>bad<i>HTML")
- print(soup.prettify())
'运行
数据库连接
- import sqlite3
- conn = sqlite3.connect('example.db')
- cursor = conn.cursor()
'运行
这些代码片段展示了 Python 在各种常见任务中的基本用法,适用于多种场景,包括数据处理、文件操作、网络请求等。由于 Python 的灵活性和广泛的库支持,你可以根据具体需求随意调用。
再贴几个比较进阶的代码:
- - 用途:发送网络请求。
- - 示例:
- ```python
- import requests
- response = requests.get("https://api.example.com/data")
- data = response.json()
- ```
- - 用途:数据分析和处理。
- - 示例:
- ```python
- import pandas as pd
- df = pd.read_csv("data.csv")
- df_filtered = df[df['column_name'] > 0]
- ```
- - 用途:数据可视化。
- - 示例:
- ```python
- import matplotlib.pyplot as plt
- plt.plot([1, 2, 3, 4])
- plt.ylabel('some numbers')
- plt.show()
- ```
- - 用途:数据库操作。
- - 示例:
- ```python
- import sqlite3
- conn = sqlite3.connect('example.db')
- c = conn.cursor()
- c.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''')
- conn.commit()
- conn.close()
- ```
- - 用途:文本匹配和处理。
- - 示例:
- ```python
- import re
- text = "Example text with 'email@example.com'"
- email = re.findall(r'[\w\.-]+@[\w\.-]+', text)
- ```
- - 用途:并发执行。
- - 示例:
- ```python
- import threading
-
- def print_numbers():
- for i in range(1, 6):
- print(i)
-
- t = threading.Thread(target=print_numbers)
- t.start()
- t.join()
- ```
- - 用途:Web 开发。
- - 示例:
- ```python
- from flask import Flask
- app = Flask(__name__)
-
- @app.route('/')
- def hello_world():
- return 'Hello, World!'
-
- if __name__ == '__main__':
- app.run()
- ```
- - 用途:抓取网络数据。
- - 示例:
- ```python
- import requests
- from bs4 import BeautifulSoup
-
- page = requests.get("http://example.com")
- soup = BeautifulSoup(page.content, 'html.parser')
- print(soup.prettify())
- ```
- - 用途:科学计算。
- - 示例:
- ```python
- import numpy as np
- a = np.array([1, 2, 3])
- print(np.mean(a))
- ```
- - 用途:游戏开发。
- - 示例:
- ```python
- import pygame
- pygame.init()
- screen = pygame.display.set_mode((400, 300))
- done = False
- while not done:
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- done = True
- pygame.display.flip()
- ```
如果有使用问题,我有技术沟通群,欢迎进来玩~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。