Python 简单小游戏与实用脚本代码示例:石头剪刀布、邮件发送等
Python 简单小游戏与实用脚本代码示例,涵盖命令行石头剪刀布、自动发送邮件、猜单词(Hangman)及闹钟功能。文章提供完整可运行代码,修复了原稿中的语法错误和缩进问题,并补充了必要的库安装说明与环境配置提示。此外还包含了天气查询应用的爬虫逻辑框架,适合初学者练习基础逻辑与模块调用,无需关注无关的推广信息。

Python 简单小游戏与实用脚本代码示例,涵盖命令行石头剪刀布、自动发送邮件、猜单词(Hangman)及闹钟功能。文章提供完整可运行代码,修复了原稿中的语法错误和缩进问题,并补充了必要的库安装说明与环境配置提示。此外还包含了天气查询应用的爬虫逻辑框架,适合初学者练习基础逻辑与模块调用,无需关注无关的推广信息。

本文整理了多个基于 Python 的入门级游戏与实用脚本,涵盖命令行交互、网络请求及系统功能调用。内容包含完整的可运行代码,修复了常见语法错误,并补充了环境配置与逻辑说明,适合初学者练习基础编程逻辑。
这是一个经典的命令行游戏。程序随机生成计算机的选择(石头、剪刀或布),用户输入自己的选择。通过比较双方的选择判定胜负,并统计分数直到用户退出。
无需额外第三方库,使用 Python 标准库 random 即可。
import random
choices = ["Rock", "Paper", "Scissors"]
computer = random.choice(choices)
player_score = 0
cpu_score = 0
while True:
player = input("Rock, Paper or Scissors? ").capitalize()
if player == computer:
print("Tie!")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
cpu_score += 1
else:
print("You win!", player, "smashes", computer)
player_score += 1
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
cpu_score += 1
else:
print("You win!", player, "covers", computer)
player_score += 1
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
cpu_score += 1
else:
print("You win!", player, "cut", computer)
player_score += 1
elif player == 'E':
print("Final Scores:")
print(f"CPU: {cpu_score}")
print(f"Player: {player_score}")
break
else:
print("That's not a valid play. Check your spelling!")
continue
computer = random.choice(choices)
.py 文件。python filename.py。编写一个 Python 脚本,利用 SMTP 协议自动发送电子邮件。适用于批量通知或自动化报告场景。
需要安装 smtplib (标准库) 和 email (标准库)。注意:Gmail 等邮箱服务通常需要在设置中开启'允许不安全的应用'或使用应用专用密码。
import smtplib
from email.message import EmailMessage
# 创建邮件对象
email = EmailMessage()
email['from'] = '[email protected]' # 替换为你的发件人邮箱
email['to'] = '[email protected]' # 替换为你的收件人邮箱
email['subject'] = '测试邮件主题'
email.set_content('这是邮件正文内容')
try:
with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:
smtp.ehlo() # 服务器握手
smtp.starttls() # 启用加密传输
smtp.login('[email protected]', 'your_password_or_app_key') # 登录认证
smtp.send_message(email) # 发送邮件
print("邮件发送成功")
except Exception as e:
print(f"发送失败:{e}")
程序从预设列表中随机选择一个单词,用下划线表示未猜出的字母。用户每次猜测一个字符,猜对显示该字母,猜错减少剩余机会。
无需额外第三方库,使用 random 和 time 标准库。
import time
import random
name = input("What is your name? ")
print("Hello, " + name, "Time to play hangman!")
time.sleep(1)
print("Start guessing...\n")
time.sleep(0.5)
words = ['python', 'programming', 'treasure', 'creative', 'medium', 'horror']
word = random.choice(words)
guesses = ''
turns = 5
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print(char, end="")
else:
print("_", end="")
failed += 1
if failed == 0:
print("\nYou won!")
break
guess = input("\nguess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("\nWrong")
print("\nYou have", turns, 'more guesses')
if turns == 0:
print("\nYou Lose")
创建一个简单的桌面闹钟,到达设定时间后播放声音提醒。
需要安装 playsound 库来播放音频文件。
pip install playsound
同时需要准备一个名为 audio.mp3 的音频文件放在同一目录下。
from datetime import datetime
from playsound import playsound
alarm_time = input("Enter the time of alarm to be set (HH:MM:SS): ")
alarm_hour = alarm_time[0:2]
alarm_minute = alarm_time[3:5]
alarm_seconds = alarm_time[6:8]
alarm_period = alarm_time[9:11].upper()
print("Setting up alarm...")
while True:
now = datetime.now()
current_hour = now.strftime("%I")
current_minute = now.strftime("%M")
current_seconds = now.strftime("%S")
current_period = now.strftime("%p")
if alarm_period == current_period:
if alarm_hour == current_hour:
if alarm_minute == current_minute:
if alarm_seconds == current_seconds:
print("Wake Up!")
playsound('audio.mp3')
break
接收城市名称,通过网络爬虫获取该城市的实时天气信息。
需要安装 requests 和 BeautifulSoup。
pip install requests beautifulsoup4
注:由于网页结构经常变动,以下代码演示了基本的爬取逻辑框架,实际使用时需根据目标网站 HTML 结构调整选择器。
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
url = "https://example-weather-site.com/weather/beijing" # 替换为目标天气网站 URL
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# 假设温度数据在 class="temp" 的元素中,请根据实际页面修改
temp_element = soup.find(class_='temp')
if temp_element:
temperature = temp_element.get_text(strip=True)
print(f"当前温度:{temperature}")
else:
print("未能找到温度数据,请检查网页结构")
except requests.exceptions.RequestException as e:
print(f"网络请求失败:{e}")
except Exception as e:
print(f"解析出错:{e}")
以上代码涵盖了 Python 基础控制流、模块导入、网络请求及系统交互等核心知识点。建议读者在本地环境逐一运行,并根据实际需求修改参数。学习过程中遇到报错时,请优先检查缩进、引号匹配及依赖库版本是否兼容。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online