Use the else block

Use the else block

EasyException Handling Programs · 7 of 20

Write a Python program that uses else to run code only when no exception occurred.

Input
"25", "x"
Output
25 squared is 625
x is not a number

Approach

  1. else runs after try only if nothing was raised.

Solution

Python
for text in ["25", "x"]:    try:        n = int(text)    except ValueError:        print(text, "is not a number")    else:        print(text, "squared is", n * n)
Output
25 squared is 625
x is not a number

Line by line

Lines 6-7

Keeping the follow-up work in else means a bug there is not hidden by the except.

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Use the finally block

Use the finally block

EasyException Handling Programs · 8 of 20

Write a Python program that shows finally always runs.

Output
  result: 25.0
  clean-up done
  error handled
  clean-up done

Approach

  1. Run the function once successfully and once with an error.

Solution

Python
def process(value):    try:        print("  result:", 100 / value)    except ZeroDivisionError:        print("  error handled")    finally:        print("  clean-up done") process(4)process(0)
Output
  result: 25.0
  clean-up done
  error handled
  clean-up done

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Handle a missing dictionary key

Handle a missing dictionary key

EasyException Handling Programs · 3 of 20

Write a Python program that reads a key from a dictionary and handles a missing key.

Output
missing key: 'timeout'
30

Approach

  1. Catch KeyError; compare with dict.get().

Solution

Python
config = {"browser": "chromium"}try:    print(config["timeout"])except KeyError as e:    print("missing key:", e)print(config.get("timeout", 30))
Output
missing key: 'timeout'
30

Line by line

Line 6

get with a default avoids the exception entirely when a default makes sense.

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Handle division by zero

Handle division by zero

EasyException Handling Programs · 1 of 20

Write a Python program that divides two numbers and prints a friendly message when the divisor is 0.

Input
(10, 2), (5, 0)
Output
5.0 | cannot divide by zero

Approach

  1. Put the division in try and catch ZeroDivisionError.

Solution

Python
def safe_divide(a, b):    try:        return a / b    except ZeroDivisionError:        return "cannot divide by zero" print(safe_divide(10, 2), "|", safe_divide(5, 0))
Output
5.0 | cannot divide by zero

Line by line

Lines 2-5

Only the division is inside try; the specific exception is caught, so other bugs still show up.

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Handle invalid integer input

Handle invalid integer input

EasyException Handling Programs · 2 of 20

Write a Python program that converts text to an integer and reports invalid values.

Input
"42", "4.2", "abc"
Output
42 -> 42
4.2 -> invalid: invalid literal for int() with base 10: '4.2'
abc -> invalid: invalid literal for int() with base 10: 'abc'

Approach

  1. int() raises ValueError for text that is not a whole number.

Solution

Python
for text in ["42", "4.2", "abc"]:    try:        print(text, "->", int(text))    except ValueError as e:        print(text, "-> invalid:", e)
Output
42 -> 42
4.2 -> invalid: invalid literal for int() with base 10: '4.2'
abc -> invalid: invalid literal for int() with base 10: 'abc'

Line by line

Line 4

as e gives access to the message Python created.

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Handle an index out of range

Handle an index out of range

EasyException Handling Programs · 4 of 20

Write a Python program that reads a list item by index and handles invalid indexes.

Input
index 1 and 10 of ["a", "b", "c"]
Output
1 b
10 is out of range for 3 items

Approach

  1. Catch IndexError.

Solution

Python
items = ["a", "b", "c"]for i in [1, 10]:    try:        print(i, items[i])    except IndexError:        print(i, "is out of range for", len(items), "items")
Output
1 b
10 is out of range for 3 items

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Platform information

Platform information

EasyOS Module Programs · 49 of 49

Write a Python program to print platform details.

Output
OS: Windows
Architecture bits: 64bit
Python implementation: CPython

Approach

  1. The platform module.

Solution

Python
import platform print("OS:", platform.system())print("Architecture bits:", platform.architecture()[0])print("Python implementation:", platform.python_implementation())
Output
OS: Windows
Architecture bits: 64bit
Python implementation: CPython

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

File details with os.stat()

File details with os.stat()

EasyOS Module Programs · 48 of 49

Write a Python program to show the details of a file with os.stat().

Output
size: 5
is regular file: True
has mtime: True

Approach

  1. stat() returns size, timestamps and mode.

Solution

Python
import osimport stat with open("info.txt", "w") as f:    f.write("hello")st = os.stat("info.txt")print("size:", st.st_size)print("is regular file:", stat.S_ISREG(st.st_mode))print("has mtime:", st.st_mtime > 0)
Output
size: 5
is regular file: True
has mtime: True

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Does a path exist?

Does a path exist?

EasyOS Module Programs · 46 of 49

Write a Python program to check whether a path exists.

Output
here.txt True
. True
nowhere False

Approach

  1. os.path.exists works for files and folders.

Solution

Python
import os open("here.txt", "w").close()for p in ["here.txt", ".", "nowhere"]:    print(p, os.path.exists(p))
Output
here.txt True
. True
nowhere False

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Is a path a symbolic link?

Is a path a symbolic link?

EasyOS Module Programs · 47 of 49

Write a Python program to check whether a path is a symbolic link.

Output
Creating symlinks needs extra permission here
target.txt is a link: False

Approach

  1. os.path.islink; creating links may need extra rights on Windows, so handle the error.

Solution

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs