Python bootcamp · Lab 23

Safe division

mediumTry Except12 minLesson: Try Except

Read the question, write Python on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read two integers a and b (one per line). Print the integer division a // b.

If b is 0, division is impossible — catch the error and print the word error instead of letting the program crash.

Input. Two lines, each one integer.

Output. The integer quotient, or error.

Examples

Example 1 — Integer division floors the result.
Input
17
5
Output
3
Example 2 — Dividing by zero is caught, not crashed.
Input
4
0
Output
error
Hint
  1. Wrap the division in try: and catch ZeroDivisionError.
  2. Prefer catching the specific error over a bare except — you only want to handle the divide-by-zero case.
Show correct code

Peek only after you have tried. You can still Check your own version.

a = int(input())
b = int(input())
try:
    print(a // b)
except ZeroDivisionError:
    print("error")
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.