Python,學霸
例項1:Hello World
# 打印 Hello World
print("Hello World")
例項2:計算兩數之和
# 輸入兩個數位
num1 = input("輸入第一個數位:")
num2 = input("輸入第二個數位:")
# 求和
sum = float(num1) + float(num2)
# 顯示計算結果
print(f"{num1} + {num2} = {sum}")
例項3:判斷奇偶數
# 輸入一個數位
num = int(input("輸入一個數位:"))
# 判斷奇偶
if num % 2 == 0:
print(f"{num} 是偶數")
else:
print(f"{num} 是奇數")
例項4:使用迴圈打印乘法表
# 打印9x9乘法表
for i in range(1, 10):
for j in range(1, i+1):
print(f"{j}x{i}={i*j}", end="\t")
print()
例項5:列表推導式生成平方數列表
# 生成前10個整數的平方數列表
squares = [i**2for i in range(1, 11)]
print(squares)
例項6:函式計算階乘
# 定義一個計算階乘的函式
deffactorial(n):
if n == 1:
return1
else:
return n * factorial(n-1)
# 使用函式
num = 5
print(f"{num} 的階乘是 {factorial(num)}")
例項7:字典推導式
# 使用字典推導式建立一個字典,其中鍵為1到5,值為鍵的平方
squares_dict = {i: i**2for i in range(1, 6)}
print(squares_dict)
例項8:檔操作讀寫
# 寫入檔
with open('test.txt', 'w') as f:
f.write("Hello Python!\n")
# 讀取檔
with open('test.txt', 'r') as f:
content = f.read()
print(content)
例項9:例外處理
# 嘗試執行除法計算,捕獲異常
try:
result = 10 / 0
except ZeroDivisionError:
print("除數不能為0")
例項10:類和物件
# 定義一個簡單的類
classDog:
def__init__(self, name):
self.name = name
defspeak(self):
returnf"{self.name} says Woof!"
# 建立一個物件
my_dog = Dog('Spot')
print(my_dog.speak())
例項11:生成費氏數列
# 生成費氏數列的前N個數位
deffibonacci(n):
a, b = 0, 1
result = []
while len(result) < n:
result.append(b)
a, b = b, a+b
return result
# 呼叫函式
print(fibonacci(10))
例項12:列表去重
# 使用集合去除列表中的重復元素
defremove_duplicates(lst):
return list(set(lst))
# 範例列表
my_list = [1, 2, 2, 3, 4, 4, 5]
print(remove_duplicates(my_list))
例項13:檢查回文字串
# 檢查字串是否為回文
defis_palindrome(s):
return s == s[::-1]
# 測試字串
test_str = "madam"
print(is_palindrome(test_str))
例項14:字典按值排序
# 使用lambda函式對字典按值進行排序
my_dict = {'apple': 5, 'banana': 1, 'orange': 3}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict)
例項15:找出列表中的最大數和最小數
# 找出列表中的最大和最小值
deffind_max_min(lst):
return max(lst), min(lst)
# 範例列表
my_list = [40, 1, 5, 200]
print(find_max_min(my_list))
例項16:字串首字母大寫
# 將字串的每個單詞的首字母大寫
defcapitalize_string(s):
return' '.join(word.capitalize() for word in s.split())
test_str = "hello python world"
print(capitalize_string(test_str))
例項17:合並兩個字典
# 合並兩個字典
defmerge_dicts(dict1, dict2):
return {**dict1, **dict2}
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
print(merge_dicts(dict1, dict2))
例項18:計算列表中元素出現的頻率
# 計算列表中各元素出現的次數
from collections import Counter
my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
count = Counter(my_list)
print(count)
例項19:簡單的網頁爬蟲
# 使用requests和BeautifulSoup庫進行簡單的網頁爬蟲
import requests
from bs4 import BeautifulSoup
URL = "http://example.com"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
title = soup.find("title").text
print(title)
例項20:建立簡單的HTTP伺服器
# 使用http.server庫建立簡單的HTTP伺服器
from http.server import HTTPServer, BaseHTTPRequestHandler
classSimpleHTTPRequestHandler(BaseHTTPRequestHandler):
defdo_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b'Hello, Python!')
httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
httpd.serve_forever()
例項21:環境變量獲取
# 獲取環境變量
import os
# 獲取特定的環境變量值
print(os.getenv('PATH'))
例項22:生成隨機密碼
# 使用random和string庫生成隨機密碼
import random
import string
defgenerate_password(length):
characters = string.ascii_letters + string.digits + string.punctuation
return''.join(random.choice(characters) for i in range(length))
print(generate_password(12))
例項23:計算執行時間
# 使用time模組計算函式執行時間
import time
deflong_running_task():
time.sleep(2)
start_time = time.time()
long_running_task()
end_time = time.time()
print(f"Execution time: {end_time - start_time} seconds")
例項24:簡單的TCP客戶端
# 使用socket庫建立一個簡單的TCP客戶端
import socket
HOST = '127.0.0.1'# The server's hostname or IP address
PORT = 65432# The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, server')
data = s.recv(1024)
print(f"Received {data.decode()}")
例項25:信件發送
# 使用smtplib發送信件
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '[email protected]'
receivers = ['[email protected]']
msg = MIMEText('Python email test', 'plain', 'utf-8')
msg['From'] = Header("Python Script", 'utf-8')
msg['To'] = Header("Test User", 'utf-8')
msg['Subject'] = Header('SMTP Email Test', 'utf-8')
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, msg.as_string())
print("Successfully sent email")
except smtplib.SMTPException:
print("Error: unable to send email")
例項26:讀取CSV檔
# 使用csv庫讀取CSV檔
import csv
filename = 'data.csv'
with open(filename, mode='r') as file:
csvReader = csv.reader(file)
for row in csvReader:
print(row)
例項27:寫入JSON檔
# 使用json庫寫入JSON檔
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
with open('data.json', 'w') as f:
json.dump(data, f)
例項28:解析命令列參數
# 使用argparse解析命令列參數
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
例項29:建立二維碼
# 使用qrcode庫建立二維碼
import qrcode
data = "https://www.example.com"
img = qrcode.make(data)
img.save("website_qr.png")
例項30:操作Excel檔
# 使用openpyxl庫操作Excel檔
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# 添加一行數據
ws.append(["Name", "Age", "Gender"])
ws.append(["John", 30, "Male"])
# 保存到檔
wb.save("sample.xlsx")
例項31:正規表式匹配
# 使用re模組進行正規表式匹配
import re
text = "The rain in Spain"
pattern = 'Spain'
match = re.search(pattern, text)
if match:
print("Match found")
else:
print("No match")
例項32:建立簡單的圖形化使用者介面(GUI)
# 使用tkinter建立簡單的GUI
import tkinter as tk
defon_click():
label.config(text="Hello, Tkinter!")
root = tk.Tk()
root.title("Simple GUI")
btn = tk.Button(root, text="Click Me", command=on_click)
btn.pack()
label = tk.Label(root, text="Welcome")
label.pack()
root.mainloop()
例項33:日期和時間操作
# 使用datetime模組進行日期和時間操作
from datetime import datetime, timedelta
now = datetime.now()
print("Current date and time:", now)
new_date = now + timedelta(days=10)
print("Date after 10 days:", new_date)
例項34:生成和解析XML
# 使用ElementTree生成和解析XML
import xml.etree.ElementTree as ET
# 建立XML數據
data = '''<person>
<name>John</name>
<age>30</age>
<city>New York</city>
</person>'''
# 解析XML
root = ET.fromstring(data)
print("Name:", root.find('name').text)
print("Age:", root.find('age').text)
print("City:", root.find('city').text)
例項35:執行緒使用
# 使用_thread啟動新執行緒
import _thread
import time
defprint_time(thread_name, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print(f"{thread_name}: {time.ctime(time.time())}")
try:
_thread.start_new_thread(print_time, ("Thread-1", 2))
_thread.start_new_thread(print_time, ("Thread-2", 4))
except:
print("Error: unable to start thread")
while1:
pass
例項36:復制檔
# 使用shutil模組復制檔
import shutil
source_file = 'source.txt'
target_file = 'destination.txt'
shutil.copy(source_file, target_file)
例項37:獲取網頁內容
# 使用requests獲取網頁內容
import requests
url = 'http://example.com'
response = requests.get(url)
print(response.text)
例項38:解析命令列參數(更高級)
# 使用argparse模組進行更高級的命令列參數解析
import argparse
parser = argparse.ArgumentParser(description="An advanced example.")
parser.add_argument("--quiet", action="store_true",
help="decrease output verbosity")
parser.add_argument("square", type=int,
help="display a square of a given number")
args = parser.parse_args()
answer = args.square**2
ifnot args.quiet:
print(f"The square of {args.square} is {answer}")
例項39:網路套接字編程
# 建立一個簡單的伺服器,使用sockets
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 1234))
s.listen(5)
whileTrue:
clientsocket, address = s.accept()
print(f"Connection from {address} has been established.")
clientsocket.send(bytes("Welcome to the server!", "utf-8"))
clientsocket.close()
例項40:使用Pandas處理數據
# 使用Pandas庫進行數據處理
import pandas as pd
# 建立DataFrame
data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],
'Age': [28, 34, 29, 32],
'City': ['New York', 'Paris', 'Berlin', 'London']}
df = pd.DataFrame(data)
# 顯示DataFrame
print(df)