有哪些好玩的 Python 代码?
2023-05-11 阅读 36
以下是几个有趣的 Python 代码:
1. 猜数字游戏
这是一个简单的猜数字游戏,让用户猜一个随机生成的数字。
```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!")
```
2. 爬取网页
使用 `requests` 模块和 `BeautifulSoup` 库,可以轻松地爬取网页内容。
```python
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)
```
3. 绘制图形
使用 `turtle` 模块可以绘制各种图形,如下面的例子绘制一个五角星。
```python
import turtle
star = turtle.Turtle()
for i in range(5):
star.forward(100)
star.right(144)
turtle.done()
```
4. 生成随机密码
使用 `string` 模块和 `random` 模块可以生成随机密码。
```python
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)
```
5. 生成词云
使用 `wordcloud` 库可以生成漂亮的词云图,如下面的例子生成一个 Python 词云。
```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()
```
更新于 2023年05月15日