介紹Python中的不同數(shù)據(jù)類(lèi)型,包括整數(shù)、浮點(diǎn)數(shù)、字符串和布爾值。
int_num = 42 # 整數(shù)float_num = 3.14 # 浮點(diǎn)數(shù)string_var = "Hello, Python!" # 字符串bool_var = True # 布爾值
展示如何在Python中聲明變量并給它們賦值。
x = 10 # 變量賦值y = "Python"
解釋了列表和元組的創(chuàng)建,它們是Python中用于存儲(chǔ)序列的兩種主要數(shù)據(jù)結(jié)構(gòu)。
my_list = [1, 2, 3, "Python"] # 列表my_tuple = (1, 2, 3, "Tuple") # 元組
字典是Python中用于存儲(chǔ)鍵值對(duì)的另一種數(shù)據(jù)結(jié)構(gòu)。
my_dict = {'name': 'John', 'age': 25, 'city': 'Pythonville'} # 字典
控制流程語(yǔ)句,如if-elif-else和for循環(huán),用于控制程序的執(zhí)行流程。
if x > 0: print("Positive")elif x == 0: print("Zero")else: print("Negative")for item in my_list: print(item)while condition: # code
函數(shù)定義和調(diào)用的示例,展示了如何創(chuàng)建一個(gè)簡(jiǎn)單的函數(shù)。
def greet(name="User"): return f"Hello, {name}!"result = greet("John")
類(lèi)和對(duì)象的使用,演示了如何定義一個(gè)類(lèi)并創(chuàng)建類(lèi)的實(shí)例。
class Dog: def __init__(self, name): self.name = name def bark(self): print("Woof!")my_dog = Dog("Buddy")my_dog.bark()
文件操作的基本示例,包括讀取和寫(xiě)入文件。
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語(yǔ)句來(lái)處理可能的錯(cuò)誤。
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")finally: print("Execution completed.")
展示如何導(dǎo)入和使用Python的內(nèi)置庫(kù)和模塊。
import mathfrom datetime import datetime result = math.sqrt(25) current_time = datetime.now()
列表推導(dǎo)式的使用,提供了一種簡(jiǎn)潔的方法來(lái)創(chuàng)建列表。
squares = [x**2 for x in range(5)] # 列表推導(dǎo)式
Lambda函數(shù)的用法,展示了如何創(chuàng)建匿名函數(shù)。
add = lambda x, y: x + y result = add(2, 3)
虛擬環(huán)境的創(chuàng)建和使用,用于隔離項(xiàng)目依賴(lài)。
# 創(chuàng)建虛擬環(huán)境python -m venv myenv# 激活虛擬環(huán)境source myenv/bin/activate # 在Unix或MacOSmyenv/Scripts/activate # 在Windows# 停用虛擬環(huán)境deactivate
包管理工具pip的使用,用于安裝和管理Python包。
# 安裝包pip install package_name# 列出已安裝的包pip list# 創(chuàng)建requirements.txtpip freeze > requirements.txt# 從requirements.txt安裝包pip install -r requirements.txt
JSON數(shù)據(jù)格式的轉(zhuǎn)換,展示了如何將Python對(duì)象轉(zhuǎn)換為JSON格式,以及反向操作。
import json# 將Python對(duì)象轉(zhuǎn)換為JSONjson_data = json.dumps({"name": "John", "age": 25})# 將JSON轉(zhuǎn)換為Python對(duì)象python_obj = json.loads(json_data)
正則表達(dá)式的使用,用于字符串的搜索和操作。
import repattern = r'/d+' # 匹配一個(gè)或多個(gè)數(shù)字result = re.findall(pattern, "There are 42 apples and 123 oranges.")
日期和時(shí)間的處理,展示了如何獲取當(dāng)前日期和計(jì)算未來(lái)日期。
from datetime import datetime, timedeltacurrent_date = datetime.now()future_date = current_date + timedelta(days=7)
列表的操作,包括過(guò)濾、映射和歸約。
numbers = [1, 2, 3, 4, 5]# 過(guò)濾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)
字典的操作,包括獲取值和字典推導(dǎo)式。
my_dict = {'a': 1, 'b': 2, 'c': 3}# 獲取值value = my_dict.get('d', 0)# 字典推導(dǎo)式squared_dict = {key: value**2 for key, value in my_dict.items()}
線(xiàn)程的使用,展示了如何在Python中創(chuàng)建和管理線(xiàn)程。
import threadingdef print_numbers(): for i in range(5): print(i)thread = threading.Thread(target=print_numbers)thread.start()
Asyncio的使用,展示了如何在Python中進(jìn)行異步編程。
import asyncioasync def print_numbers(): for i in range(5): print(i) await asyncio.sleep(1)asyncio.run(print_numbers())
使用Beautiful Soup進(jìn)行網(wǎng)頁(yè)抓取。
from bs4 import BeautifulSoupimport requestsurl = "https://example.com"response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')title = soup.title.text
使用Flask框架創(chuàng)建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進(jìn)行單元測(cè)試。
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數(shù)據(jù)庫(kù)的交互。
import sqlite3conn = sqlite3.connect('example.db')cursor = conn.cursor()# 執(zhí)行SQL查詢(xún)cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name')# 提交更改conn.commit()# 關(guān)閉連接conn.close()
文件的讀寫(xiě)操作。
# 寫(xiě)入文件with open('example.txt', 'w') as file: file.write('Hello, Python!')# 讀取文件with open('example.txt', 'r') as file: content = file.read()
錯(cuò)誤處理的示例。
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()
使用枚舉類(lèi)型的示例。
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
使用列表推導(dǎo)式來(lái)生成特定條件的列表。
numbers = [1, 2, 3, 4, 5]# 偶數(shù)的平方squares = [x**2 for x in numbers if x % 2 == 0]
使用Lambda函數(shù)進(jìn)行簡(jiǎn)單的函數(shù)定義。
add = lambda x, y: x + yresult = add(3, 5)
使用concurrent.futures進(jìn)行線(xiàn)程池操作。
from concurrent.futures import ThreadPoolExecutordef square(x): return x**2with ThreadPoolExecutor() as executor: results = executor.map(square, [1, 2, 3, 4, 5])
使用gettext進(jìn)行國(guó)際化。
import gettext# 設(shè)置語(yǔ)言lang = 'en_US'_ = gettext.translation('messages', localedir='locale', languages=[lang]).getteprint(_("Hello, World!"))
虛擬環(huán)境的創(chuàng)建、激活和停用。
# 創(chuàng)建虛擬環(huán)境python -m venv myenv# 激活虛擬環(huán)境source myenv/bin/activate # 在Unix/Linuxmyenv/Scripts/activate # 在Windows# 停用虛擬環(huán)境deactivate
日期的格式化和天數(shù)的添加。
from datetime import datetime, timedeltanow = datetime.now()# 格式化日期formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')# 給日期添加天數(shù)future_date = now + timedelta(days=7)
字典的值獲取和遍歷。
my_dict = {'name': 'John', 'age': 30}# 獲取值,并設(shè)置默認(rèn)值age = my_dict.get('age', 25)# 遍歷鍵和值for key, value in my_dict.items(): print(f"{key}: {value}")
使用正則表達(dá)式匹配字符串中的數(shù)字。
import retext = "Hello, 123 World!"# 匹配數(shù)字numbers = re.findall(r'/d+', text)
使用生成器生成一系列值。
def square_numbers(n): for i in range(n): yield i**2squares = square_numbers(5)
使用SQLite數(shù)據(jù)庫(kù)進(jìn)行查詢(xún)。
import sqlite3# 連接SQLite數(shù)據(jù)庫(kù)conn = sqlite3.connect('mydatabase.db')cursor = conn.cursor()# 執(zhí)行SQL查詢(xún)cursor.execute('SELECT * FROM mytable')
使用zipfile模塊創(chuàng)建和解壓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進(jìn)行網(wǎng)頁(yè)抓取。
import requestsfrom bs4 import BeautifulSoupurl = 'https://example.com'response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')# 從HTML提取數(shù)據(jù)title = soup.title.text
使用smtplib發(fā)送電子郵件。
import smtplibfrom email.mime.text import MIMEText# 設(shè)置郵件服務(wù)器server = smtplib.SMTP('smtp.gmail.com', 587)server.starttls()# 登錄郵箱賬戶(hù)server.login('your_email@gmail.com', 'your_password')# 發(fā)送郵件msg = MIMEText('Hello, Python!')msg['Subject'] = 'Python Email'server.sendmail('your_email@gmail.com', 'recipient@example.com', msg.as_string())
JSON文件的讀寫(xiě)操作。
import jsondata = {'name': 'John', 'age': 30}# 寫(xiě)入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備忘請(qǐng)單是一個(gè)全面而實(shí)用的Python編程快速參考資源。它覆蓋了從基礎(chǔ)的數(shù)據(jù)類(lèi)型、變量賦值、控制流程、函數(shù)、類(lèi)與對(duì)象、文件處理、異常處理到更高級(jí)的主題,如列表推導(dǎo)式、Lambda函數(shù)、虛擬環(huán)境、包管理、JSON操作、正則表達(dá)式、日期處理、集合操作、線(xiàn)程并發(fā)、異步編程、Web抓取、RESTful API開(kāi)發(fā)、單元測(cè)試、數(shù)據(jù)庫(kù)交互、裝飾器、枚舉、國(guó)際化、生成器、ZIP文件操作、電子郵件發(fā)送等多個(gè)方面。
總的來(lái)說(shuō),備忘清單是為不同水平的Python開(kāi)發(fā)者設(shè)計(jì)的,幫助大家快速查找和回顧編程中的關(guān)鍵概念和實(shí)用技巧。
本文鏈接:http://www.tebozhan.com/showinfo-26-84900-0.htmlPython 備忘清單,一眼掃完核心知識(shí)點(diǎn)
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com