Python is one of the important programming languages for backend software development. One of the reasons it is so popular is its use in machine learning and artificial intelligence. As Python is ideal for compute-intensive operations, that means it is best suited to all the use cases where computer vision, machine learning or deep learning is utilized. That’s the reason you will see most of the machine learning libraries and frameworks in Python and a majority of AI engineers write code in Python. Besides AI, Python is also used extensively for backend development, including API and business services development.
Today we will discuss technical coding challenges for Python engineers. We will separately specify coding challenges for beginner, mid-level and expert Python engineers. These coding challenges will not only help technical managers evaluate Python engineers but will also be helpful to candidates who want to test their skills. Let’s start with coding challenges for beginner-level developers in Python.
Interview Questions for Beginner-level Python Engineers
When preparing interview questions for beginners in the Python language, you should focus on basic syntax, language constructs, data structure, libraries, algorithms, OOP, error handling, regular expressions and networking. Here are some of the coding challenges which are suitable for beginner-level Python engineers.
Question 1
What will be the output of the below code:
var1 = 7
var2 = 2
result = var1 // var2+ var1%var2
print(result)
Question 2
What is wrong with the below code:
def concatenate_strings(str1, str2):
return str1 + " " + str2
result = concatenate_strings("Test", 3)
print(result)
Question 3
What is wrong with the below code:
def print_uppercase(text):
for letter in text:
print(letter.upper())
print_uppercase(["Test", "Python"])
Question 4
Write a method that calculates the simple interest on a loan. The program should take user input for the principal amount, the annual interest rate (as a percentage), and the time to pay in years. The program should calculate and display the total amount (principal + interest) after the specified time.
Question 5
What will be the output of the following code:
def test(x, y=[]):
y.append(x)
return y
print(test(1))
print(test(2))
Question 6
What is wrong in the below code:
name = input("Input your name: ")
if name == "John" or "Brian":
print("Welcome, John or Brian!")
else:
print("You're not John or Brian.")
Question 7
Create a simple calculator that can perform basic arithmetic operations (addition, subtraction, multiplication and division) on two numbers. The program should take user input for both numbers and the desired operation. The result of the operation will be printed on the screen.
Question 8
What will be the output of the following code:
numbers = [5, 1, 9, 3, 7]
squared_numbers = list(map(lambda x: x**2, numbers))
squared_numbers.sort(reverse=True)
print(squared_numbers[:3])
Question 9
What is wrong with the below code:
import requests
url = "https://jsonplaceholder.typicode.com/users"
response = requests.get(url)
data = response.json()
email_addresses = [user["email"] for user in data if user["company"]["catchPhrase"].contains("fintech")]
print(email_addresses)
Question 10
Find the issue in the below code:
numbers = {1: "one", 2: "two", 3: "three"}
for number in numbers:
if numbers[number] == "two":
del numbers[number]
print(numbers)
Interview Questions for Mid-level Python Engineers
When designing interview questions for mid-level Python developers, you should focus on questions that test the deeper understanding of the language and advanced features. Some of the areas that should be tested include advanced data structures, multithreading, performance optimization, unit testing, advanced OOP and web services. Find below some of the questions that test these concepts:
Question 1
What is wrong with the below code:
def caching_decorator(func):
cache = {}
def wrapper(*args):
if args in cache:
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper
@caching_decorator
def add(a, b):
return a + b
add(3, 5)
print(add.cache)
Question 2
What will be the output of the below code:
def test_function():
try:
return "In try"
finally:
return "In finally"
result = test_function()
print(result)
Question 3
Develop a task scheduler that runs a specific function after a certain period of time. The scheduler should take user input for the function to run, the time interval (in seconds) between each run, and the total number of runs. Use Python’s threading or multiprocessing module to develop the scheduler.
Question 4
Develop a Python-based web scraper that retrieves a specific piece of information from a website. For example, extract all code snippets from a technology blog or get the current price of a product from a shopping website. Use libraries like Beautiful Soup or Scrapy to parse the HTML content and extract the relevant data.
Question 5
What is wrong with the below code:
import threading
counter = 0
def increment_counter():
global counter
for _ in range(100000):
counter += 1
threads = [threading.Thread(target=increment_counter) for _ in range(10)]
[thread.start() for thread in threads]
[thread.join() for thread in threads]
print(counter)
Question 6
What will be the output of the below code:
def outer_function():
value = "Say cheese to"
def inner_function1():
nonlocal value
value = "Python"
def inner_function2():
global value
value = "Engineers"
inner_function1()
inner_function2()
return value
value = "Programming"
result = outer_function()
print(value, result)
Question 7
What is wrong with below code:
import requests
def fetch_data(api_url):
try:
response = requests.get(api_url)
response.raise_for_status()
return response.json()
except requests.HTTPError as e:
print("Error: ", e)
api_url = "https://jsonplaceholder.typicode.com/todos/1"
data = fetch_data(api_url)
print(data["title"])
Question 8
Develop a Python function that reads a text file and calculates the metadata, including the number of lines, words, and characters in the file. You can ignore whitespaces and punctuation when counting characters. There will be only one input to this program: the text file. After processing, the result will be printed.
Question 9
What is wrong with the below code:
data = [
{"id": 1, "name": "Helen", "age": 28},
{"id": 2, "name": "Chris", "age": 49},
{"id": 3, "name": "Jennifer", "age": 19},
]
result = {item["name"]: item["age"] for item in data if item["age"] > 20}
print(result)
Question 10
Implement two versions of a function that generates the first n Fibonacci numbers. The first version of the function should be a regular function that returns a list of Fibonacci numbers, while the other version should be a generator function that produces Fibonacci numbers one at a time. Compare both implementations’ memory usage and runtime performance and share your results.
Interview Questions for Expert-level Python Engineers
When designing coding challenges for expert-level Python developers, you should evaluate the advanced concepts and in-depth knowledge of Python’s features. Some of the areas to test include advanced algorithms, metaprogramming, code optimization, profiling, parallelism, design patterns, security and distributed systems. Here are some coding challenges which are suitable for expert Python developers:
Question 1
Find the issue in the below code:
class MyResource:
def __init__(self, name):
self.name = name
def __enter__(self):
print(f"Acquiring {self.name}")
return self
def __exit__(self, exc_type, exc_value, traceback):
print(f"Releasing {self.name}")
def use_resource():
with MyResource("Resource A") as res_a, MyResource("Resource B") as res_b:
raise Exception("An error occurred")
try:
use_resource()
except Exception as e:
print(e)
Question 2
What will be the output of the below code:
class Meta(type):
def __new__(cls, name, bases, attrs):
attrs["greeting"] = "Hello, Python Engineers!"
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=Meta):
pass
obj = MyClass()
print(obj.greeting)
Question 3
Find the issue in the below code:
import threading
counter = 0
def increment():
global counter
for _ in range(100000):
counter += 1
threads = [threading.Thread(target=increment) for _ in range(10)]
[thread.start() for thread in threads]
[thread.join() for thread in threads]
print(counter)
Question 4
What will be the output of the below code:
class DynamicAttributes:
def __getattr__(self, name):
return name.upper()
def __getattribute__(self, name):
if name.startswith("get_"):
return super().__getattribute__(name[4:])
raise AttributeError
dyn = DynamicAttributes()
print(dyn.get_foo)
Question 5
Create a distributed task queue using message brokers like RabbitMQ or Apache Kafka. The program should allow users to submit tasks, execute them in parallel on multiple workers and manage the results. Try to implement fault tolerance, retries and prioritization of tasks in your program.
Question 6
What is wrong with the below code:
# module_a.py
import module_b
class A:
def get_b_instance(self):
return module_b.B()
# module_b.py
import module_a
class B:
def get_a_instance(self):
return module_a.A()
# main.py
import module_a
a = module_a.A()
b = a.get_b_instance()
print(b)
Question 7
What will be the output of the below code:
import asyncio
async def display():
await asyncio.sleep(1)
return "Hello World"
async def main():
result = await display()
print(result)
asyncio.run(main())
Question 8
Develop a real-time chat application using WebSockets, asyncio and a suitable web framework like FastAPI or Django. Implement features like user authentication, chat rooms, and message broadcasting. Make sure the application can handle a large number of concurrent requests.
Question 9
Optimize the following code snippet that uses Pandas DataFrame to calculate the mean price for each category:
import pandas as pd
data = {"category": ['A', 'B', 'A', 'A', 'B', 'B', 'A', 'B'],
"price": [10, 15, 12, 9, 20, 18, 8, 25]}
df = pd.DataFrame(data)
mean_prices = df.groupby("category")["price"].mean()
print(mean_prices)
You can optimize data types and use method chaining to optimize the code above. Also, confirm which one of the built-in pandas functions are already being used in the above code.
Question 10
There is a function that performs an expensive computation. You need to implement a caching mechanism using decorators or the functools.lru_cache function. Analyze the performance improvements and share the trade-offs involved in using caching in this scenario.
Conclusion
In this article, we discussed Python coding challenges for evaluating engineering candidates. As the coding challenges depend on the experience level of the developers, we have divided the coding challenges into three sections: beginner, mid-level and expert. These coding challenges evaluate the skillset of Python engineers in different Python areas and test their capabilities to implement a real-world scenario in Python language. Of course, these questions serve just as a guideline and are not for definite evaluation. Evaluating the soft skills of Python engineers is as important as testing their technical skills, so a combination of both is required.
Further reading: