包含编程籽料、学习路线图、爬虫代码、安装包等!【点击领取】
前言
Python作为当下最流行的编程语言之一,以其简洁的语法和强大的功能吸引了无数开发者。今天,我将为大家分享10个既有趣又实用的Python脚本,这些脚本涵盖了从基础到进阶的各种知识点,不仅能帮助你巩固Python基础,还能让你在实践中感受到编程的乐趣!
1. 猜数字游戏
import random
def guess_number():
number = random.randint(1, 100)
attempts = 0
print("欢迎来到猜数字游戏!")
print("我已经想好了一个1到100之间的数字,来猜猜看吧!")
while True:
guess = int(input("请输入你猜的数字: "))
attempts += 1
if guess < number:
print("太小了,再大一点!")
elif guess > number:
print("太大了,再小一点!")
else:
print(f"恭喜你!猜对了!你用了{attempts}次尝试。")
break
guess_number()
知识点:随机数生成、循环结构、条件判断、用户输入处理
2. 简易密码生成器
import random
import string
def generate_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
print("生成的密码是:", generate_password())
知识点:字符串操作、随机选择、列表推导式
3. 网络爬虫 - 获取天气信息
import requests
from bs4 import BeautifulSoup
def get_weather(city):
url = f"https://www.weather.com/weather/today/l/{city}"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
temperature = soup.find('span', {'class': 'CurrentConditions--tempValue--3KcTQ'}).text
condition = soup.find('div', {'class': 'CurrentConditions--phraseValue--2xXSr'}).text
print(f"{city}当前天气: {condition}, 温度: {temperature}")
get_weather("Beijing")
知识点:HTTP请求、HTML解析、BeautifulSoup库使用
4. 图片转ASCII艺术
from PIL import Image
def image_to_ascii(image_path, output_width=100):
# ASCII字符集,从暗到亮
ascii_chars = "@%#*+=-:. "
# 打开并调整图片大小
image = Image.open(image_path)
width, height = image.size
ratio = height / width
new_height = int(output_width * ratio)
resized_image = image.resize((output_width, new_height))
# 转换为灰度图
grayscale_image = resized_image.convert("L")
pixels = grayscale_image.getdata()
# 将像素映射到ASCII字符
ascii_str = ""
for pixel_value in pixels:
ascii_str += ascii_chars[pixel_value // 25]
# 格式化输出
ascii_str_len = len(ascii_str)
for i in range(0, ascii_str_len, output_width):
print(ascii_str[i:i+output_width])
image_to_ascii("example.jpg")
知识点:图像处理、Pillow库使用、ASCII艺术生成
5. 简易计算器
def calculator():
print("简易计算器")
print("支持的操作: +, -, *, /")
while True:
try:
num1 = float(input("输入第一个数字: "))
operator = input("输入运算符: ")
num2 = float(input("输入第二个数字: "))
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
result = num1 / num2
else:
print("无效运算符")
continue
print(f"结果: {result}")
except ValueError:
print("请输入有效的数字!")
except ZeroDivisionError:
print("不能除以零!")
another = input("继续计算吗?(y/n): ")
if another.lower() != 'y':
break
calculator()
知识点:异常处理、用户交互、基本数学运算
6. 单词频率统计器
from collections import Counter
import re
def word_frequency(text):
# 使用正则表达式提取单词并转换为小写
words = re.findall(r'\b\w+\b', text.lower())
word_counts = Counter(words)
# 按频率排序
sorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
print("单词频率统计:")
for word, count in sorted_words[:10]: # 显示前10个高频词
print(f"{word}: {count}次")
sample_text = """
Python is an interpreted, high-level and general-purpose programming language.
Python's design philosophy emphasizes code readability with its notable use of significant whitespace.
"""
word_frequency(sample_text)
知识点:正则表达式、集合操作、Counter类、lambda函数
7. 简易待办事项管理器
import json
import os
TODO_FILE = "todo_list.json"
def load_todos():
if os.path.exists(TODO_FILE):
with open(TODO_FILE, 'r') as f:
return json.load(f)
return []
def save_todos(todos):
with open(TODO_FILE, 'w') as f:
json.dump(todos, f)
def todo_manager():
todos = load_todos()
while True:
print("\n待办事项管理器")
print("1. 查看待办事项")
print("2. 添加待办事项")
print("3. 标记完成")
print("4. 删除待办事项")
print("5. 退出")
choice = input("请选择操作: ")
if choice == '1':
print("\n当前待办事项:")
for i, todo in enumerate(todos, 1):
status = "✓" if todo['completed'] else "✗"
print(f"{i}. [{status}] {todo['task']}")
elif choice == '2':
task = input("输入新的待办事项: ")
todos.append({"task": task, "completed": False})
save_todos(todos)
print("已添加!")
elif choice == '3':
try:
index = int(input("输入要标记完成的序号: ")) - 1
todos[index]['completed'] = True
save_todos(todos)
print("已标记完成!")
except (ValueError, IndexError):
print("无效的序号!")
elif choice == '4':
try:
index = int(input("输入要删除的序号: ")) - 1
del todos[index]
save_todos(todos)
print("已删除!")
except (ValueError, IndexError):
print("无效的序号!")
elif choice == '5':
print("再见!")
break
else:
print("无效的选择!")
todo_manager()
知识点:文件操作、JSON数据处理、CRUD操作实现
8. 简易聊天机器人
import random
responses = {
"你好": ["你好!", "嗨!", "很高兴见到你!"],
"你叫什么名字": ["我是Python聊天机器人", "你可以叫我Bot", "我没有名字,你可以给我取一个"],
"今天天气怎么样": ["我不知道,你可以查一下天气预报", "看起来不错!", "我建议你出门看看"],
"再见": ["再见!", "下次见!", "祝你有个美好的一天!"],
"默认": ["我不太明白你的意思", "能换个说法吗?", "这个我还不会回答"]
}
def chatbot():
print("聊天机器人已启动! 输入'再见'结束对话")
while True:
user_input = input("你: ")
if user_input.lower() == "再见":
print("机器人:", random.choice(responses["再见"]))
break
response = responses.get(user_input, responses["默认"])
print("机器人:", random.choice(response))
chatbot()
知识点:字典数据结构、随机选择、简单AI交互
9. 文件加密解密工具
from cryptography.fernet import Fernet
def generate_key():
return Fernet.generate_key()
def save_key(key, key_file):
with open(key_file, 'wb') as f:
f.write(key)
def load_key(key_file):
return open(key_file, 'rb').read()
def encrypt_file(input_file, output_file, key):
fernet = Fernet(key)
with open(input_file, 'rb') as f:
original = f.read()
encrypted = fernet.encrypt(original)
with open(output_file, 'wb') as f:
f.write(encrypted)
def decrypt_file(input_file, output_file, key):
fernet = Fernet(key)
with open(input_file, 'rb') as f:
encrypted = f.read()
decrypted = fernet.decrypt(encrypted)
with open(output_file, 'wb') as f:
f.write(decrypted)
# 使用示例
key = generate_key()
save_key(key, 'secret.key')
# 加密文件
encrypt_file('test.txt', 'test.encrypted', key)
# 解密文件
decrypt_file('test.encrypted', 'test_decrypted.txt', key)
知识点:加密解密原理、Fernet加密、文件操作
10. 简易股票价格监控
import requests
import time
from datetime import datetime
def stock_monitor(symbol, interval=60):
api_key = "YOUR_API_KEY" # 替换为你的API密钥
base_url = "https://www.alphavantage.co/query"
print(f"开始监控 {symbol} 股票价格...")
while True:
params = {
"function": "GLOBAL_QUOTE",
"symbol": symbol,
"apikey": api_key
}
response = requests.get(base_url, params=params)
data = response.json()
if "Global Quote" in data:
quote = data["Global Quote"]
price = quote["05. price"]
change = quote["09. change"]
change_percent = quote["10. change percent"]
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"{timestamp} - {symbol}: ${price} ({change} {change_percent})")
else:
print("无法获取股票数据")
time.sleep(interval)
# 使用示例 (需要注册Alpha Vantage获取API密钥)
# stock_monitor("AAPL") # 监控苹果公司股票
知识点:API调用、JSON数据处理、定时任务
结语
这10个Python脚本涵盖了从基础到进阶的多个知识点,每个脚本都有其独特的实用性和趣味性。通过实践这些脚本,你不仅能巩固Python基础知识,还能学习到许多实用的编程技巧。
最后:
希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!
文末福利
最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
包含编程资料、学习路线图、源代码、软件安装包等!【点击这里】领取!
① Python所有方向的学习路线图,清楚各个方向要学什么东西
② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析
③ 100多个Python实战案例,学习不再是只会理论
④ 华为出品独家Python漫画教程,手机也能学习