以下是Python中简短有趣的代码示例,涵盖不同应用场景,兼具趣味性和实用性:
一、随机笑话生成
import pyjokes
joke = pyjokes.get_joke()
print("Here's a random joke:", joke)
通过pyjokes
库快速生成随机笑话,提升编程学习趣味性。
二、文字冒险游戏
import random
health = 100
print("欢迎来到神秘森林!")
while health > 0:
action = input("前进/探索/休息: ").lower()
if action == "前进":
encounter = random.randint(1, 3)
if encounter == 1:
health += 20
print("遇到小鹿,获得20点生命值!")
elif encounter == 2:
health -= 10
print("遭遇陷阱,损失10点生命值!")
elif action == "探索":
print("探索未知区域...")
elif action == "休息":
health += 5
print("恢复5点生命值...")
else:
print("无效操作!")
if health <= 0:
print("游戏结束!")
break
利用random
模块实现简单文字交互,适合初学者练习条件判断和随机事件处理。
三、列表推导式与字典操作
-
列表去重
my_list = [1, 2, 2, 3, 4, 4, 5] unique_list = list(set(my_list)) print(unique_list) # [1, 2, 3, 4, 5]
通过
set
和list
转换实现快速去重。 -
字典键值对调换
my_dict = {'a': 1, 'b': 2, 'c': 3} swapped_dict = {v: k for k, v in my_dict.items()} print(swapped_dict) # {1: 'a', 2: 'b', 3: 'c'}
使用字典推导式实现键值对反转。
四、二进制转十进制
decimal = int('1010', 2)
print(decimal) # 10
一行代码完成二进制到十进制的转换,简洁高效。
五、猜数字游戏
import random
secret_number = random.randint(1, 100)
attempts = 0
print("猜数字游戏!")
while True:
user_guess = int(input("请输入你的猜测: "))
attempts += 1
if user_guess == secret_number:
print(f"恭喜你,猜对了!用了{attempts}次。")
break
elif user_guess < secret_number:
print("太小了!")
else:
print("太大了!")
通过random
生成随机数,结合循环和条件判断实现基础猜谜功能。
六、Turtle绘制螺旋
import turtle
import random
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
t = turtle.Turtle()
t.speed(0)
for i in range(200):
t.pencolor(random.choice(colors))