文件score.txt中有30个学生的成绩,将成绩读取出来后,计算成绩的最大值、最小值以及总和。
时间: 2023-04-28 08:00:07 浏览: 168
首先,需要打开score.txt文件,并将文件中的成绩读取出来。可以使用Python中的open()函数和readlines()方法来实现:
```
file = open('score.txt', 'r')
scores = file.readlines()
```
接下来,需要将读取出来的成绩转换为数字类型,并计算最大值、最小值和总和。可以使用Python中的for循环和内置函数来实现:
```
max_score = float('-inf')
min_score = float('inf')
total_score =
for score in scores:
score = float(score.strip())
if score > max_score:
max_score = score
if score < min_score:
min_score = score
total_score += score
```
最后,可以输出最大值、最小值和总和:
```
print('最大值:', max_score)
print('最小值:', min_score)
print('总和:', total_score)
```
完整代码如下:
```
file = open('score.txt', 'r')
scores = file.readlines()
max_score = float('-inf')
min_score = float('inf')
total_score =
for score in scores:
score = float(score.strip())
if score > max_score:
max_score = score
if score < min_score:
min_score = score
total_score += score
print('最大值:', max_score)
print('最小值:', min_score)
print('总和:', total_score)
```
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)