AlgoMaster Logo

Best Practices - Quiz

Last Updated: December 6, 2025

1 min read

Best Practices Exercises

31 quizzes

1
Code Completion

Use a style-checking tool to verify that the current file follows PEP 8 naming and spacing rules.

python
1
subprocess.run(["python", "-m", "flake8", ])

Click an option to fill the blank:

2
Code Completion

Format the value of total_requests into a readable string using an f-string before logging it.

python
1
logger.info(f"Total requests: {}")

Click an option to fill the blank:

3
Code Completion

Retrieve a configuration value with a safe default so the code remains robust in production.

python
1
timeout = config.get("REQUEST_TIMEOUT", )

Click an option to fill the blank:

4
Multiple Choice

According to PEP 8, which function name is preferred for readability?

5
Multiple Choice

Which is the most PEP 8 compliant way to add spaces around an assignment?

6
Multiple Choice

Which tool is commonly used to automatically format Python code according to a consistent style?

7
Multiple Choice

Which file is typically used to provide a high-level overview and usage instructions for a Python project?

8
Multiple Choice

Where should a function’s docstring be placed to follow best practices?

9
Multiple Choice

Which of the following is the most Pythonic way to iterate over items in a list with their index?

10
Multiple Choice

Which design pattern best describes a class that provides a single shared database connection instance?

11
Multiple Choice

A class that handles logging, database access, and HTTP requests all together is an example of which anti-pattern?

12
Multiple Choice

Which data structure is usually best for fast membership checks in large collections?

13
Multiple Choice

Which practice helps protect a Python application from known vulnerabilities in third-party packages?

14
Multiple Choice

Which line keeps code within the recommended 79-character limit when building a long string?

15
Sequencing

Order the steps to add documentation to a new Python module and make it discoverable.

Drag and drop to reorder, or use the arrows.

16
Sequencing

Order the steps to safely optimize a slow function in a production codebase.

Drag and drop to reorder, or use the arrows.

17
Output Prediction

What is the output of this code that uses a Pythonic list comprehension?

1numbers = [1, 2, 3, 4]
2result = [n * 2 for n in numbers if n % 2 == 0]
3print(result)
18
Output Prediction

What is the output when accessing a dictionary using the get method with a default?

1config = {"timeout": 10}
2value = config.get("retries", 3)
3print(value)
19
Output Prediction

What is the output of this code using a small Singleton-like cache?

1class Settings:
2    _instance = None
3    def __new__(cls):
4        if cls._instance is None:
5            cls._instance = super().__new__(cls)
6        return cls._instance
7
8first = Settings()
9second = Settings()
10print(first is second)
20
Output Prediction

What is the output when using a set for membership testing?

1allowed_roles = {"admin", "editor", "viewer"}
2print("guest" in allowed_roles)
21
Output Prediction

What is the output of this code that uses a docstring and prints the function’s __doc__?

1def greet(name):
2    """Return a polite greeting."""
3    return f"Hello, {name}!"
4
5print(greet.__doc__)
22
Bug Spotting

Find the bug in this code that is meant to validate user input and log an error.

Click on the line(s) that contain the bug.

python
1
import logging
2
 
3
logger = logging.getLogger(__name__)
4
 
5
def get_age(age):
6
    if not isinstance(age, int) or age < 0:
7
        logger.error("Invalid age: %s", age)
8
        raise ValueError("Age must be non-negative integer")
9
    return age
10
 
23
Bug Spotting

Find the bug in this code that attempts to cache configuration in a Singleton-style class.

Click on the line(s) that contain the bug.

python
1
class Config:
2
    _instance = None
3
 
4
    def __new__(cls, settings=None):
5
        if cls._instance is None:
6
            cls._instance = super().__new__(cls)
7
            cls.settings = settings or {}
8
        return cls._instance
9
 
10
config1 = Config({"debug": True})
11
config2 = Config({"debug": False})
12
 
24
Matching

Match each design pattern to its primary intent.

Click an item on the left, then click its match on the right. Click a matched item to unmatch.

25
Matching

Match each security practice with its description.

Click an item on the left, then click its match on the right. Click a matched item to unmatch.

26
Fill in the Blanks

Complete the function to document and compute an average response time using Pythonic tools.

python
1
def average_response_time(durations):
2
""""""
3
if not durations:
4
return
5
total = sum(durations)
6
return total /
7

Click an option to fill blank 1:

27
Fill in the Blanks

Complete this secure function that reads a setting with a safe default and validates it.

python
1
def get_max_items(config):
2
"""Return a validated maximum number of items to process."""
3
raw_value = config.get("MAX_ITEMS", )
4
if not isinstance(raw_value, int) or raw_value <= 0:
5
raise ValueError("MAX_ITEMS must be a positive integer")
6
return min(raw_value, )
7

Click an option to fill blank 1:

28
Fill in the Blanks

Complete this Pythonic function that returns a sorted list of unique user IDs.

python
1
def normalize_user_ids(user_ids):
2
"""Return unique, sorted user IDs as strings."""
3
unique_ids = (str(uid) for uid in user_ids)
4
return (unique_ids)
5

Click an option to fill blank 1:

29
Fill in the Blanks

Complete this context manager-based function to measure execution time of a block.

python
1
import time
2
from contextlib import contextmanager
3
4
@contextmanager
5
def measure(label):
6
start = time.()
7
try:
8
yield
9
finally:
10
duration = time.() - start
11
print(f"{label} took {duration:.4f} ")
12

Click an option to fill blank 1:

30
Hotspot Selection

Click the line that violates PEP 8 naming conventions for a constant.

Click on the line to select.

python
1
MAX_CONNECTIONS = 10
2
pi_value = 3.14159
3
DbHost = "db.internal"
4
DEFAULT_TIMEOUT = 5
5
 
31
Hotspot Selection

Click the line that represents the God Object anti-pattern by taking on too many responsibilities.

Click on the line to select.

python
1
class UserService:
2
    def create_user(self, data):
3
        self._save_to_db(data)
4
        self._send_welcome_email(data)
5
        self._rebuild_search_index()
6
 

Premium Content

Subscribe to unlock full access to this content and more premium articles.