如何修改if/else块以按预期捕获异常


flag = 'y'
while flag == 'y':
try:
item_price = float(input('Enter item price: '))
item_quantity = float(input('Enter the item quantity: '))
if item_price > 0 and item_quantity > 0:
sub_total = item_quantity * item_price
total = sub_total + sub_total * 0.0825
print(f'Subtotal is ${sub_total}')
print(f'Total is ${round(total,2)}')
else:
print('Error: Enter a positive number for item price and quantity.')
except ValueError:
print('Error: Please enter a number!')
flag = input('Do you want to continue (y/n)?n')

在这种情况下,我可以输入负项目价格,只有在输入数量后,才会显示Error: Enter a positive number for item price and quantity.。如果商品价格为负数,如何显示此错误?

所以问题是在哪里检查数字是否为负

try:
item_price = float(input('Enter item price: '))
if item_price > 0: # Notice where this if is placed.
item_quantity = float(input('Enter the item quantity: '))
if item_quantity > 0:
sub_total = item_quantity * item_price
total = sub_total + sub_total * 0.0825
print(f'Subtotal is ${sub_total}')
print(f'Total is ${round(total,2)}')
else:
print('Error: Enter a positive number for item price and quantity.')
else:
print('Error: Enter a positive number for item price and quantity.')

如果你把If语句拆分,你可以在它要求数量之前检查一个正价格

如果你想使用异常,你可以为每种情况引发不同的ValueErrors,然后使用字符串方法来区分它们,并决定打印给调用者的错误类型:

try:
item = float(input('price:'))
if item <= 0:
raise ValueError('Error: Enter a positive number')
#here handle the different possible exception strings individually:
except ValueError as e:
if (str(e).startswith('Error')):
print(str(e))
else:   #the built-in would be 'cannot convert str to float'
print('Error: please enter a number')

这会起作用。

class CustomValueError(ValueError):
def __init__(self, arg):
self.strerror = arg
self.args = {arg}
flag = 'y'
while flag == 'y':
try:
item_price = float(input('Enter item price: '))
if item_price > 0:
item_quantity = float(input('Enter the item quantity: '))
if item_quantity > 0:
sub_total = item_quantity * item_price
total = sub_total + sub_total * 0.0825
print(f'Subtotal is ${sub_total}')
print(f'Total is ${round(total,2)}')
else:
try:
raise CustomValueError("Error: Enter a positive number for item price and quantity.")
else:
try:
raise CustomValueError("Error: Enter a positive number for item price and quantity.")
except ValueError:
print('Error: Please enter a number!')
flag = input('Do you want to continue (y/n)?n')

最新更新