Several except blocks

Several except blocks

EasyException Handling Programs · 5 of 20

Write a Python function that handles TypeError and ZeroDivisionError separately.

Input
(8, 4), (8, 0), (8, "2")
Output
2.0
error: division by zero
error: cannot divide int by str

Approach

  1. One except block per error type.

Solution

Python
def divide(a, b):    try:        return a / b    except ZeroDivisionError:        return "error: division by zero"    except TypeError:        return f"error: cannot divide {type(a).__name__} by {type(b).__name__}" for a, b in [(8, 4), (8, 0), (8, "2")]:    print(divide(a, b))
Output
2.0
error: division by zero
error: cannot divide int by str

Learn the concept

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

More exception handling programs

← All 20 Exception Handling Programs

Catch several errors in one block

Catch several errors in one block

EasyException Handling Programs · 6 of 20

Write a Python program that catches ValueError and TypeError in one except block.

Input
"12", "x", None
Output
24
'x': ValueError
None: TypeError

Approach

  1. Use a tuple of exception types.

Solution

Python
for value in ["12", "x", None]:    try:        print(int(value) * 2)    except (ValueError, TypeError) as e:        print(f"{value!r}: {type(e).__name__}")
Output
24
'x': ValueError
None: TypeError

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