Exceptions
When something goes wrong, Python raises an exception: an error that stops the program, unless you handle it.
int("hello") # ValueError: invalid literal for int() with base 10: 'hello'
10 / 0 # ZeroDivisionError: division by zero
try and except
Put risky code in try. If it raises, Python jumps to the matching except:
try:
age = int(input("Age: "))
print(f"Next year you will be {age + 1}")
except ValueError:
print("That was not a number.")
You can catch several kinds, and get the error itself with as:
except (ValueError, TypeError) as error:
print("Problem:", error)
Raising your own
When your function gets input it cannot work with, raise an exception with a clear message:
def set_speed(kmh):
if kmh < 0:
raise ValueError("Speed cannot be negative")
return kmh
Catch exceptions where you know how to recover (ask again, use a default). Do not hide them with a bare except: that swallows everything.
Your task
parse_quantity(text): convert tointand return it. If it is below 1,raise ValueError("Quantity must be at least 1"). (Text like"abc"already raisesValueErrorfromint.)safe_divide(a, b): returna / b, orNoneifbis zero.ask_quantity(): keep asking withinput("Quantity: ")untilparse_quantitysucceeds, then return the number. PrintTry againafter each bad answer.