AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

Python 備忘清單,一眼掃完核心知識點

來源: 責編: 時間:2024-04-23 17:58:36 144觀看
導讀數據類型介紹Python中的不同數據類型,包括整數、浮點數、字符串和布爾值。int_num = 42 # 整數float_num = 3.14 # 浮點數string_var = "Hello, Python!" # 字符串bool_var = True # 布爾值變量和賦值展示如何在Py

數據類型

0Pa28資訊網——每日最新資訊28at.com

介紹Python中的不同數據類型,包括整數、浮點數、字符串和布爾值。0Pa28資訊網——每日最新資訊28at.com

int_num = 42  # 整數float_num = 3.14  # 浮點數string_var = "Hello, Python!"  # 字符串bool_var = True  # 布爾值

變量和賦值

展示如何在Python中聲明變量并給它們賦值。0Pa28資訊網——每日最新資訊28at.com

x = 10  # 變量賦值y = "Python"

列表 & 元組

解釋了列表和元組的創建,它們是Python中用于存儲序列的兩種主要數據結構。0Pa28資訊網——每日最新資訊28at.com

my_list = [1, 2, 3, "Python"]  # 列表my_tuple = (1, 2, 3, "Tuple")  # 元組

字典

字典是Python中用于存儲鍵值對的另一種數據結構。0Pa28資訊網——每日最新資訊28at.com

my_dict = {'name': 'John', 'age': 25, 'city': 'Pythonville'}  # 字典

控制流程

控制流程語句,如if-elif-else和for循環,用于控制程序的執行流程。0Pa28資訊網——每日最新資訊28at.com

if x > 0:    print("Positive")elif x == 0:    print("Zero")else:    print("Negative")for item in my_list:    print(item)while condition:    # code

函數

函數定義和調用的示例,展示了如何創建一個簡單的函數。0Pa28資訊網——每日最新資訊28at.com

def greet(name="User"):     return f"Hello, {name}!"result = greet("John")

類 & 對象

類和對象的使用,演示了如何定義一個類并創建類的實例。0Pa28資訊網——每日最新資訊28at.com

class Dog:    def __init__(self, name):         self.name = name    def bark(self):         print("Woof!")my_dog = Dog("Buddy")my_dog.bark()

文件處理

文件操作的基本示例,包括讀取和寫入文件。0Pa28資訊網——每日最新資訊28at.com

with open("file.txt", "r") as file:     content = file.read()with open("new_file.txt", "w") as new_file:     new_file.write("Hello, Python!")

異常處理

異常處理的用法,展示了如何用try-except語句來處理可能的錯誤。0Pa28資訊網——每日最新資訊28at.com

try:     result = 10 / 0 except ZeroDivisionError:     print("Cannot divide by zero!")finally:     print("Execution completed.")

庫 & 模塊

展示如何導入和使用Python的內置庫和模塊。0Pa28資訊網——每日最新資訊28at.com

import mathfrom datetime import datetime result = math.sqrt(25) current_time = datetime.now()

列表推導式

列表推導式的使用,提供了一種簡潔的方法來創建列表。0Pa28資訊網——每日最新資訊28at.com

squares = [x**2 for x in range(5)]  # 列表推導式

Lambda 函數

Lambda函數的用法,展示了如何創建匿名函數。0Pa28資訊網——每日最新資訊28at.com

add = lambda x, y: x + y result = add(2, 3)

虛擬環境

虛擬環境的創建和使用,用于隔離項目依賴。0Pa28資訊網——每日最新資訊28at.com

# 創建虛擬環境python -m venv myenv# 激活虛擬環境source myenv/bin/activate  # 在Unix或MacOSmyenv/Scripts/activate  # 在Windows# 停用虛擬環境deactivate

包管理

包管理工具pip的使用,用于安裝和管理Python包。0Pa28資訊網——每日最新資訊28at.com

# 安裝包pip install package_name# 列出已安裝的包pip list# 創建requirements.txtpip freeze > requirements.txt# 從requirements.txt安裝包pip install -r requirements.txt

與JSON的交互

JSON數據格式的轉換,展示了如何將Python對象轉換為JSON格式,以及反向操作。0Pa28資訊網——每日最新資訊28at.com

import json# 將Python對象轉換為JSONjson_data = json.dumps({"name": "John", "age": 25})# 將JSON轉換為Python對象python_obj = json.loads(json_data)

正則表達式

正則表達式的使用,用于字符串的搜索和操作。0Pa28資訊網——每日最新資訊28at.com

