[英]Python Input Validation with multiple variables…simplified?
首先,我搜索了很多該站點,並找到了有關該主題的其他帖子,甚至是我正在從事的相同任務,因此代碼非常相似...但是,有些地方略有不同。 我正在使用“從Python入門,第4版”上這門課,而我的作業來自第5章“ 15.測試平均值和等級”。 我已經為除輸入驗證之外的所有內容編寫了代碼,我的講師堅稱我們將使用該代碼,盡管我們僅應使用本書已涵蓋的編碼技術:到目前為止,沒有列表,元組,字典,lambda等。 ,這使得我在網上(和在本網站上)發現的大多數用於輸入驗證的示例都沒有用,因為我無法弄清楚它們,如果願意的話也無法使用它們。 我已經聯系指導老師尋求幫助(在線課程),但是已經有數周沒有收到任何回復,所以我在這里。 該程序應要求用戶輸入5個測試分數,找到分數的平均值,為每個分數指定字母等級,然后顯示帶有字母等級的分數以及平均值。 我以為如果使用“ for ranges in range(1,6)”循環詢問分數,那么驗證輸入會更容易,但是我不知道如何訪問用戶輸入的每個分數以發送到define_grade函數,然后再顯示在main中(我在下面沒有包含任何代碼)...因此,我最終為每個分數制作了一個變量,但隨后遇到了如何驗證輸入的問題(確保輸入的分數不小於0或大於100,或者確保用戶輸入了每個變量的數字而不是字母。 我希望能夠在代碼中編寫一些異常處理,這樣,如果用戶輸入字母而不是數字,則不會引發異常,因為我的講師說:“這是我從現在開始嘗試的工作。導致您的程序崩潰”,盡管他還沒有確切地告訴我如何實現這種輸入驗證。 任何幫助都將不勝感激,我已經為此苦苦掙扎了好幾天,這正使我感到非常壓力。
編輯:TypeError:input_validation()缺少4個必需的位置參數:'score2','score3','score4'和'score5'是我得到的錯誤,我知道我做錯了,但是,我不知道不知道是什么...我覺得有一個更簡單的方法來處理多個變量的輸入驗證。.由於我還很陌生,所以我不知道如何實現它。
def get_scores():
score1 = input_validation(float(input('Enter the score for the first test: ')))
score2 = input_validation(float(input('Enter the score for the second test: ')))
score3 = input_validation(float(input('Enter the score for the third test: ')))
score4 = input_validation(float(input('Enter the score for the fourth test: ')))
score5 = input_validation(float(input('Enter the score for the fifth test: ')))
return score1, score2, score3, score4, score5
def input_validation(score1, score2, score3, score4, score5):
while (score1, score2, score3, score4, score5) < 0 or (score1, score2, score3, score4, score5) > 100:
print('Score cannot be less than 0 or greater than 100!')
(score1, score2, score3, score4, score5) = float(input('Please enter a correct test score: '))
return score1, score2, score3, score4, score5
您的直接錯誤是您已定義input_validation()
接受五個參數,但是在調用它時僅將其傳遞給一個參數。
收集一個功能中的輸入並驗證另一個功能中的輸入是很尷尬的,因為必須非常緊密地協調這些功能,才能在出現錯誤輸入時重新提示。
一次要求幾個分數然后一次驗證所有分數也是很尷尬的,因為如果有些分數有效而有些分數無效,您會怎么做? 您必須再次要求所有分數,這浪費了用戶的時間,或者您需要一種僅提示無效分數的方法,這是不必要的復雜性。
一次只處理一個分數,將所有輸入和驗證都放在一個位置可能是一個更好的設計:
def input_validation(prompt):
# keep looping until they enter a good score
while True:
# get the answer as a string
answer = input(prompt)
try:
# convert to float
score = float(answer)
# if in range, we're done! return the converted score number
if 0 <= score <= 100:
return score
# otherwise out of range, print an error message and keep looping
else:
print('Score cannot be less than 0 or greater than 100!')
# if the answer wasn't a number, print an error message and keep looping
except ValueError:
print ('That is not a test score.')
然后您可以這樣稱呼它:
score1 = input_validation('Enter the score for the first test: ')
score2 = input_validation('Enter the score for the second test: ')
如果要將分數保留在列表中,而不要使用五個單獨的變量:
scores = []
for i in range(5):
scores.append(input_validation('Enter the score for test number %d: ' % i+1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.