几个有趣Python实例!
2024-12-28 12:09
以下是几个有趣的Python入门程序示例:
1. 猜数字游戏
```
import random
number = random.randint(1, 100)
guess = int(input("猜猜数字是多少(1-100):"))
while guess != number:
if guess < number:
print("猜小了")
else:
print("猜大了")
guess = int(input("再猜一次:"))
print("恭喜你,猜对了!")
```
2. 打字游戏
```
import time
word = "Hello, world!"
print("请在三秒内尽可能快地输入以下内容:", word)
start_time = time.time()
user_input = input()
end_time = time.time()
if user_input == word:
print("输入正确,用时:", end_time - start_time, "秒")
else:
print("输入错误")
```
3. 简单的计算器
```
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("请选择操作:")
print("1.加")
print("2.减")
print("3.乘")
print("4.除")
choice = input("请选择(1/2/3/4):")
num1 = float(input("请输入第一个数字:"))
num2 = float(input("请输入第二个数字:"))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("输入错误")
```