1 回答

TA貢獻1804條經驗 獲得超3個贊
您可以在輸入上使用try/except來處理ValueError何時float()無法將值轉換為浮點數或OverflowError“如果參數超出 Python 浮點數范圍”。
loopCount = 0
while loopCount < 4:
try:
height = float(input("Please enter the height of the triangle: "))
break
except:
print("That is not a number.")
loopCount += 1
if loopCount == 4:
print("You failed to input valid values")
# return with an error or maybe abort with sys.exit(1)
else:
print("Great! I can now compute stuff.")
您可以一次檢查try塊內的所有輸入(如果您不關心哪一個特別無效或者您不需要向用戶指出它):
loopCount = 0
while loopCount < 4:
try:
base_1 = float(input("Please enter the base length of the trapezoid: "))
base_2 = float(input("Please enter the second base length of the trapezoid: "))
height = float(input("Please enter the height of the trapezoid: "))
break
except:
print("One of the inputs is not a number.")
loopCount += 1
if loopCount == 4:
print("You failed to input valid values")
# return with an error or maybe abort with sys.exit(1)
else:
print("Great! I can now compute stuff.")
為了避免大量重復try-except,我建議創建一個獲取浮點輸入(或所有輸入)的方法,然后從您的主方法中調用它。
添加回答
舉報