Try-Except 块 - 我这样做是否正确?
Try-Except block - Did I do this correctly?
我们正在学习异常处理。我这样做正确吗? 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
这里你体验的就是所谓的,WET代码Write Everything Twice,我们尝试写DRY代码,即Don't重复自己。
在你的情况下,你应该做的是创建一个名为 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: ')
...
我们正在学习异常处理。我这样做正确吗? 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
这里你体验的就是所谓的,WET代码Write Everything Twice,我们尝试写DRY代码,即Don't重复自己。
在你的情况下,你应该做的是创建一个名为 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: ')
...