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)