Python是一种功能强大的编程语言,可以用来创建许多有趣的程序。以下是一些有趣的Python程序示例:
石头剪刀布游戏
import randomdef rock_paper_scissors():choices = ["石头", "剪刀", "布"]computer_choice = random.choice(choices)user_choice = input("请输入你的选择(石头、剪刀、布): ")print(f"计算机选择了:{computer_choice}")if user_choice == computer_choice:print("平局!")elif (user_choice == "石头" and computer_choice == "剪刀") or \(user_choice == "剪刀" and computer_choice == "布") or \(user_choice == "布" and computer_choice == "石头"):print("你赢了!")else:print("你输了!")rock_paper_scissors()
猜数字游戏
import randomdef guess_the_number():number = random.randint(1, 100)attempts = 0print("我正在想一个1到100之间的数字。")while True:guess = int(input("请输入你的猜测: "))attempts += 1if guess < number:print("太小了,再试一次!")elif guess > number:print("太大了,再试一次!")else:print(f"恭喜你,猜对了!你一共用了{attempts}次机会。")breakguess_the_number()
计算BMI
def calculate_bmi():height = float(input("请输入你的身高(米): "))weight = float(input("请输入你的体重(千克): "))bmi = weight / (height 2)print(f"你的BMI是:{bmi:.2f}")if bmi < 18.5:print("体重过轻")elif 18.5 <= bmi < 24.9:print("正常范围")elif 25 <= bmi < 29.9:print("超重")else:print("肥胖")calculate_bmi()```生成随机数
import random
rnd = random.randint(1, 500)
print(f"随机数是:{rnd}")
读取和写入文件
写入文件
with open("example.txt", "w") as f:
f.write("Hello, World!")
读取文件
with open("example.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line.strip())
使用Pygame播放音乐
import pygame
pygame.init()
mixer = pygame.mixer.Sound("example.mp3")
mixer.play()
while mixer.get_busy():
pygame.time.Clock().tick(10)
图片转字符画
这是一个简化的示例,实际应用中需要更复杂的算法和库,如PIL和Pillow
import turtle
for _ in range(50):
turtle.forward(100)
turtle.right(10)
turtle.done()
2048游戏
这是一个简化的示例,实际应用中需要更复杂的逻辑和界面
import random
def move_up():
pass
def move_down():
pass
def move_left():
pass
def move_right():
pass
初始化游戏板
board = [[0 for _ in range(4)] for _ in range(4)]
放置初始数字
for i in range(2):
for j in range(2):
board[i][j] = random.randint(1, 2)
打印游戏板
for row in board:
print(" ".join(str(cell) for cell in row))
这些示例展示了Python在不同领域的应用,从简单的游戏到数据处理,再到图形界面和音乐播放。你可以根据自己的兴趣和需求,选择或修改这些示例来创建自己的有趣程序。如果你对以上示例

