有趣的python程序
时间: 2023-05-27 22:01:22 浏览: 101
以下是一些有趣的Python程序:
1. 猜数字游戏:
```python
import random
secret_number = random.randint(1, 100)
guess = 0
tries = 0
print("Welcome to the Guess That Number game!")
print("I'm thinking of a number between 1 and 100.")
print("You have 10 tries to guess it.\n")
while guess != secret_number and tries < 10:
guess = int(input("Enter your guess: "))
if guess < secret_number:
print("Too low.")
elif guess > secret_number:
print("Too high.")
tries += 1
if guess == secret_number:
print("\nCongratulations! You guessed my number in", tries, "tries!")
else:
print("\nSorry, you failed to guess my number. It was", secret_number)
```
2. 计算器程序:
```python
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("Select operation.")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
while True:
choice = input("Enter choice (1/2/3/4): ")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
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))
break
else:
print("Invalid Input")
```
3. 矩阵乘法程序:
```python
def matrix_multiplication(X, Y):
result = []
for i in range(len(X)):
row = []
for j in range(len(Y[0])):
sum = 0
for k in range(len(Y)):
sum += X[i][k] * Y[k][j]
row.append(sum)
result.append(row)
return result
X = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Y = [[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]
result = matrix_multiplication(X, Y)
for row in result:
print(row)
```
4. 无限制斐波那契数列生成器:
```python
a, b = 0, 1
while True:
yield a
a, b = b, a + b
```
5. 简单的爬虫程序:
```python
import requests
import re
url = 'https://www.wikipedia.org/'
response = requests.get(url)
if response.status_code == 200:
pattern = re.compile('<title>(.*?)</title>')
title = re.search(pattern, response.text)
print(title.group(1))
else:
print("Error:" + response.status_code)
```
这些程序可以帮助你理解Python语言的特点和功能。如果你对Python编程感兴趣,可以继续学习并编写更复杂的程序。
阅读全文