3 回答

TA貢獻1895條經驗 獲得超3個贊
當您處理此類事情(無論是作業還是生產代碼)時,最好測試每個單獨的函數以確保它們正常工作。例如,嘗試find_perfect
使用不同的(硬編碼的)列表運行;你會發現它每次都能得到正確的答案。現在嘗試測試get_test_scores
并打印輸出。哎呀!
您的問題是您僅附加最后的測試分數。該線tests.append(test_score)
應該位于for
循環內部。

TA貢獻1839條經驗 獲得超15個贊
你tests.append(test_score)會發生一次,因為它在 for 循環之外,試試這個:
def get_test_scores():
tests = []
for i in range(SIZE):
test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))
while (test_score <0) or (test_score >100):
print("ERROR!")
test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))
tests.append(test_score)
return tests
順便說一句,我認為值得快速計算你有多少個 100 并且不再迭代,在 python 中,你可以從像 tuple 這樣的函數返回很少的值,例如:
def get_test_scores():
tests = []
count = 0
for i in range(SIZE):
test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))
while (test_score <0) or (test_score >100):
print("ERROR!")
test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))
if test_score == 100:
count += 1
tests.append(test_score)
return count, tests
用法 :
count, scores = get_test_scores()
count 是一個數字,scores 是分數列表
添加回答
舉報