目前正在做一項大學作業,我們需要輸入并添加 3 個不同的分數。分數不得小于 0 或大于 10,并且只能是 0.5 的倍數。這是我遇到麻煩的后半部分。
如果輸入不是 0.5 的倍數,我如何告訴程式給出錯誤?
score1 = float(input("Please input the first score: ")
if score1 <0 or score1 >10:
score1 = float(input("Error! Scores can only be between 0 and 10.\n Please input Score 1 again: "))
elif score1
uj5u.com熱心網友回復:
一種方法是使用 while 回圈:
score1 = float(input("Please input the first score: ")
# while loop will keep asking for correct input if the input does not satisfy the requirements
while score1 <0 or score1 >10 or not (score1%0.5)== 0.0:
score1 = float(input("Error! Scores can only be between 0 and 10 and in multiples of 0.5.\n Please input Score 1 again: ")
print(score1, "passes all the tests")
或者,如果您愿意,您可以提出錯誤宣告:
score1 = float(input("score: "))
if score1<0 or score1>10 or not (score1%0.5)==0.0:
raise BaseException("Error! the input score1 must be between 1 and 10 and a multiple of 0.5")
print(score1, "passes all the tests")
uj5u.com熱心網友回復:
嵌套的 if 陳述句在這里發揮作用。首先它會檢查 condn 是否為 score>0 和 score<10 然后下一個檢查多個陳述句的 if 陳述句開始播放。使用回圈將輸入背靠背,直到不滿足條件。
score = float(input("Enter score"))
if score>0 and score<10:
if (score*10)%5 == 0:
print(" Score is a Multiple of 0.5")
else:
print("Score is Not multiple of 0.5")
else:
print("Error! Scores can only be between 0 and 10")
`
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/533039.html
