老师,菜菜捞捞,Python趣味代码
时间: 2024-06-20 15:02:39 浏览: 135
"菜菜捞捞"这个名字看起来像是一个亲切的昵称,可能指的是某位热爱Python或教育领域的朋友。在Python中,编写趣味代码可以让学习过程变得更生动有趣。例如:
1. **Fibonacci数列游戏**:用递归或循环的方式生成斐波那契数列,并以动画或游戏的形式显示出来。
```python
def fibonacci(n):
if n <= 0:
return []
elif n == 1:
return
else:
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence
# 输出前10个斐波那契数
print(fibonacci(10))
```
2. **猜数字游戏**:创建一个简单的命令行游戏,让计算机随机选择一个数字,玩家尝试猜测。
```python
import random
number_to_guess = random.randint(1, 100)
guesses_taken = 0
while True:
guess = int(input("Guess a number between 1 and 100: "))
guesses_taken += 1
if guess < number_to_guess:
print("Too low!")
elif guess > number_to_guess:
print("Too high!")
else:
print(f"Congratulations! You guessed it in {guesses_taken} tries.")
break
```
阅读全文