Try Else Block in Python

Level 394 keystrokes

This uses try-except-else where the else block runs only if no exception occurs.

Python code

# try runs code that could raise an exception
1try:
# 10 / 2 succeeds, so result is 5.0 (/ always gives a float)
2 result = 10 / 2
# Would run only if the division raised ZeroDivisionError
3except ZeroDivisionError:
4 print("Error")
# else runs only when the try block raised no exception
5else:
# Prints "Result: 5.0"
6 print(f"Result: {result}")

Output

Result: 5.0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • :× 4
  • "× 4
  • (× 2
  • )× 2
  • {× 1
  • }× 1
  • /× 1
  • =× 1

More Python examples at level 3

← Python typing practice