# 14 Python Exercises for Intermediate with Solutions

So you learned the basics of Python and moved a little beyond basics. Now to test and brush up your skills you need to do some exercises. In this article, we will explore various exercises to enhance your intermediate Python knowledge with some practice exercises questions, and answers with solutions.

In this article, I will share several intermediate Python programming exercises and their answer codes. First try to solve each problem independently. If you face difficulty to solve those on your own, then only refer to the provided code. You can also try different methods to solve the same problem.

## 1. String Manipulation

Question: Create a function to reverse a given string.

```# Reverse string in Python
def reverse_string(input_str):
return input_str[::-1]
# Test the function
print(reverse_string("Python"))  # Output: "nohtyP"
```

Here in this code, we used slicing (`[::-1]`) method of Python to reverse the input string. We just made a function (reverse_string)out of that. This exercise helps you understand string manipulation techniques. This kind of function can be useful in scenarios where string reversal is required, such as creating a palindrome or deciphering encoded messages.

## 2. List Operations

Question: Write a function to remove duplicate elements from a list.

```# Python code to remove duplicate elements from string
def remove_duplicates(input_list):
return list(set(input_list))
# Test the function
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))  # Output: [1, 2, 3, 4, 5]
```

To remove duplicates, we can use set function of Python. `set()` function in Python can automatically remove duplicates due to its unique property. Then, the set is converted back to a list. This kind of technique can be useful for data cleaning and ensuring unique values while doing some data analysis tasks.

## 3. Dictionary Handling

Question: In this intermediate Python exercises, create a program that merges two dictionaries.

```# Merge two dictioaries in python
def merge_dicts(dict1, dict2):
return {**dict1, **dict2}
# Test the function
dict_a = {'a': 1, 'b': 2}
dict_b = {'b': 3, 'c': 4}
print(merge_dicts(dict_a, dict_b))  # Output: {'a': 1, 'b': 3, 'c': 4}
```

The `merge_dicts` function uses the `**` unpacking operator to combine two dictionaries into a new one. It merges the key-value pairs of both dictionaries. The result is a new dictionary that contains all the key-value pairs from both `dict1` and `dict2`.

## 4. File Handling

Question: In this exercises, write an intermediate Python script to read content from a text file and count the occurrences of each word.

```# Count ocurrence of each word in python
def count_word_occurrences(file_path):
word_count = {}
with open(file_path, 'r') as file:
for word in words:
word_count[word] = word_count.get(word, 0) + 1
return word_count
# Create a sample text file with some content
with open('sample_text.txt', 'w') as file:
file.write("This is a sample text. It contains some words for testing.nPython intermediate exercises. Python is awesome")
# Test the function
print(count_word_occurrences('sample_text.txt'))
```
``````Output:
{'This': 1, 'is': 2, 'a': 1, 'sample': 1, 'text.': 1, 'It': 1, 'contains': 1, 'some': 1, 'words': 1, 'for': 1, 'testing.': 1, 'Python': 2, 'intermediate': 1, 'exercises.': 1, 'awesome': 1}``````

The `count_word_occurrences` function opens a text file, reads its content, and splits it into words. The splitting method I used is by space (the default one). You can try different splitting methods as per your needs (like: by dot, by comma, etc.).

After splitting, we count the occurrences of each word using a dictionary. The `get` method is used to handle the initial count for each word. This exercise illustrates basic file handling and word counting.

If you are working with text files, especially for doing text analysis or natural language processing, this kind of situation you may need to perform very often. One very popular example of this exercise is Term Frequency-Inverse Document Frequency in short TF-IDF.

## 5. Error Handling

Question: Develop a function that handles division by zero.

```# # Python intermediate exercises : Divide any number by zero
def safe_divide(num1, num2):
try:
result = num1 / num2
return result
except ZeroDivisionError:
return "Cannot divide by zero."
# Test the function
print(safe_divide(10, 2))    # Output: 5.0
print(safe_divide(5, 0))     # Output: "Cannot divide by zero."
```

We all know any number can not be divided by zero. It results infinity. In Python also if you try to divide any number by zero, it will through an error called `ZeroDivisionError: division by zero`.

This intermediate Python exercises is to handle and bypass this error. In this code, `safe_divide` function attempts division and uses a `try-except` block to catch the `ZeroDivisionError` if the divisor is zero.

It returns a meaningful message instead of letting the program crash. This exercise demonstrates the importance of error handling for robust and fault-tolerant code. We frequently use this kind of `try-except` code block to build some applications that we are planning to deploy. So that our code will not crash in any scenario.

## 6. Class and Object Concepts

Question: Create a simple class to represent a book with attributes like title, author, and publish year.

```# Python intermediate exercises : Class & Objects
class Book:
def __init__(self, title, author, publish_year):
self.title = title
self.author = author
self.publish_year = publish_year
# Create an instance of the Book class
book1 = Book("The Python Journey", "John Coder", 2022)
# Print information about the book
print("Title:", book1.title)
print("Author:", book1.author)
print("Publish Year:", book1.publish_year)
```
``````Output:
Title: The Python Journey
Author: John Coder
Publish Year: 2022``````

In the above Python code, we are defining the blueprint for creating book objects using the `Book` class. The `__init__` method initializes the object’s attributes.

