python好玩的代码

Python是一门非常灵活且强大的编程语言,可以用来实现各种有趣的代码。随机笑话生成器:使用API获取随机笑话并打印。

python
import requests def get_random_joke(): response = requests.get("https://api.icndb.com/jokes/random") joke = response.json()["value"]["joke"] return joke print(get_random_joke())

文字动画:在终端中创建简单的文字动画。

python
import time import sys def text_animation(text): for char in text: sys.stdout.write(char) sys.stdout.flush() time.sleep(0.1) text_animation("Hello, Python!")

猜数字游戏:编写一个简单的猜数字游戏。

python
import random def guess_the_number(): number_to_guess = random.randint(1, 100) guess = None while guess != number_to_guess: guess = int(input("猜猜看这个数字是多少:")) if guess < number_to_guess: print("太小了,再试试!") elif guess > number_to_guess: print("太大了,再试试!") else: print(f"恭喜你,猜对了!数字是 {number_to_guess}") guess_the_number()

简单的Web爬虫:使用BeautifulSoup库从网页中抓取信息。

python
import requests from bs4 import BeautifulSoup url = "https://www.example.com" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 提取标题 title = soup.title.string print(f"网页标题:{title}") # 提取所有链接 links = soup.find_all('a') for link in links: print(link.get('href'))

请确保在运行这些代码之前安装了相应的库。例如,使用

bash
pip install beautifulsoup4

这些示例只是展示了Python的一小部分有趣功能。你可以根据自己的兴趣和想法创建更多有趣的代码。

简单的文本游戏:创建一个简单的文本冒险游戏。

python
def text_adventure_game(): print("欢迎来到冒险游戏!") print("你发现自己站在两扇门前。") choice = input("你想进入左边的门还是右边的门?: ") if choice.lower() == "左": print("你进入了一个神秘的房间,发现一箱宝藏!恭喜你获胜!") elif choice.lower() == "右": print("你走进了一个黑暗的洞穴,里面有一只巨大的蜘蛛。你被吃掉了,游戏结束!") else: print("无效的选择,游戏结束。") text_adventure_game()

图像处理:使用Pillow库进行简单的图像处理。

python
from PIL import Image, ImageFilter # 打开图像文件 image = Image.open("example.jpg") # 应用模糊滤镜 blurred_image = image.filter(ImageFilter.BLUR) # 保存处理后的图像 blurred_image.save("blurred_example.jpg") print("图像处理完成,已保存为 blurred_example.jpg")

确保使用

bash
pip install pillow

生成随机密码:生成一个包含字母和数字的随机密码。

python
import random import string def generate_random_password(length=8): characters = string.ascii_letters + string.digits password = ''.join(random.choice(characters) for _ in range(length)) return password print("随机生成的密码:", generate_random_password())

这些例子只是冰山一角,Python提供了丰富的库和功能,可用于各种有趣的应用。你可以根据自己的兴趣进一步探索Python的强大之处。希望你能找到一些有趣的项目或挑战,不断提高自己的编程技能!

标签