Python
Module 16: Python Testing and Best PracticesBeginner18 min read

Writing Tests & PEP 8 Standards

Verify your code correctness with automated tests and adhere to Python style guides.

Key Takeaways & Core Concepts
  • Indentation: 4 spaces per indentation level.
  • Line Length: Limit all lines to a maximum of 79 characters.
  • Naming Conventions: * snake_case for functions and variables (calculate_total).

Writing Tests & PEP 8 Standards

### Testing & PEP 8 in Python

#### 1. PEP 8 (Python Enhancement Proposal 8) PEP 8 is the official style guide for Python code. Key conventions:

  • Indentation: 4 spaces per indentation level.
  • Line Length: Limit all lines to a maximum of 79 characters.
  • Naming Conventions:
  • snake_case for functions and variables (calculate_total).
  • PascalCase for classes (StudentProfile).
  • ALL_CAPS for constants (MAX_CONNECTIONS = 100).

#### 2. Unit Testing with unittest Python comes bundled with a comprehensive unit testing framework:

PYTHON Code Example
1import unittest
2
3def add(a, b):
4 return a + b
5
6class TestMath(unittest.TestCase):
7 def test_add_positive(self):
8 self.assertEqual(add(2, 3), 5)
9
10 def test_add_negative(self):
11 self.assertEqual(add(-1, -1), -2)
12
13if __name__ == "__main__":
14 unittest.main()
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
14 lines
Assertion Checks
1def set_percentage(value):
2 assert 0 <= value <= 100, "Percentage must be between 0 and 100"
3 return f"{value}%"
4
5print(set_percentage(95))
6try:
7 print(set_percentage(150))
8except AssertionError as e:
9 print("Caught Assertion:", e)
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
9 lines
Note: Assertions enforce invariants during execution.
Practice & AssessmentPython Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)