Python: Exception Handling

Case #1

discount = 20

price = input("Enter price of the product: ")

try:
    calculated_price = float(price) - discount
except:
    calculated_price = 0

print(calculated_price)
Python

Run the script again and enter some string when it asks for the price-

Enter price of the product: abcdef
0
Python

Run the script and enter some decimal value when it asks for the price-

Enter price of the product: 33
13.0
Python

Case #2

If we know what type of exception might occur in certain cases, then we can define the except to handle that type of exception only.

Like, here we know that a ValueError might occur, so we have added a handler only for the ValueError-

discount = 20
calculated_price = 0

price = input("Enter price of the product: ")

try:
    if float(price) > discount:
        calculated_price = float(price) - discount
    else:
        calculated_price -= 1
except ValueError as err:
    calculated_price = 0
    print(err)

print(f'calculated price: {calculated_price}')
Python

If we use a number as input, then we get a result-

Enter price of the product: 99

calculated price: 79.0
Python

But, if we use some string, then we can see that the script was unable to convert that string to float-

Enter price of the product: kkk

could not convert string to float: 'kkk'

calculated price: 0
Python

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.