有趣的小程序代码,用 Python 解锁编程乐趣130


Python 以其易用性和强大的功能而闻名,使其成为编写各种有趣小程序的理想选择。从文本游戏到图形界面小程序,以下是一些引人入胜的 Python 代码示例,让您领略编程的乐趣。

1. 猜数字游戏

编写一个简单的猜数字游戏,让计算机生成一个随机数,并提示用户猜测。用户可以不断输入猜测,直到猜中为止。代码如下:```python
import random
# 生成一个随机数
number = (1, 100)
# 获取用户的猜测
guess = int(input("猜测一个数字(1-100):"))
# 检查猜测是否正确
while guess != number:
if guess < number:
print("猜得太小了,再猜一次!")
else:
print("猜得太大了,再猜一次!")
guess = int(input("猜测一个数字(1-100):"))
# 猜测正确,打印祝贺信息
print("恭喜!你猜中了!")
```

2. 文本冒险游戏

使用 Python 创建一个简单的文本冒险游戏,其中用户可以在命令行界面中浏览不同的房间,收集物品并解决谜题。代码示例:```python
# 定义房间
rooms = {
"room1": {"description": "你在一间小房间里,有一扇门和一张桌子。",
"items": ["钥匙"],
"exits": ["room2"]},
"room2": {"description": "你在一间大房间里,有几张椅子和一扇窗户。",
"items": ["药水"],
"exits": ["room1", "room3"]},
"room3": {"description": "你在一间黑暗的房间里,有一扇门和一个箱子。",
"items": ["宝剑"],
"exits": ["room2"]}
}
# 当前房间
current_room = "room1"
# 游戏循环
while True:
# 打印当前房间描述
print(rooms[current_room]["description"])
# 显示房间中的物品
if len(rooms[current_room]["items"]) > 0:
print("物品:")
for item in rooms[current_room]["items"]:
print(f" - {item}")
# 显示房间中的出口
if len(rooms[current_room]["exits"]) > 0:
print("出口:")
for exit in rooms[current_room]["exits"]:
print(f" - {exit}")
# 获取用户输入
command = input("> ").lower()
if command == "exit":
break
elif command == "look":
# 查看当前房间
print(rooms[current_room]["description"])
elif ("go"):
# 移动到另一个房间
exit = command[3:]
if exit in rooms[current_room]["exits"]:
current_room = exit
else:
print("无法移动到该房间。")
elif ("take"):
# 获取物品
item = command[5:]
if item in rooms[current_room]["items"]:
rooms[current_room]["items"].remove(item)
print(f"你获取了 {item}。")
else:
print("该物品不存在或无法获取。")
elif ("use"):
# 使用物品
item = command[4:]
if item in rooms[current_room]["items"]:
# 使用物品并根据物品类型执行不同操作
...
else:
print("该物品不存在或无法使用。")
else:
print("无效命令。")
```

3. 图形界面计算器

使用 Python 的 Tkinter 库创建一个简单的图形界面计算器,允许用户输入数字和运算符并获得结果。代码示例:```python
import tkinter as tk
# 创建计算器窗口
window = ()
("计算器")
# 创建输入框
entry = (window)
()
# 创建按钮
buttons = [
["7", "8", "9", "/"],
["4", "5", "6", "*"],
["1", "2", "3", "-"],
["0", ".", "=", "+"]
]
for row in buttons:
frame = (window)
()
for button_text in row:
button = (frame, text=button_text)
(side=)
# 定义按钮事件处理程序
def button_click(button_text):
if button_text == "=":
# 计算结果
result = eval(())
(0, )
(0, result)
elif button_text == ".":
# 添加小数点
if "." not in ():
(, ".")
else:
# 添加数字或运算符
(, button_text)
# 绑定按钮事件处理程序
for button in buttons:
for button_text in button:
button = (window, text=button_text, command=lambda button_text=button_text: button_click(button_text))
# 运行计算器
()
```

4. 二叉树可视化

使用 Python 的 Turtle 库创建一个简单的二叉树可视化工具,允许用户输入二叉树并将其可视化为图形。代码示例:```python
import turtle
# 创建画布
canvas = ()
("white")
(-100, -100, 100, 100)
# 创建画笔
("black")
(2)
# 定义绘制二叉树的递归函数
def draw_tree(turtle, node, x, y, angle):
if node is None:
return
# 转到节点位置
()
(x, y)
()
# 绘制节点
(5)
# 绘制到左子节点的线
(angle - 45)
(50)
draw_tree(turtle, , x - 50, y - 50, angle - 45)
# 绘制到右子节点的线
(angle + 45)
(50)
draw_tree(turtle, , x + 50, y - 50, angle + 45)
# 获取用户输入的二叉树
tree_input = input("请输入二叉树(以中序遍历的形式):")
tree = convert_input_to_tree(tree_input)
# 绘制二叉树
draw_tree(turtle, tree, 0, 0, 90)
# 保持画布打开
()
```
这些只是您可以使用 Python 创建的众多有趣小程序代码示例中的几个。通过结合创造力和技术技能,您可以释放 Python 的全部潜力,构建引人入胜且有用的应用程序。

2024-10-15


上一篇:Python 文件保存指南:从新手到大师

下一篇:Python中保存文件的完整指南