Python 有没有办法为每个输入添加ValueError?
所以我试着写一个代码,输入一个矩形的宽度和高度,它给你面积和周长,现在很明显,输入只能是数字,所以如果当前输入不是数字,我希望能够请求另一个输入。(告诉用户只输入数字)。问题是,如果第一个输入(宽度)是数字,而只有第二个输入(高度)不是数字,我不希望程序要求用户再次输入宽度,我只希望用户再次输入高度而不是宽度,因为宽度已经作为数字输入。我该怎么做Python 有没有办法为每个输入添加ValueError?,python,python-3.x,valueerror,except,Python,Python 3.x,Valueerror,Except,所以我试着写一个代码,输入一个矩形的宽度和高度,它给你面积和周长,现在很明显,输入只能是数字,所以如果当前输入不是数字,我希望能够请求另一个输入。(告诉用户只输入数字)。问题是,如果第一个输入(宽度)是数字,而只有第二个输入(高度)不是数字,我不希望程序要求用户再次输入宽度,我只希望用户再次输入高度而不是宽度,因为宽度已经作为数字输入。我该怎么做 while True: try: a = float(input("Please enter width :")) b = float
while True:
try:
a = float(input("Please enter width :"))
b = float(input("Please enter height :"))
except ValueError:
print("PLease only enter numbers ")
continue
area = float(a*b)
perimeter = float((a+b)*2)
print('The area of the rectangle is {} and the perimeter of the rectangle is {} '.format(area, perimeter))
基本的解决方法是将每个对
float
的调用包装在一个单独的try
中,并分别处理它们。不过,逐字逐句写出两个try
s会显得凌乱而笨重
相反,我会将try
移动到它自己的函数中,然后调用该函数两次:
# Let this function handle the bad-input looping
def ask_for_float(message):
while True:
try:
return float(input(message))
except ValueError:
print("Please only enter numbers ")
a = ask_for_float("Please enter width :")
b = ask_for_float("Please enter height :")
在单独的try块中写入输入,然后可以单独捕获错误。 比如说,
try:
a = float(input("Please enter width :"))
except ValueError:
print("PLease only enter numbers ")
try:
b = float(input("Please enter height :"))
except ValueError:
print("PLease only enter numbers ")
continue
area = float(a*b)
perimeter = float((a+b)*2)