用Python写程序,从键盘输入几个学生的成绩(整数),输入-1分时,结束输入成绩,计算并输出平均分。
时间: 2023-06-01 09:02:29 浏览: 173
scores = []
while True:
score = int(input("请输入学生成绩(输入-1结束):"))
if score == -1:
break
scores.append(score)
average = sum(scores) / len(scores)
print("平均分为:", average)
相关问题
用python写程序。键盘输入若干个学生的成绩(整数),输入-1分时,结束输入成绩,计算并输出平均分。
A:
```python
sum = 0
count = 0
while True:
score = int(input("请输入学生的成绩(输入-1结束):"))
if score == -1:
break
sum += score
count += 1
if count == 0:
print("没有输入任何成绩")
else:
print("平均分为:", sum/count)
```
解释:
1. 定义两个变量`sum`和`count`,分别用于存储总分和学生人数。
2. 使用`while True`语句无限循环,直到输入-1结束。
3. 每次循环中,使用`input`函数获取用户输入的成绩,并将其转换成整数类型。
4. 如果输入的成绩是-1,则跳出循环。
5. 否则,将成绩累加到`sum`变量中,并将`count`加1。
6. 在循环结束后,判断是否有输入任何成绩。如果没有,则输出相应的提示信息。
7. 否则,计算平均分,并输出结果。
用python写从键盘输入一批学生的成绩,计算平均分。
以下是用Python实现从键盘输入一批学生的成绩,计算平均分的代码:
```python
# 获取学生数量
n = int(input("请输入学生数量:"))
# 初始化总分数
total_score = 0
# 循环获取每个学生的成绩并计算总分数
for i in range(n):
score = int(input("请输入第{}个学生的成绩:".format(i+1)))
total_score += score
# 计算平均分
average_score = total_score / n
# 输出平均分
print("这批学生的平均分为:", average_score)
```
运行代码,输入学生数量以及每个学生的成绩,即可得到这批学生的平均分。