import repattern = r'/d+'  # 匹配一個或多個數字result = re.findall(pattern, "There are 42 apples and 123 oranges.")

與日期的交互

日期和時間的處理,展示了如何獲取當前日期和計算未來日期。0Pa28資訊網——每日最新資訊28at.com

from datetime import datetime, timedeltacurrent_date = datetime.now()future_date = current_date + timedelta(days=7)

列表操作

列表的操作,包括過濾、映射和歸約。0Pa28資訊網——每日最新資訊28at.com

numbers = [1, 2, 3, 4, 5]# 過濾evens = list(filter(lambda x: x % 2 == 0, numbers))# 映射squared = list(map(lambda x: x**2, numbers))# 歸約 (需要functools)from functools import reduceproduct = reduce(lambda x, y: x * y, numbers)

字典操作

字典的操作,包括獲取值和字典推導式。0Pa28資訊網——每日最新資訊28at.com

my_dict = {'a': 1, 'b': 2, 'c': 3}# 獲取值value = my_dict.get('d', 0)# 字典推導式squared_dict = {key: value**2 for key, value in my_dict.items()}

線程并發

線程的使用,展示了如何在Python中創建和管理線程。0Pa28資訊網——每日最新資訊28at.com

import threadingdef print_numbers():     for i in range(5):         print(i)thread = threading.Thread(target=print_numbers)thread.start()

Asyncio并發

Asyncio的使用,展示了如何在Python中進行異步編程。0Pa28資訊網——每日最新資訊28at.com

import asyncioasync def print_numbers():     for i in range(5):         print(i)        await asyncio.sleep(1)asyncio.run(print_numbers())

Web Scraping with Beautiful Soup

使用Beautiful Soup進行網頁抓取。0Pa28資訊網——每日最新資訊28at.com

from bs4 import BeautifulSoupimport requestsurl = "https://example.com"response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')title = soup.title.text

RESTful API with Flask

使用Flask框架創建RESTful API。0Pa28資訊網——每日最新資訊28at.com

from flask import Flask, jsonify, requestapp = Flask(__name__)@app.route('/api/data', methods=['GET'])def get_data():    data = {'key': 'value'}    return jsonify(data)if __name__ == '__main__':    app.run(debug=True)

單元測試 with unittest

使用unittest進行單元測試。0Pa28資訊網——每日最新資訊28at.com

import unittestdef add(x, y):     return x + yclass TestAddition(unittest.TestCase):    def test_add_positive_numbers(self):         self.assertEqual(add(2, 3), 5)if __name__ == '__main__':    unittest.main()

數據庫交互 with SQLite

使用SQLite數據庫的交互。0Pa28資訊網——每日最新資訊28at.com

import sqlite3conn = sqlite3.connect('example.db')cursor = conn.cursor()# 執行SQL查詢cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name')# 提交更改conn.commit()# 關閉連接conn.close()

文件處理

文件的讀寫操作。0Pa28資訊網——每日最新資訊28at.com

# 寫入文件with open('example.txt', 'w') as file:    file.write('Hello, Python!')# 讀取文件with open('example.txt', 'r') as file:    content = file.read()

錯誤處理

錯誤處理的示例。0Pa28資訊網——每日最新資訊28at.com

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.")

Python Decorators

使用裝飾器的示例。0Pa28資訊網——每日最新資訊28at.com

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()

枚舉 with Enums

使用枚舉類型的示例。0Pa28資訊網——每日最新資訊28at.com

from enum import Enumclass Color(Enum):     RED = 1     GREEN = 2     BLUE = 3print(Color.RED)

集合操作

集合的基本操作,包括并集、交集和差集。0Pa28資訊網——每日最新資訊28at.com

set1 = {1, 2, 3}set2 = {3, 4, 5}# 并集union_set = set1 | set2# 交集intersection_set = set1 & set2# 差集difference_set = set1 - set2

列表推導式

使用列表推導式來生成特定條件的列表。0Pa28資訊網——每日最新資訊28at.com

numbers = [1, 2, 3, 4, 5]# 偶數的平方squares = [x**2 for x in numbers if x % 2 == 0]

Lambda 函數

使用Lambda函數進行簡單的函數定義。0Pa28資訊網——每日最新資訊28at.com

add = lambda x, y: x + yresult = add(3, 5)

線程與Concurrent.futures

使用concurrent.futures進行線程池操作。0Pa28資訊網——每日最新資訊28at.com

from concurrent.futures import ThreadPoolExecutordef square(x):     return x**2with ThreadPoolExecutor() as executor:     results = executor.map(square, [1, 2, 3, 4, 5])

