有哪些好玩的 Python 代码?
以下是几个有趣的 Python 代码:
- 猜数字游戏
这是一个简单的猜数字游戏,让用户猜一个随机生成的数字。
import random
number = random.randint(1, 100)
guess = int(input("Guess a number between 1 and 100: "))
while guess != number:
if guess < number:
print("Too low!")
else:
print("Too high!")
guess = int(input("Guess again: "))
print("Congratulations! You guessed the number!")
- 爬取网页
使用 requests 模块和 BeautifulSoup 库,可以轻松地爬取网页内容。
import requests
from bs4 import BeautifulSoup
url = "https://www.python.org/"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
print(soup.title.text)
- 绘制图形
使用 turtle 模块可以绘制各种图形,如下面的例子绘制一个五角星。
import turtle
star = turtle.Turtle()
for i in range(5):
star.forward(100)
star.right(144)
turtle.done()
- 生成随机密码
使用 string 模块和 random 模块可以生成随机密码。
import string
import random
length = 8
chars = string.ascii_letters + string.digits + string.punctuation
password = "".join(random.choice(chars) for i in range(length))
print(password)
- 生成词云
使用 wordcloud 库可以生成漂亮的词云图,如下面的例子生成一个 Python 词云。
from wordcloud import WordCloud
import matplotlib.pyplot as plt
text = "Python is a popular programming language that is widely used for web development, scientific computing, data analysis, artificial intelligence, and more."
wordcloud = WordCloud().generate(text)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()