以下是一些Python实战练习示例,涵盖不同难度和主题:
数字求绝对值:
import math num = -10 abs_value = math.abs(num) print("The absolute value of", num, "is", abs_value)骰子模拟器:
```python
import random
def roll_dice():
return random.randint(1, 6)
while True:
print("You rolled a:", roll_dice())
3. **斐波那契数列**:
```python
def fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib_seq = [0, 1]
for i in range(2, n):
fib_seq.append(fib_seq[i-1] + fib_seq[i-2])
return fib_seq
print(fibonacci(10))
- 猜数字游戏:
```python
import random
def game():
number_to_guess = random.randint(1, 100)
attempts = 0
while True:
user_guess = int(input("Guess a number between 1 and 100: "))
attempts += 1
if user_guess == number_to_guess:
print("Congratulations! You guessed the number in", attempts, "attempts.")
break
elif user_guess < number_to_guess:
print("Too low!")
else:
print("Too high!")
game()
5. **操作重载示例(< 运算符)**:
```python
class Game:
def __init__(self, score):
self.score = score
def __lt__(self, other):
return self.score < other.score
first = Game(1)
second = Game(2)
print(first < second) # 输出: True
- 文件读写操作:
```python
with open("example.txt", "w") as file:
file.write("Hello, World!")
with open("example.txt", "r") as file:
contents = file.read()
print(contents)
7. **网页抓取(使用requests和BeautifulSoup库)**:
```python
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
for link in soup.find_all("a"):
print(link.get("href"))
这些示例涵盖了基础的数学运算、随机数生成、递归算法、用户交互、类和对象、文件操作以及网络请求和网页解析等主题。根据你的需求和水平,可以选择适合的示例进行实践和学习。