def checkGrade(raw):
''' (int) -> object (i.e., int OR str)
Assign grade from raw score
>>> checkGrade(74)
3
>>> checkGrade(82)
4
>>> checkGrade(-5)
'Error, raw score exceed min score'
>>> checkGrade(210)
'Error, raw score exceed max score'
'''
if raw>100:
score = "Error, raw score exceed max score"
elif raw>80:
score = 4.00
elif raw>70:
score = 3.00
elif raw>60:
score = 2.00
elif raw>50:
score = 1.00
elif raw>0:
score = 0
else:
score = "Error, raw score exceed min score"
return score
現在我想要做這樣的事情(在文檔字符串中):如何計算Python 2.7中以空格分隔的多個輸入?
def calGPA(n):
''' (str) -> float
Take all the raw scores, limited to 10 subjects, and
calculate GPA. Raw scores must be in range of 0 - 100.
>>> calGPA("77 45 77 55 87")
2.2
>>> calGPA("66 67 45 89")
2.0
>>> calGPA("87 91 84 89")
4.0
>>> calGPA("87 91 84 103")
'Error'
>>> calGPA("77 45 77 55 87 21 35 65 98 12 23 45")
'Error'
'''
原始標記輸入是用空格分隔的字符串。我如何使用checkGrade()
這個輸入函數來計算GPA?我試過這個:
map(int, s.split())
但它不起作用。
編輯追加新的要求
如果我想改變這一切投入到像calGPA("A B C D F")
代替calGPA("80 70 63 55 40")
字母,如果輸入包含任何除「A」,「B」,「 C「,」D「,」F「,如calGPA("A C B Z S")
,則輸出應爲」錯誤「。如果元素不是「A」,「B」,「C」,「D」,「F」之一,我應該怎麼做才能得到「錯誤」?
請格式化您的代碼,並給出比「不行」更好的錯誤說明。 – timgeb
使用'raws'作爲參數名稱而不是'raw'。然後,爲map(int,raws.split()):raw創建一個'for'循環:'。縮進代碼的其餘部分,使其位於'for'循環中。 – zondo
我不認爲在這種情況下使用'raw'作爲變量名是一個問題。 –