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,我建议创建一个获取浮点输入(或所有输入)的方法,然后从您的主方法中调用它。
添加回答
举报