Python模块与包练习小例子
时间: 2024-01-16 12:02:55 浏览: 78
好的,以下是一些Python模块与包的练习小例子,供你参考:
1. 计算字符串中元音字母的数量
```python
def count_vowels(string):
vowels = ['a', 'e', 'i', 'o', 'u']
count = 0
for char in string:
if char.lower() in vowels:
count += 1
return count
```
2. 计算列表中的最大值和最小值
```python
def min_max(numbers):
return min(numbers), max(numbers)
```
3. 实现一个计算圆面积和周长的函数和一个计算平均值和标准差的函数
```python
# math模块
import math
def circle_area(radius):
return math.pi * radius ** 2
def circle_circumference(radius):
return 2 * math.pi * radius
# stats模块
def mean(numbers):
return sum(numbers) / len(numbers)
def std_dev(numbers):
mean_value = mean(numbers)
variance = sum((x - mean_value) ** 2 for x in numbers) / len(numbers)
return math.sqrt(variance)
```
4. 对学生列表按照成绩从高到低排序
```python
class Student:
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def __repr__(self):
return f'{self.name} ({self.age}) - {self.score}'
def sort_students(students):
return sorted(students, key=lambda student: student.score, reverse=True)
```
5. 实现一个简单的计算器应用程序
```python
# calculator模块
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
# 应用程序
import calculator
print('欢迎使用简单计算器')
num1 = float(input('请输入第一个数字:'))
num2 = float(input('请输入第二个数字:'))
operator = input('请选择运算符 (+, -, *, /):')
if operator == '+':
result = calculator.add(num1, num2)
elif operator == '-':
result = calculator.subtract(num1, num2)
elif operator == '*':
result = calculator.multiply(num1, num2)
elif operator == '/':
result = calculator.divide(num1, num2)
else:
print('无效的运算符')
print(f'计算结果为:{result}')
```
以上是一些Python模块与包的练习小例子,希望对你有所帮助。
阅读全文
相关推荐


















