有趣的python代码合集
时间: 2023-07-10 11:03:48 浏览: 41
以下是一些有趣的 Python 代码:
1. 打印出一颗圣诞树
```python
height = int(input("Enter the height of the Christmas tree: "))
for i in range(height):
print(' ' * (height - i - 1) + '*' * (2 * i + 1))
print(' ' * (height - 1) + '|')
```
2. 生成一个随机密码
```python
import random
lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
symbols = "!@#$%^&*()"
all = lower + upper + numbers + symbols
length = 16
password = "".join(random.sample(all, length))
print(password)
```
3. 计算一个字符串中每个单词出现的次数
```python
string = "This is a test string. This string is a test."
# 将字符串转换为小写,以便不区分大小写
string = string.lower()
# 拆分字符串为单词列表
words = string.split()
# 使用字典记录每个单词出现的次数
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
print(counts)
```
4. 绘制一个彩虹
```python
import turtle
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
turtle.penup()
turtle.goto(-200, 0)
turtle.pendown()
for color in colors:
turtle.color(color)
turtle.forward(50)
turtle.right(60)
turtle.done()
```
5. 生成一个随机漫步
```python
import turtle
import random
turtle.speed(0)
turtle.hideturtle()
for i in range(500):
turtle.setheading(random.randint(0, 360))
turtle.forward(random.randint(10, 50))
turtle.done()
```
希望这些代码可以让你感到有趣和启发。