如果你正在学习Python,那么你需要的话可以,点击这里👉Python重磅福利:入门&进阶全套学习资料、电子书、软件包、项目源码等等免费分享!
前言
Python,作为一种高级编程语言,以其简洁的语法、丰富的库支持和广泛的应用领域,成为了数据科学、人工智能、Web开发、自动化脚本编写等多个领域的首选语言。无论是初学者还是经验丰富的开发者,都能从Python的灵活性和强大功能中受益。本文旨在通过20个精选的Python实例,展示Python在不同场景下的应用,帮助读者快速掌握Python编程的精髓,并激发对Python编程的浓厚兴趣。
1. 计算器程序:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
try:
return x / y
except ZeroDivisionError:
print("除数不能为零")
print("选择操作:")
print("1.加法")
print("2.减法")
print("3.乘法")
print("4.除法")
choice = input("输入操作序号(1/2/3/4): ")
num1 = float(input("输入第一个数字: "))
num2 = float(input("输入第二个数字: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("输入错误")
2. 列表去重:
def unique_elements(input_list):
return list(set(input_list))
my_list = [1, 2, 2, 3, 4, 4, 5]
print("原始列表:", my_list)
print("去重后的列表:", unique_elements(my_list))
3. 文件内容复制:
def copy_file(source_path, destination_path):
with open(source_path, 'r') as source:
with open(destination_path, 'w') as destination:
for line in source:
destination.write(line)
source_file = 'source.txt'
destination_file = 'destination.txt'
copy_file(source_file, destination_file)
print("文件复制完成。")
4. 字符串反转:
def reverse_string(input_string):
return input_string[::-1]
print("反转前的字符串:", "Hello World")
print("反转后的字符串:", reverse_string("Hello World"))
5. 生成随机密码:
import random
import string
def generate_password(length):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(length))
return password
password_length = 10
print("生成的密码:", generate_password(password_length))
6. 简单的网页爬虫:
import requests
from bs4 import BeautifulSoup
def simple_web_crawler(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
return soup.get_text()
website = 'https://www.example.com'
print("网站内容:", simple_web_crawler(website))
7. 排序列表:
def sort_list(input_list):
return sorted(input_list)
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
print("未排序的列表:", my_list)
print("排序后的列表:", sort_list(my_list))
8. 计算字符频率:
from collections import Counter
def character_frequency(input_string):
return Counter(input_string)
my_string = "hello world"
print("字符频率:", character_frequency(my_string))
9. 生成斐波那契数列:
def fibonacci(n):
a, b = 0, 1
result = []
for _ in range(n):
result.append(a)
a, b = b, a + b
return result
print("斐波那契数列前10个数:", fibonacci(10))
10. 简单的待办事项应用:
class Todo:
def __init__(self):
self.tasks = []
def add_task(self, task):
self.tasks.append(task)
def remove_task(self, task):
self.tasks.remove(task)
def display_tasks(self):
for index, task in enumerate(self.tasks):
print(f"{index}. {task}")
my_todo = Todo()
my_todo.add_task("Learn Python")
my_todo.add_task("Read a book")
my_todo.display_tasks()
my_todo.remove_task("Read a book")
my_todo.display_tasks()
11. 文本分析 - 计算单词数量:
def count_words(text):
words = text.split()
return len(words)
text = "This is a simple text for word counting."
print("单词数量:", count_words(text))
12. 数据可视化 - 使用Matplotlib绘制简单折线图:
import matplotlib.pyplot as plt
def plot_line_graph(x_values, y_values, title, x_label, y_label):
plt.plot(x_values, y_values)
plt.title(title)
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.show()
x_values = [1, 2, 3, 4]
y_values = [10, 40, 50, 20]
plot_line_graph(x_values, y_values, "Simple Line Graph", "X-axis", "Y-axis")
13. 自动化脚本 - 重命名文件:
import os
def rename_files(directory, new_name):
for filename in os.listdir(directory):
old_file = os.path.join(directory, filename)
new_file = os.path.join(directory, new_name + os.path.splitext(filename)[1])
os.rename(old_file, new_file)
rename_files('/path/to/directory', 'new_filename')
14. 网络应用 - 检查网站是否可用:
import requests
def check_website_status(url):
try:
response = requests.get(url)
if response.status_code == 200:
return True
else:
return False
except requests.exceptions.RequestException:
return False
website = 'https://www.example.com'
print("网站是否可用:", check_website_status(website))
15. 日期和时间 - 格式化当前日期:
from datetime import datetime
def format_current_date(format_string='%Y-%m-%d'):
return datetime.now().strftime(format_string)
print("当前日期:", format_current_date())
16. 文件处理 - 读取CSV文件内容:
import csv
def read_csv_file(file_path):
with open(file_path, newline='') as csvfile:
reader = csv.reader(csvfile)
data = [row for row in reader]
return data
csv_file = 'example.csv'
data = read_csv_file(csv_file)
print(data)
17. 正则表达式 - 验证电子邮件地址:
import re
def validate_email(email):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
return re.match(pattern, email) is not None
email = "example@example.com"
print("电子邮件地址有效:", validate_email(email))
18. 数据加密 - 使用MD5加密字符串:
import hashlib
def encrypt_string(text):
return hashlib.md5(text.encode()).hexdigest()
encrypted_text = encrypt_string("Hello World!")
print("加密后的字符串:", encrypted_text)
19. 数据筛选 - 筛选列表中的偶数:
def filter_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0]
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter_even_numbers(numbers)
print("偶数列表:", even_numbers)
20. 进程管理 - 运行外部命令:
import subprocess
def run_command(command):
try:
result = subprocess.check_output(command, shell=True)
return result.decode('utf-8').strip()
except subprocess.CalledProcessError as e:
return e.output.decode('utf-8').strip()
command = "ls -l"
print("命令输出:", run_command(command))
这20个实例覆盖了Python编程的多个方面,从基础语法到高级特性,再到实际应用,旨在帮助读者全面了解和掌握Python编程。希望这些实例能够激发你的学习兴趣,让你在Python编程的道路上越走越远。
如果你正在学习Python,那么你需要的话可以,点击这里👉Python重磅福利:入门&进阶全套学习资料、电子书、软件包、项目源码等等免费分享!或扫描下方CSDN官方微信二维码获娶Python入门&进阶全套学习资料、电子书、软件包、项目源码