我们正在学习异常处理。我做得对吗? ValueError是用于捕获键入的字符串而不是数字的正确异常吗?我尝试使用TypeError,但是没有捕获到异常。
还有,在我的四个输入中是否有更有效的方法来捕获每个异常?什么是最佳做法?
#Ask user for ranges. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input.
while True:
try:
rangeLower = float(input("Enter your Lower range: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
while True:
try:
rangeHigher = float(input("Enter your Higher range: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
#Ask user for numbers. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input.
while True:
try:
num1 = float(input("Enter your First number: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
while True:
try:
num2 = float(input("Enter your Second number: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
答案 0 :(得分:4)
在这里,您遇到了称为 WET 的代码两次编写所有内容,我们尝试编写 DRY 代码,即不要重复自己。
在这种情况下,您应该做的是创建一个名为float_input
的函数,就像使用try
except
块并为每个变量赋值调用一样。
def float_input(msg):
while True:
try:
return float(input(msg))
except ValueError:
pass
range_lower = float_input('Enter your lower range: ')
...