The created instance, `book1`, represents a specific book with a title, author, and publication year. These intermediate python exercises will help you to brush up your object-oriented programming concepts.

## 7. List Comprehensions

Question: Write a function that squares each element in a given list using list comprehension.

```# Python intermediate exercises : List Comprehensions
def square_elements(input_list):
return [x**2 for x in input_list]
# Test the function
print(square_elements([1, 2, 3, 4]))  # Output: [1, 4, 9, 16]
```

The `square_elements` function utilizes the list comprehension technique of Python to create a new list where each element of `input_list` is squared. We can simply do this using a for loop.

## 8. Lambda Functions

Question: Create a lambda function to calculate the area of a rectangle.

```# Python exercises for intermediate : Lambda function to find area of a rectangle
rectangle_area = lambda length, width: length * width
# Test the lambda function
print(rectangle_area(5, 7))  # Output: 35
```

Lambda functions are highly useful while writing high-level Python codes, especially where speed matters. Here `rectangle_area` lambda function takes two parameters, length and width. Using those values it calculates the area of a rectangle (multiplying those values as per area formula).

## 9. Filter and Map

Question: Use `filter` and `map` to get a list of squared values (like: 4, 16, 36, etc.) for even numbers in a given list.

```# Python exercises for intermediate : find squared numbers from the list elements
input_numbers = [1, 2, 3, 4, 5, 6]
even_squares = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, input_numbers)))
# Display the result
print(even_squares)  # Output: [4, 16, 36]
```

In the above code, first, we are filtering even numbers in the input list. Then squaring those even numbers and producing output. To do fast searching, we used the lambda function here. You can try different techniques also.

We used `filter` function to select even numbers, and the `map` function to square each of those even numbers. This exercise demonstrates the combination of higher-order functions for more complex data transformations.

## 10. Decorator

Question: In this python intermediate exercises, create a decorator to measure the execution time of a function.

```# Python exercises for intermediate : calculate function execution time
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {end_time - start_time:.5f} seconds to execute.")
return result
return wrapper
# Apply the decorator
@timing_decorator
def slow_function():
time.sleep(2)
# Test the decorated function
slow_function()
```
``````Output:
slow_function took 2.00108 seconds to execute.``````

In the above Python code, `timing_decorator` function is a decorator that measures the execution time of a wrapped function. The decorator is applied to `slow_function`.

When this `slow_function` is called, the timing information is displayed. This exercise introduces you to decorators, a powerful feature in Python. While dealing with object-oriented programming in Python you may often need to play with decorator.

## 11. Recursion

Question: Write a recursive function to calculate the factorial of a given number.

```# Python exercises for intermediate : Write a recursive function
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Test the function
print(factorial(5))  # Output: 120
```

In the above code, `factorial` function is implemented recursively, where the base case is when `n` is 0 or 1. The function calls itself with a smaller value until it reaches the base case. I included this exercise to introduce you to recursive function implementation.

## 12. Set Operations

Question: Write a function to find the intersection of two sets.

```# Python exercises for intermediate : find common values of two sets
def set_intersection(set1, set2):
return set1.intersection(set2)
# Test the function
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
print(set_intersection(set_a, set_b))  # Output: {3, 4}
```

The `set_intersection` function uses the `intersection` method to find the common elements between two sets. This exercise introduces you to set operations, a fundamental concept in Python for handling unique collections of elements.

`set()` operation is a fundamental concept in Python for handling unique collections of elements. Here `set_intersection` function uses the `intersection` method to find the common elements between two sets.

## 13. JSON Parsing

Question: Create a function to parse a JSON string and extract specific information.

```import json
def extract_info(json_string):
return data['name'], data['age']
# Test the function
json_data = '{"name": "Alice", "age": 30, "city": "Wonderland"}'
name, age = extract_info(json_data)
print(f"Name: {name}, Age: {age}")  # Output: Name: Alice, Age: 30
```

If you are planning to work as a Python backend developer or data engineer, you must know JSON parsing. Here in this code, we are reading a JSON file using `json.loads()` function. Then using key value information, we only extract the name and age from that JSON and finally print it.

Question: Implement a simple multithreading example to execute two functions concurrently.

```# Python intermediate exercises : simple multithreading
import time
def print_numbers():
for i in range(5):
time.sleep(1)
print(i)
def print_letters():
for letter in 'ABCDE':
time.sleep(1)
print(letter)
# Create and start two threads
```
``````Output:
0A
B1
C2
D3
E4``````

In this code, we used `threading` module to create two threads to execute `print_numbers` and `print_letters` functions at the same time. Python executes any function one by one by default. But if you want to fully utilize your CPU, then you must use multithreading.

Here in this code, we tried to run two functions simultaneously. In the same way, you can multithread for loop in Python for better execution speed.

## Conclusion

In this article, I tried to list of some intermediate Python exercises that can help you to brush up your knowledge and can be useful before appearing for a job interview. You can download these intermediate Python exercises as pdf to practice these question answer codes with solutions in offline mode.

This is it for this article. If you want to learn Python quickly then this Udemy course is for you: Learn Python in 100 days of coding. If you are a person who loves learning from books then this article is for you: 5 Best Book for Learning Python. See you in the comment section below.