python好玩的代码推荐
时间: 2023-10-12 08:19:49 浏览: 41
以下是一些有趣的 Python 代码示例:
1. 猜数字游戏
```python
import random
number = random.randint(1, 10)
guesses = 0
while guesses < 3:
guess = int(input("猜一个数字(1-10):"))
guesses += 1
if guess == number:
print("恭喜你,你猜对了!")
break
elif guess < number:
print("你猜的数字太小了。")
else:
print("你猜的数字太大了。")
else:
print("很遗憾,你已经猜了3次,正确的数字是:", number)
```
2. 打印九九乘法表
```python
for i in range(1, 10):
for j in range(1, i+1):
print(f"{i}*{j}={i*j}", end="\t")
print()
```
3. 翻转字符串
```python
string = "Hello, world!"
reversed_string = string[::-1]
print(reversed_string)
```
4. 统计单词出现次数
```python
text = "This is a text. This text contains some words. Some words appear more than once in the text."
words = text.lower().split()
word_count = {}
for word in words:
if word not in word_count:
word_count[word] = 0
word_count[word] += 1
for word, count in word_count.items():
print(f"{word}: {count}")
```
5. 模拟掷骰子
```python
import random
while True:
input("按回车键掷骰子。")
number = random.randint(1, 6)
print("你掷得的数字是:", number)
if input("再掷一次?(y/n)") != "y":
break
```
希望这些代码示例能够给你带来一些乐趣和启发。