2016-02-02 27 views
0

我正在創建一個程序,要求提供學生人數,然後詢問他們的姓名。在Python中控制條件循環

例:

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

我認爲這是一個讓問題比現在更困難的例子。您無需在循環結束時和循環結束時檢查結束條件 - 只需一次就可以。你也不必爲第二循環的計數器,你可以在名稱循環從第一循環:

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) 

但每當我看到平行陣列這樣,警報響起,說你需要一個更好的數據結構。也許是元組或字典的數組。