Home › Python with Chai › Lesson 9

try-except: explain, don't crash

Python with Chai, lesson 9 of 20. A short Hinglish video, simple English notes and code you can run, free.

Open the interactive lesson with Run button

The idea

If the customer types "teen" instead of a number, int() raises a ValueError and the program crashes.

Put the risky code inside try. If an error happens, except catches it.

The program keeps running and politely tells the user what went wrong.

The code

try:
    cups = int(input("Kitne cup? "))
    print("Bill:", cups * 20)
except ValueError:
    print("Number likho!")

Output:

Kitne cup? teen
Number likho!

Try it yourself

Remember

try-except: explain the problem instead of crashing.

← input: ask the customer · while True: keep the shop open →

All lessons: Python with Chai