2017-10-10 104 views
0

我有這個代碼的問題,這個程序應該不斷讓您輸入學生,直到通過次數達到8或學生總數達到10個。然而,目前它只是不斷要求輸入,因此有一個無限循環。我該如何解決這個問題?python程序的無限循環

total_students=0 
student_passes=0 
student_failures=0 

while (total_students <= 10) or (student_passes != 8): 
     result=int(input("Input the exam result: ")) 
     if result>=50: 
      student_passes = student_passes + 1 
     else: 
      student_failures = student_failures + 1 
     total_students = total_students + 1 

print (student_passes) 
print (student_failures) 

if student_passes >= 8: 
    print ("Well done") 
+2

更改或to和? –

+0

但我只需要這些條件中的任何一個來結束循環。 –

+1

@AbdullahJadoon你需要_both_條件才能在循環中成爲_stay_。 – khelwood

回答

2

改變或與。雖然兩者都屬實,但您仍繼續:

total_students=0 
student_passes=0 
student_failures=0 

while (total_students != 10) and (student_passes != 8): # != or < 
     result=int(input("Input the exam result: ")) 
     if result>=50: 
      student_passes += 1 
     else: 
      student_failures += 1 
     total_students +=1 

print (student_passes) 
print (student_failures) 
+0

謝謝!爲什麼等到11個輸入,直到程序終止爲止?它應該是10. –

+1

@AbdullahJadoon我們可以改變爲!= 10,因爲我們正在增加價值。當它擊中10我們不想繼續。你的錯誤<= 10,這應該是<10 –

+0

輝煌非常感謝您的幫助。我在這裏的工作已經完成。 –

0

您可能需要重新訪問您的代碼。我不是Python專家,但我相信你應該修改while循環的條件。

如while(total_students < = 10)或(student_passes < = 8): 這將解決您的問題。

total_students=0 
student_passes=0 
student_failures=0 

while (total_students <= 10) or (student_passes <= 8): 
     result=int(input("Input the exam result: ")) 
     if result>=50: 
      student_passes = student_passes + 1 
     else: 
      student_failures = student_failures + 1 
     total_students = total_students + 1 

print (student_passes) 
print (student_failures) 

if student_passes >= 8: 
    print ("Well done") 
0

您應該使用,而不是,以滿足您的要求。

total_students=0 
student_passes=0 
student_failures=0 

while (total_students <= 10 and student_passes < 8): 
     result=int(input("Input the exam result: ")) 
     if result>=50: 
      student_passes = student_passes + 1 
     else: 
      student_failures = student_failures + 1 
     total_students = total_students + 1 

print (student_passes) 
print (student_failures) 

if student_passes >= 8: 
    print ("Well done")