介紹Python中的不同數據類型,包括整數、浮點數、字符串和布爾值。
int_num = 42 # 整數float_num = 3.14 # 浮點數string_var = "Hello, Python!" # 字符串bool_var = True # 布爾值
展示如何在Python中聲明變量并給它們賦值。
x = 10 # 變量賦值y = "Python"
解釋了列表和元組的創建,它們是Python中用于存儲序列的兩種主要數據結構。
my_list = [1, 2, 3, "Python"] # 列表my_tuple = (1, 2, 3, "Tuple") # 元組
字典是Python中用于存儲鍵值對的另一種數據結構。
my_dict = {'name': 'John', 'age': 25, 'city': 'Pythonville'} # 字典
控制流程語句,如if-elif-else和for循環,用于控制程序的執行流程。
if x > 0: print("Positive")elif x == 0: print("Zero")else: print("Negative")for item in my_list: print(item)while condition: # code
函數定義和調用的示例,展示了如何創建一個簡單的函數。
def greet(name="User"): return f"Hello, {name}!"result = greet("John")
類和對象的使用,演示了如何定義一個類并創建類的實例。
class Dog: def __init__(self, name): self.name = name def bark(self): print("Woof!")my_dog = Dog("Buddy")my_dog.bark()
文件操作的基本示例,包括讀取和寫入文件。
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語句來處理可能的錯誤。
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")finally: print("Execution completed.")
展示如何導入和使用Python的內置庫和模塊。
import mathfrom datetime import datetime result = math.sqrt(25) current_time = datetime.now()
列表推導式的使用,提供了一種簡潔的方法來創建列表。
squares = [x**2 for x in range(5)] # 列表推導式
Lambda函數的用法,展示了如何創建匿名函數。
add = lambda x, y: x + y result = add(2, 3)
虛擬環境的創建和使用,用于隔離項目依賴。
# 創建虛擬環境python -m venv myenv# 激活虛擬環境source myenv/bin/activate # 在Unix或MacOSmyenv/Scripts/activate # 在Windows# 停用虛擬環境deactivate
包管理工具pip的使用,用于安裝和管理Python包。
# 安裝包pip install package_name# 列出已安裝的包pip list# 創建requirements.txtpip freeze > requirements.txt# 從requirements.txt安裝包pip install -r requirements.txt
JSON數據格式的轉換,展示了如何將Python對象轉換為JSON格式,以及反向操作。
import json# 將Python對象轉換為JSONjson_data = json.dumps({"name": "John", "age": 25})# 將JSON轉換為Python對象python_obj = json.loads(json_data)
正則表達式的使用,用于字符串的搜索和操作。
import repattern = r'/d+' # 匹配一個或多個數字result = re.findall(pattern, "There are 42 apples and 123 oranges.")
日期和時間的處理,展示了如何獲取當前日期和計算未來日期。
from datetime import datetime, timedeltacurrent_date = datetime.now()future_date = current_date + timedelta(days=7)
列表的操作,包括過濾、映射和歸約。
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)
字典的操作,包括獲取值和字典推導式。
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中創建和管理線程。
import threadingdef print_numbers(): for i in range(5): print(i)thread = threading.Thread(target=print_numbers)thread.start()
Asyncio的使用,展示了如何在Python中進行異步編程。
import asyncioasync def print_numbers(): for i in range(5): print(i) await asyncio.sleep(1)asyncio.run(print_numbers())
使用Beautiful Soup進行網頁抓取。
from bs4 import BeautifulSoupimport requestsurl = "https://example.com"response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')title = soup.title.text
使用Flask框架創建RESTful API。
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)
使用unittest進行單元測試。
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()
使用SQLite數據庫的交互。
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()
文件的讀寫操作。
# 寫入文件with open('example.txt', 'w') as file: file.write('Hello, Python!')# 讀取文件with open('example.txt', 'r') as file: content = file.read()
錯誤處理的示例。
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.")
使用裝飾器的示例。
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()
使用枚舉類型的示例。
from enum import Enumclass Color(Enum): RED = 1 GREEN = 2 BLUE = 3print(Color.RED)
集合的基本操作,包括并集、交集和差集。
set1 = {1, 2, 3}set2 = {3, 4, 5}# 并集union_set = set1 | set2# 交集intersection_set = set1 & set2# 差集difference_set = set1 - set2
使用列表推導式來生成特定條件的列表。
numbers = [1, 2, 3, 4, 5]# 偶數的平方squares = [x**2 for x in numbers if x % 2 == 0]
使用Lambda函數進行簡單的函數定義。
add = lambda x, y: x + yresult = add(3, 5)
使用concurrent.futures進行線程池操作。
from concurrent.futures import ThreadPoolExecutordef square(x): return x**2with ThreadPoolExecutor() as executor: results = executor.map(square, [1, 2, 3, 4, 5])
使用gettext進行國際化。
import gettext# 設置語言lang = 'en_US'_ = gettext.translation('messages', localedir='locale', languages=[lang]).getteprint(_("Hello, World!"))
虛擬環境的創建、激活和停用。
# 創建虛擬環境python -m venv myenv# 激活虛擬環境source myenv/bin/activate # 在Unix/Linuxmyenv/Scripts/activate # 在Windows# 停用虛擬環境deactivate
日期的格式化和天數的添加。
from datetime import datetime, timedeltanow = datetime.now()# 格式化日期formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')# 給日期添加天數future_date = now + timedelta(days=7)
字典的值獲取和遍歷。
my_dict = {'name': 'John', 'age': 30}# 獲取值,并設置默認值age = my_dict.get('age', 25)# 遍歷鍵和值for key, value in my_dict.items(): print(f"{key}: {value}")
使用正則表達式匹配字符串中的數字。
import retext = "Hello, 123 World!"# 匹配數字numbers = re.findall(r'/d+', text)
使用生成器生成一系列值。
def square_numbers(n): for i in range(n): yield i**2squares = square_numbers(5)
使用SQLite數據庫進行查詢。
import sqlite3# 連接SQLite數據庫conn = sqlite3.connect('mydatabase.db')cursor = conn.cursor()# 執行SQL查詢cursor.execute('SELECT * FROM mytable')
使用zipfile模塊創建和解壓ZIP文件。
import zipfilewith zipfile.ZipFile('archive.zip', 'w') as myzip: myzip.write('file.txt')with zipfile.ZipFile('archive.zip', 'r') as myzip: myzip.extractall('extracted')
使用requests和BeautifulSoup進行網頁抓取。
import requestsfrom bs4 import BeautifulSoupurl = 'https://example.com'response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')# 從HTML提取數據title = soup.title.text
使用smtplib發送電子郵件。
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文件的讀寫操作。
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文件操作、電子郵件發送等多個方面。
總的來說,備忘清單是為不同水平的Python開發者設計的,幫助大家快速查找和回顧編程中的關鍵概念和實用技巧。
本文鏈接:http://www.tebozhan.com/showinfo-26-84900-0.htmlPython 備忘清單,一眼掃完核心知識點
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 《蛋仔派對》推行未成年人的反詐與消費教育