Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何修改if/else块以按预期捕获异常?_Python_Exception - Fatal编程技术网

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

Python 如何修改if/else块以按预期捕获异常?,python,exception,Python,Exception,在这种情况下,我可以输入负项目价格,只有在输入数量后,才会显示错误:为项目价格和数量输入正数。。如果商品价格为负数,如何显示此错误?因此问题在于检查数字是否为负数 flag = 'y' while flag == 'y': try: item_price = float(input('Enter item price: ')) item_quantity = float(input('Enter the item quantity: '))

在这种情况下,我可以输入负项目价格,只有在输入数量后,才会显示
错误:为项目价格和数量输入正数。
。如果商品价格为负数,如何显示此错误?

因此问题在于检查数字是否为负数

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')

如果将If语句拆分,您可以在它要求数量之前检查正价格

,因此问题在于检查数字是否为负

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')
如果将If语句拆分,则可以在它要求数量之前检查正价格

这将起作用

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.')
这会奏效的

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.')

如果要使用异常,可以针对每种情况引发不同的ValueErrors,然后使用string方法区分它们,并决定向调用方打印哪种类型的错误:

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')
试试看:
项目=浮动(输入('价格:'))

如果item如果要使用异常,可以针对每种情况提出不同的ValueErrors,然后使用string方法区分它们,并决定向调用方打印哪种类型的错误:

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')
试试看:
项目=浮动(输入('价格:'))

如果项目如果我为项目输入了正确的价格,为数量输入了错误的数字,它将重新启动while循环以再次输入价格。在输入正确的价格后,我如何要求它只更正数量?这是一个单独的问题,但您需要重新构造代码。您可以简单地在try函数中添加另一个循环来检查数量,但这将使代码比现在更混乱。此时,您需要进行一些重新设计,以使代码更加高效。您可能想在软件交换网站上询问。如果我为项目输入了正确的价格,为数量输入了错误的数字,则会重新启动while循环以再次输入价格。在输入正确的价格后,我如何要求它只更正数量?这是一个单独的问题,但您需要重新构造代码。您可以简单地在try函数中添加另一个循环来检查数量,但这将使代码比现在更混乱。此时,您需要进行一些重新设计,以使代码更加高效。您可能想在软件交换网站上提问。这是否回答了您的问题?这回答了你的问题吗?