Part A - Theory Component
Coding Best Practices in Python Language
Python is a high-level, dynamically typed language known for its readability and
simplicity. Following coding best practices ensures code consistency, maintainability,
and scalability. Below are key principles that define professional Python coding.
a) Code Formatting and Naming Conventions
Python follows the PEP 8 style guide for code formatting. Proper indentation (4 spaces
per level) is mandatory. Function and variable names should use lowercase letters with
underscores (snake_case), while class names use PascalCase. Constants should be written
in uppercase. For example:
def calculate_average(numbers):
total = sum(numbers)
return total / len(numbers)
b) Error Handling Techniques
Error handling in Python is done using try-except blocks to catch exceptions gracefully.
Developers should handle specific exceptions rather than using a generic except block.
The finally block can be used for cleanup tasks. Example:
try:
result = 10 / num
except ZeroDivisionError:
print('Division by zero is not allowed.')
finally:
print('Operation complete.')
c) Memory Management
Python handles memory management automatically using reference counting and
garbage collection. However, developers can use context managers (with statements) to
ensure timely release of resources, such as closing files or network connections.
d) Modularity and File Organization
Large Python projects should be divided into multiple modules and packages. Each
module should serve a specific purpose. Functions and classes should be reusable and
logically grouped. Proper folder structure makes maintenance easier.
e) Importance of Readability and Maintainability
Readable code reduces bugs and makes collaboration easier. Adding docstrings,
comments, and type hints improves clarity. Consistent formatting and naming make the
code self-explanatory for new developers.
2. Advantages of Code Reviews
Code review is the process of systematically examining another developer’s code to
identify errors, improve design, and ensure coding standards. It is an essential step in
modern software development.
a) Importance of Code Review
Code reviews improve software quality by catching bugs early, enhancing performance,
and promoting learning. They help maintain consistent coding styles across a team and
ensure that all developers understand the system’s codebase.
b) Benefits of Code Reviews
1. Early detection of bugs
2. Improved code readability
3. Knowledge sharing among team members
4. Stronger team collaboration
5. Better maintainability of projects
c) Example of Poor vs Reviewed Code
Poor Code:
x=10;y=20;print(x+y)
Reviewed Code:
def add_numbers(a, b):
return a + b
print(add_numbers(10, 20))
d) Best Practices During Code Review
1. Focus on readability, performance, and maintainability.
2. Provide constructive feedback.
3. Avoid personal criticism and encourage open discussion.
4. Review small chunks of code at a time.
5. Use automated tools for style checking (e.g., flake8, pylint).
3. Advantages of Unit Testing
Unit testing is the process of testing individual components of a program to ensure that
each works correctly. It plays a critical role in verifying correctness and preventing future
regressions.
a) Importance of Unit Testing
Unit testing ensures reliability by verifying that small units of code, such as functions,
produce expected results. It helps in identifying defects early, saving debugging time and
cost.
b) Benefits of Unit Testing
1. Detects bugs early in development.
2. Improves code quality and design.
3. Facilitates safe refactoring.
4. Reduces debugging time.
5. Ensures long-term project stability.
c) Tools Used for Unit Testing in Python
Python provides two primary frameworks for unit testing: unittest and pytest. unittest is
built into Python’s standard library and uses a class-based structure with assertion
methods, while pytest offers simplicity and better reporting.
Part B - Practical Component
Task 1 - Implement a Simple Program in Python
Source code:
Below is the Python implementation for calculating sum, average, and
maximum value of a list of integers:
# sum_avg_max.py
def calculate_sum(numbers):
'''Returns the sum of a list of numbers.'''
return sum(numbers)
def calculate_average(numbers):
'''Returns the average of a list of numbers.'''
if len(numbers) == 0:
raise ValueError('List cannot be empty')
return sum(numbers) / len(numbers)
def find_maximum(numbers):
'''Returns the maximum number from the list.'''
if not numbers:
raise ValueError('Empty list provided')
return max(numbers)
if __name__ == '__main__':
try:
nums = list(map(int, input('Enter integers separated by space: ').split()))
print('Sum:', calculate_sum(nums))
print('Average:', calculate_average(nums))
print('Maximum:', find_maximum(nums))
except Exception as e:
print('Error:', e)
Output of the code sum_max_avg.py :
Task 2 — Code Review
The reviewed code is clear and modular, adhering to Pythonic conventions. Functions are
reusable and error handling is present. However, improvements can be made in input
validation and documentation.
Strengths:
1. Proper function separation
2. Good use of exception handling
3. Easy-to-read variable names
Suggestions:
1. Add more docstrings for clarity
2. Include edge case testing for empty or invalid inputs
3. Use logging instead of print statements for better debugging
Task 3 — Add Unit Tests
Below is a sample unit test file for the implemented functions using unittest:
# test_sum_avg_max.py
import unittest
from sum_avg_max import calculate_sum, calculate_average, find_maximum
class TestMathFunctions([Link]):
def test_sum(self):
try:
[Link](calculate_sum([1, 2, 3]), 6)
print("Test Sum: PASS")
except AssertionError:
print("Test Sum: FAIL")
raise
def test_average(self):
try:
[Link](calculate_average([1, 2, 3]), 2.0)
print("Test Average: PASS")
except AssertionError:
print("Test Average: FAIL")
raise
def test_maximum(self):
try:
[Link](find_maximum([1, 2, 3]), 3)
print("Test Maximum: PASS")
except AssertionError:
print("Test Maximum: FAIL")
raise
if __name__ == '__main__':
[Link](verbosity=0)
Sample Test Output:
Conclusion
Through this assignment, the importance of coding best practices, code reviews, and unit
testing in Python development becomes clear. By following structured coding styles,
ensuring peer review, and verifying functions through testing, we build software that is
robust, readable, and maintainable. This process enhances collaboration and guarantees
long-term quality in software projects.