Search⌘ K
AI Features

Challenge: Safe Division

Explore how to use try and except blocks in Python to handle errors during division. Learn to ask for user input, perform safe division, and display results or friendly error messages. This lesson helps you write programs that continue running smoothly even when unexpected input causes errors.

We'll cover the following...

Sometimes programs crash when something unexpected happens, for example:

  • dividing by zero

  • typing letters instead of numbers

Python gives us a way to try running code, and handle errors if something goes wrong.

This is done using a try / except block.

Your task:

  1. Ask the user for two numbers

  2. Try to divide the first number by the second

  3. If the division works, print the result

  4. If any error happens, print a friendly message instead of crashing

💡 How this works:

  • Code inside try is run normally

  • If an error happens, Python jumps to except

  • The program continues instead of stopping

You don’t need to handle specific errors yet, one general error message is enough.

When you click Run:

  • Entering valid numbers should show the result

  • Entering something invalid should show your friendly message

# Write your code here.
Safely dividing two numbers and handling division by zero and invalid input