[英]Printing min and max function from input of a list
每次運行代碼時,都會收到“ TypeError:'int'對象不可迭代”的信息。
所以我的問題是:如何最后打印/使用min和max函數? 因此,如果有人說類型5、7、10和-1。 如何讓用戶知道最高分數是10,最低分數是5? (然后我猜測是按從高到低的順序組織)。
def fillList():
myList = []
return myList
studentNumber = 0
myList = []
testScore = int(input ("Please enter a test score "))
while testScore > -1:
# myList = fillList()
myList.append (testScore)
studentNumber += 1
testScore = int(input ("Please enter a test score "))
print ("")
print ("{:s} {:<5d}".format("Number of students", studentNumber))
print ("")
print ("{:s} ".format("Highest Score"))
print ("")
high = max(testScore)
print ("Lowest score")
print ("")
print ("Average score")
print ("")
print ("Scores, from highest to lowest")
print ("")
您的問題是testScore
是一個整數。 還有什么呢? 每次瀏覽列表時,都將其重新分配給下一個整數。
例如,如果您想將它們附加到列表中,則必須執行以下操作:
testScores = []
while testScore > -1:
testScores.append(testScore)
# rest of your code
現在很容易:
high = max(testScores)
而且,實際上,您是在代碼的編輯版本中執行此操作的: myList
包含所有testScore
值。 因此,只需使用它:
high = max(myList)
但是,實際上,如果考慮到這一點,就可以輕松保持“運行最大值”:
high = testScore
while testScore > -1:
if testScore > high:
high = testScore
# rest of your code
在用戶從不輸入任何測試分數的情況下,您會得到不同的行為(第一個分數會TypeError
有關詢問最大空列表的TypeError
,第二個分數將為-1),但是其中一個很容易一旦決定了您真正想要發生的事情,就進行更改。
如果您的所有分數都在一個數組中。
print("The max was: ",max(array))
print("The min was: ",min(array))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.