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 datacsv_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))
## 关于Python技术储备
学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后给大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!
包括:Python激活码+安装包、Python web开发,Python爬虫,Python数据分析,人工智能、自动化办公等学习教程。带你从零基础系统性的学好Python!
点击领取,100%免费!
👉Python所有方向的学习路线👈
Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。(全套教程文末领取)
👉Python学习视频600合集👈
观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
温馨提示:篇幅有限,已打包文件夹,获取方式在:文末
👉Python70个实战练手案例&源码👈
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
👉Python大厂面试资料👈
我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
👉Python副业兼职路线&方法👈
学好 Python 不论是就业还是做副业赚钱都不错,但要学会兼职接单还是要有一个学习规划。
👉 这份完整版的Python全套学习资料已经上传,朋友们如果需要可以扫描下方CSDN官方认证二维码或者点击链接免费领取【保证100%免费
】