愚人节 有什么好玩的python代码
时间: 2024-05-04 18:15:23 浏览: 144
以下是一些有趣的 Python 代码:
1. 生成随机密码:
```python
import random
import string
def generate_password(length):
letters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(letters) for i in range(length))
print(generate_password(10))
```
2. 翻转字符串:
```python
def reverse_string(s):
return s[::-1]
print(reverse_string('Hello, world!'))
```
3. 打印彩虹:
```python
import time
colors = ['\033[31m', '\033[33m', '\033[32m', '\033[36m', '\033[34m', '\033[35m']
text = 'Happy April Fools\' Day!'
for i in range(len(text)):
print(colors[i % len(colors)] + text[i], end='')
time.sleep(0.1)
print('\033[0m')
```
4. 打印倒三角形:
```python
def print_triangle(n):
for i in range(n, 0, -1):
print(' ' * (n - i) + '*' * (2 * i - 1))
print_triangle(5)
```
5. 打印斐波那契数列:
```python
def fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib
print(fibonacci(10))
```
这些代码可以用作愚人节的玩笑或简单的编程练习。
阅读全文