python有趣的小项目代码
时间: 2024-06-06 21:04:27 浏览: 7
Python有很多有趣的小项目代码,以下是一些例子:
1. “石头剪刀布”游戏
这是一个简单的游戏,可以让你与计算机玩“石头剪刀布”游戏。代码如下:
```
import random
def play_game():
player_choice = input("Enter your choice (rock/paper/scissors): ")
computer_choice = random.choice(["rock", "paper", "scissors"])
print("You chose", player_choice)
print("Computer chose", computer_choice)
if player_choice == computer_choice:
print("It's a tie!")
elif player_choice == "rock" and computer_choice == "scissors":
print("You win!")
elif player_choice == "paper" and computer_choice == "rock":
print("You win!")
elif player_choice == "scissors" and computer_choice == "paper":
print("You win!")
else:
print("Computer wins!")
while True:
play_game()
play_again = input("Play again? (y/n): ")
if play_again.lower() != "y":
break
```
2. 生成随机密码
这个小项目可以让你生成随机密码,代码如下:
```
import random
import string
def generate_password(length):
letters = string.ascii_letters + string.digits + string.punctuation
password = "".join(random.choice(letters) for i in range(length))
return password
print(generate_password(10))
```
3. 爬取网站数据
这个小项目可以让你爬取网站数据,代码如下:
```
import requests
from bs4 import BeautifulSoup
url = "https://www.csdn.net/"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
for article in soup.find_all("div", class_="title"):
print(article.text.strip())
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)