國際化 (i18n) with gettext

使用gettext進行國際化。0Pa28資訊網——每日最新資訊28at.com

import gettext# 設置語言lang = 'en_US'_ = gettext.translation('messages', localedir='locale', languages=[lang]).getteprint(_("Hello, World!"))

虛擬環境

虛擬環境的創建、激活和停用。0Pa28資訊網——每日最新資訊28at.com

# 創建虛擬環境python -m venv myenv# 激活虛擬環境source myenv/bin/activate  # 在Unix/Linuxmyenv/Scripts/activate  # 在Windows# 停用虛擬環境deactivate

日期操作

日期的格式化和天數的添加。0Pa28資訊網——每日最新資訊28at.com

from datetime import datetime, timedeltanow = datetime.now()# 格式化日期formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')# 給日期添加天數future_date = now + timedelta(days=7)

字典操作

字典的值獲取和遍歷。0Pa28資訊網——每日最新資訊28at.com

my_dict = {'name': 'John', 'age': 30}# 獲取值,并設置默認值age = my_dict.get('age', 25)# 遍歷鍵和值for key, value in my_dict.items():    print(f"{key}: {value}")

正則表達式

使用正則表達式匹配字符串中的數字。0Pa28資訊網——每日最新資訊28at.com

import retext = "Hello, 123 World!"# 匹配數字numbers = re.findall(r'/d+', text)

生成器

使用生成器生成一系列值。0Pa28資訊網——每日最新資訊28at.com

def square_numbers(n):     for i in range(n):         yield i**2squares = square_numbers(5)

數據庫交互 with SQLite

使用SQLite數據庫進行查詢。0Pa28資訊網——每日最新資訊28at.com

import sqlite3# 連接SQLite數據庫conn = sqlite3.connect('mydatabase.db')cursor = conn.cursor()# 執行SQL查詢cursor.execute('SELECT * FROM mytable')

操作ZIP文件

使用zipfile模塊創建和解壓ZIP文件。0Pa28資訊網——每日最新資訊28at.com

import zipfilewith zipfile.ZipFile('archive.zip', 'w') as myzip:    myzip.write('file.txt')with zipfile.ZipFile('archive.zip', 'r') as myzip:    myzip.extractall('extracted')

Web 爬蟲 requests 和 BeautifulSoup

使用requests和BeautifulSoup進行網頁抓取。0Pa28資訊網——每日最新資訊28at.com

import requestsfrom bs4 import BeautifulSoupurl = 'https://example.com'response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')# 從HTML提取數據title = soup.title.text

發送電子郵件 with smtplib

使用smtplib發送電子郵件。0Pa28資訊網——每日最新資訊28at.com

import smtplibfrom email.mime.text import MIMEText# 設置郵件服務器server = smtplib.SMTP('smtp.gmail.com', 587)server.starttls()# 登錄郵箱賬戶server.login('your_email@gmail.com', 'your_password')# 發送郵件msg = MIMEText('Hello, Python!')msg['Subject'] = 'Python Email'server.sendmail('your_email@gmail.com', 'recipient@example.com', msg.as_string())

操作JSON文件

JSON文件的讀寫操作。0Pa28資訊網——每日最新資訊28at.com

import jsondata = {'name': 'John', 'age': 30}# 寫入JSON文件with open('data.json', 'w') as json_file:    json.dump(data, json_file)# 從JSON文件讀取with open('data.json', 'r') as json_file:    loaded_data = json.load(json_file)

總結

這份Python備忘請單是一個全面而實用的Python編程快速參考資源。它覆蓋了從基礎的數據類型、變量賦值、控制流程、函數、類與對象、文件處理、異常處理到更高級的主題,如列表推導式、Lambda函數、虛擬環境、包管理、JSON操作、正則表達式、日期處理、集合操作、線程并發、異步編程、Web抓取、RESTful API開發、單元測試、數據庫交互、裝飾器、枚舉、國際化、生成器、ZIP文件操作、電子郵件發送等多個方面。0Pa28資訊網——每日最新資訊28at.com

總的來說,備忘清單是為不同水平的Python開發者設計的,幫助大家快速查找和回顧編程中的關鍵概念和實用技巧。0Pa28資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-84900-0.htmlPython 備忘清單,一眼掃完核心知識點

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 《蛋仔派對》推行未成年人的反詐與消費教育

下一篇: Spring Boot 配置文件加載優先級詳解

標簽:
  • 熱門焦點
Top