Python 是一种广泛使用的高级编程语言,以其简洁的语法和丰富的库支持而受到开发者们的喜爱。以下列出了 27 个实用的 Python 实例,涵盖从基础到进阶的不同领域,帮助你提升编程技能。
1. 打印 "Hello, World!"
print("Hello, World!")
2. 计算两个数的和
num1 = 10
num2 = 20
sum = num1 + num2
print("Sum:", sum)
3. 斐波那契数列的前 N 项
def fibonacci(n):
a, b = 0, 1
series = []
for i in range(n):
series.append(a)
a, b = b, a + b
return series
print(fibonacci(10))
4. 找出列表中的最大和最小值
numbers = [10, 3, 5, 7, 9, 1]
print("Max:", max(numbers))
print("Min:", min(numbers))
5. 列表去重
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)
6. 列表排序
numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()
print(numbers)
7. 反转列表
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers)
8. 字典操作:添加、删除和查找
person = {'name': 'John', 'age': 30}
person['city'] = 'New York' # 添加
print(person)
del person['age'] # 删除
print(person)
print(person.get('name', 'Unknown')) # 查找
9. 列表推导式
squares = [x**2 for x in range(10)]
print(squares)
10. 读取和写入文件
# 写入
with open('example.txt', 'w') as file:
file.write("Hello, Python!\n")
# 读取
with open('example.txt', 'r') as file:
content = file.read()
print(content)
11. 使用函数计算阶乘
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
12. 字符串格式化
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")
13. 列表中的元素出现次数
from collections import Counter
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'grape']
print(Counter(words))
14. 列表切片
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # 切片操作
15. 遍历字典
person = {'name': 'John', 'age': 30, 'city': 'New York'}
for key, value in person.items():
print(key, value)
16. 使用 enumerate
遍历列表
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
17. 列表生成器
def gen_squares(n):
for i in range(n):
yield i**2
for square in gen_squares(5):
print(square)
18. 使用 map
函数
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)
19. 使用 filter
函数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
20. 递归打印目录结构
import os
def print_directory_contents(sPath):
for sChild in os.listdir(sPath):
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
print_directory_contents(sChildPath)
else:
print(sChildPath)
print_directory_contents('.')
21. 使用 re
模块进行正则表达式匹配
import re
text = "The rain in Spain falls mainly in the plain."
match = re.search(r"(\b\w+ain\b)", text)
if match:
print("Found", match.group())
22. 网络请求(使用 requests
库)
import requests
response = requests.get('https://api.github.com/users/github')
print(response.json())
23. 发送邮件(使用 smtplib
)
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
msg['From'] = "your-email@example.com"
msg['To'] = "recipient-email@example.com"
msg['Subject'] = "Hello Email"
msg.attach(MIMEText("This is the body of the email", 'plain'))
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login("your-email@example.com", "yourpassword")
text = msg.as_string()
server.sendmail("your-email@example.com", ["recipient-email@example.com"], text)
server.quit()
24. 使用 pandas
处理数据
import pandas as pd
data = {'Name': ['Tom', 'Jane', 'Steve', 'Ricky'],
'Age': [28, 34, 29, 42]}
df = pd.DataFrame(data)
print(df)
25. 简单的 Web 服务器(使用 http.server
)
# 在命令行中运行:python -m http.server 8000
26. 加密和解密数据(使用 cryptography
库)
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt(b"A really secret message. Not for prying eyes.")
print(cipher_text)
plain_text = cipher_suite.decrypt(cipher_text)
print(plain_text)
27. 使用 matplotlib
绘图
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
plt.title("Simple Plot")
plt.xlabel("x axis label")
plt.ylabel("y axis label")
plt.show()
这些实例涵盖了 Python 编程的多个方面,从基础语法到高级库的使用,适合不同水平的 Python 学习者。
Python学习资料(项目源码、安装包、电子书、视频教程)已经打包好啦! 需要的小伙伴下方链接领取哦!或者下方扫码拿走!