有趣的python代码合集
时间: 2023-07-10 22:03:30 浏览: 162
有趣的代码
以下是一些有趣的 Python 代码:
1. 将输入的字符串反转
```python
string = input("Enter a string: ")
print(string[::-1])
```
2. 输出斐波那契数列的前 n 项
```python
n = int(input("Enter the number of terms: "))
n1, n2 = 0, 1
count = 0
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",n,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < n:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
```
3. 判断一个数是否为质数
```python
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
```
4. 生成一个随机密码
```python
import random
import string
length = int(input("Enter the length of password: "))
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(length))
print("Random password is:", password)
```
5. 使用 Turtle 绘制彩色螺旋线
```python
import turtle
colors = ["red", "purple", "blue", "green", "orange", "yellow"]
t = turtle.Pen()
turtle.bgcolor("black")
for x in range(360):
t.pencolor(colors[x%6])
t.width(x/100 + 1)
t.forward(x)
t.left(59)
```
阅读全文