在Python中控制条件循环

时间:2016-02-02 03:12:36

标签: python list loops

我正在创建一个程序,询问学生人数,然后询问他们的名字。

例如:

Enter the test scores of the students:
> 4

当我对成绩使用相同的方法时,它不会起作用(所需的最终输出是成绩旁边的学生的名字)。我的第二个循环似乎不起作用。

期望的输出:

Enter the test scores of the students: 5
Bob
Tom
Obi
Eli
Brady (only lets me add 5 names)
Enter the test scores of the students:
100
99
78
90
87 (only lets me add 5 grades)
OUTPUT:
Bob 100
Tom 99
Obi 78
Eli 90
Brady 87

以下是我尝试的代码:

students = []
scores = []
count = 0
count2 = 0
number_of_students = int(input("Enetr the number of students: "))
while count != number_of_students:
                           new_student = input()
                           students.append(new_student)
                           count = count + 1
                           if count == number_of_students:
                               break

print("Enter the test scores of the students: ")
while count2 != count:
    new_score = input()
    scores.append(new_score)
    count2 = count2 + 1
    if count == number_of_students:
        break

我可以改变什么?

1 个答案:

答案 0 :(得分:1)

我认为这是一个你使问题比现在更困难的情况。你不需要在循环的时间和结束时检查结束条件 - 只需一次就可以了。你也不需要第二个循环的计数器,你可以从第一个循环中循环遍历名称:

students = []
scores = []
count = 0

number_of_students = int(input("Enter the number of students: "))

while count < number_of_students:
    new_student = input("Student name: ")
    students.append(new_student)
    count = count + 1

print("Enter the test scores of the students:")

for name in students:
    new_score = input("Score for " + name + ": ")
    scores.append(new_score)

但每当我看到这样的并行数组时,就会发出警报声,表示您需要更好的数据结构。也许是一组元组或字典。