Fibonacci generator

Fibonacci generator

EasyIterator & Generator Programs · 5 of 20

Write a generator that yields Fibonacci numbers, and take the first 10.

Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Approach

  1. An infinite generator plus itertools.islice.

Solution

Python
from itertools import islice def fibonacci():    a, b = 0, 1    while True:        yield a        a, b = b, a + b print(list(islice(fibonacci(), 10)))
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Line by line

Line 9

islice takes the first 10 values from an endless generator.

Learn the concept

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

More iterator & generator programs

← All 20 Iterator & Generator Programs

Countdown generator

Countdown generator

EasyIterator & Generator Programs · 3 of 20

Write a generator that counts down from n to 1.

Output
[5, 4, 3, 2, 1]

Approach

  1. yield inside a while loop.

Solution

Python
def countdown(n):    while n > 0:        yield n        n -= 1 print(list(countdown(5)))
Output
[5, 4, 3, 2, 1]

Learn the concept

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

More iterator & generator programs

← All 20 Iterator & Generator Programs

Even numbers generator

Even numbers generator

EasyIterator & Generator Programs · 4 of 20

Write a generator that yields even numbers up to a limit.

Output
[0, 2, 4, 6, 8, 10, 12]

Approach

  1. Loop with a step of 2 and yield each value.

Solution

Python
def evens(limit):    for n in range(0, limit + 1, 2):        yield n print(list(evens(12)))
Output
[0, 2, 4, 6, 8, 10, 12]

Learn the concept

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

More iterator & generator programs

← All 20 Iterator & Generator Programs

A for loop by hand

A for loop by hand

EasyIterator & Generator Programs · 2 of 20

Write a Python program that rebuilds a for loop using while, iter() and next().

Output
10
20
30

Approach

  1. Call next() until StopIteration.

Solution

Python
items = [10, 20, 30]it = iter(items)while True:    try:        value = next(it)    except StopIteration:        break    print(value)
Output
10
20
30

Learn the concept

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

More iterator & generator programs

← All 20 Iterator & Generator Programs

Use iter() and next()

Use iter() and next()

EasyIterator & Generator Programs · 1 of 20

Write a Python program that walks through a list with iter() and next().

Output
login
search
logout
no more steps

Approach

  1. next() returns items one by one; a default avoids StopIteration.

Solution

Python
it = iter(["login", "search", "logout"])print(next(it))print(next(it))print(next(it))print(next(it, "no more steps"))
Output
login
search
logout
no more steps

Learn the concept

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

More iterator & generator programs

← All 20 Iterator & Generator Programs

Python Exception Handling Programs with Solutions

Python Practice › Exception Handling Programs

Python Exception Handling Programs with Solutions

20 programs16 easy4 medium0 hard

20 exception handling programs: catching specific errors, else and finally, raising and re-raising, custom exceptions, retries and safe input parsing. Each solution runs both the success path and the failure path so you can see every branch.

Before you start

Read the Exception Handling lesson first if the topic is new to you.

All programs

Exception hierarchy order

Exception hierarchy order

EasyException Handling Programs · 20 of 20

Write a Python program showing why specific exceptions must be caught before general ones.

Output
True True
specific handler: file not found

Approach

  1. FileNotFoundError is a subclass of OSError, so it must come first.

Solution

Python
print(issubclass(FileNotFoundError, OSError), issubclass(OSError, Exception))try:    open("nope.txt")except FileNotFoundError:    print("specific handler: file not found")except OSError:    print("general handler: some OS error")
Output
True True
specific handler: file not found

Line by line

Line 1

Python checks except blocks top to bottom and uses the first that matches, so a general OSError first would hide the specific one.

Learn the concept

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

More exception handling programs

← All 20 Exception Handling Programs

Clean-up with a context manager

Clean-up with a context manager

EasyException Handling Programs · 18 of 20

Write a Python program showing that a with block closes a file even when an error happens inside it.

Output
caught: something failed
file closed: True

Approach

  1. Raise inside the with and check f.closed afterwards.

Solution

Python
try:    with open("demo.txt", "w") as f:        f.write("data")        raise RuntimeError("something failed")except RuntimeError as e:    print("caught:", e)print("file closed:", f.closed)
Output
caught: something failed
file closed: True

Learn the concept

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

More exception handling programs

← All 20 Exception Handling Programs

Collect several errors

Collect several errors

MediumException Handling Programs · 19 of 20

Write a Python program that validates several fields and reports every error at once.

Output
valid
3 errors: name is required; email is invalid; age must be 18-120

Approach

  1. Collect messages in a list and raise one exception at the end.

Solution

Python
class ValidationError(Exception):    def __init__(self, errors):        super().__init__("; ".join(errors))        self.errors = errors def validate(user):    errors = []    if not user.get("name"):        errors.append("name is required")    if "@" not in user.get("email", ""):        errors.append("email is invalid")    if not 18 <= user.get("age", 0) <= 120:        errors.append("age must be 18-120")    if errors:        raise ValidationError(errors)    return "valid" for user in [{"name": "Asha", "email": "asha@x.com", "age": 29}, {"name": "", "email": "bad", "age": 5}]:    try:        print(validate(user))    except ValidationError as e:        print(len(e.errors), "errors:", e)
Output
valid
3 errors: name is required; email is invalid; age must be 18-120

Line by line

Lines 7-14

Every check runs, so the user sees all problems at once instead of one at a time.

Learn the concept

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

More exception handling programs

← All 20 Exception Handling Programs

Print exception details

Print exception details

EasyException Handling Programs · 17 of 20

Write a Python program that prints the type, message and line of a caught exception.

Output
type: IndexError
message: list index out of range
line: 3

Approach

  1. type(e).__name__, str(e) and the traceback object.

Solution

Python
try:    numbers = [1, 2, 3]    numbers[5]except IndexError as e:    tb = e.__traceback__    print("type:", type(e).__name__)    print("message:", e)    print("line:", tb.tb_lineno)
Output
type: IndexError
message: list index out of range
line: 3

Line by line

Line 5

__traceback__ holds where the error happened; tb_lineno is the line number.

Learn the concept

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

More exception handling programs

← All 20 Exception Handling Programs