在python中,循环输入学生的信息,以及对应的三科成绩,且三科成绩需分别输入,当输入的格式不正确时,仅要求重新输入当前出现错误的成绩,而不从学生信息开始重新输入,如何实现
时间: 2024-05-02 08:23:09 浏览: 23
你可以使用`while`循环来实现这个需求。以下是一个示例代码:
```python
students = []
while True:
name = input("请输入学生姓名:")
score1_input = True
score2_input = True
score3_input = True
while score1_input:
score1 = input("请输入第一门成绩:")
try:
score1 = float(score1)
score1_input = False
except ValueError:
print("成绩格式错误,请重新输入第一门成绩。")
while score2_input:
score2 = input("请输入第二门成绩:")
try:
score2 = float(score2)
score2_input = False
except ValueError:
print("成绩格式错误,请重新输入第二门成绩。")
while score3_input:
score3 = input("请输入第三门成绩:")
try:
score3 = float(score3)
score3_input = False
except ValueError:
print("成绩格式错误,请重新输入第三门成绩。")
student = {"name": name, "score1": score1, "score2": score2, "score3": score3}
students.append(student)
continue_input = input("是否继续录入?(Y/N)").upper()
if continue_input != "Y":
break
print(students)
```
在这个示例代码中,我们首先定义了一个空的列表`students`,用于存储所有输入的学生信息。然后使用`while`循环不断进行学生信息的输入。对于每个学生,我们先输入姓名,然后分别输入三门成绩。对于每门成绩,我们使用一个`while`循环来实现格式的检查和错误提示。只有当输入的成绩格式正确时,循环才会结束,否则会一直提示重新输入。当所有信息都输入完成后,我们把这个学生的信息存储到`students`列表中。最后,询问用户是否继续录入,如果选择不继续,则跳出循环并输出`students`列表。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![](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)
![](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)
![](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)