好玩的python代码
时间: 2023-07-10 13:04:27 浏览: 122
有趣的代码
以下是一些有趣的 Python 代码:
1. 生成随机密码
```python
import random
import string
password = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
print(password)
```
2. 打印彩色文字
```python
class colors:
reset = '\033[0m'
red = '\033[31m'
green = '\033[32m'
yellow = '\033[33m'
blue = '\033[34m'
print(colors.red + "Hello" + colors.green + " World!" + colors.reset)
```
3. 猜数字游戏
```python
import random
number = random.randint(1, 100)
guess = None
while guess != number:
guess = int(input("Guess a number between 1 and 100: "))
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("You guessed it!")
```
4. 统计字母出现次数
```python
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
letter_count = {}
for letter in text:
if letter.isalpha():
letter = letter.lower()
if letter not in letter_count:
letter_count[letter] = 1
else:
letter_count[letter] += 1
for letter, count in letter_count.items():
print(letter, count)
```
这些代码只是其中的几个例子,如果你想要更多有趣的 Python 代码,可以在网上搜索或浏览 GitHub 仓库。
阅读全文