Back to Python
2026-04-208 min read

Document Structure (Python Programming)

Learn Document Structure (Python Programming) step by step with clear examples and exercises.

Title: Document Structure (Python Programming)

Why This Matters

Understanding Python's document structure is crucial for organizing your code effectively, making it more readable, and easier to maintain. A well-structured program can save time during development and debugging, and it also makes a good impression on potential employers or collaborators. In interviews, demonstrating knowledge of proper Python structure can help showcase your programming skills.

Well-structured code is essential for large projects with multiple developers working together. Properly organized code makes it easier to navigate, understand, and modify the codebase, reducing the chances of introducing bugs or inconsistencies.

Prerequisites

To follow this lesson, you should have a basic understanding of Python syntax, including variables, functions, loops, conditional statements, and the importance of indentation. Familiarity with modules, classes, and exceptions is also beneficial but not required for grasping the concepts presented here.

Core Concept

Python programs are typically organized into modules, which can be thought of as individual files containing related code. A module usually has a .py extension, and it may define functions, classes, or variables that can be used by other parts of your program or even imported in other Python scripts.

A typical Python file starts with a shebang line (optional), followed by optional metadata such as comments, docstrings, and imports. After that comes the main function, which is where the execution begins when you run the script. The main function may call other functions, import modules, or perform various tasks.

Shebang Line

The shebang line (also known as a hashbang) is an optional line at the beginning of your Python file that specifies the interpreter to use when running the script. It looks like this:

#!/usr/bin/env python3

This line tells the operating system to execute the script using the python3 interpreter, which is usually found in the /usr/bin directory. If you're working on a Windows system, the shebang line might look like this:

#!/usr/bin/python

Comments and Docstrings

Comments in Python are enclosed within hashes (#) and are ignored by the interpreter. They can be used to explain what a piece of code does or why certain decisions were made during development.

Docstrings are multi-line comments that provide information about a module, function, or class. They are defined as strings immediately following the definition of the entity they describe. Docstrings follow a specific format:

def my_function():
"""
This is a docstring for my_function. It explains what the function does and how to use it.
"""

Function implementation goes here


### Importing Modules

Python provides a rich set of standard libraries that you can import into your scripts using the `import` statement. For example, to import the math module, you would write:

import math


You can also import specific functions or classes from a module using the dot notation:

from math import sin, cos


### Main Function

The main function is where your Python script begins execution. In most cases, it will contain the entry point for your program and call other functions as needed. The name of the main function is usually `main()`.

def main():

Your code goes here

if __name__ == "__main__":

main()


The last line checks if the script is being run directly (i.e., not imported as a module). If it's being run directly, the `main()` function will be called.

### Modules and Packages

Python organizes related modules into packages, which can further help with code organization. A package is simply a directory containing an `__init__.py` file, which tells Python that the directory should be treated as a package. You can create packages by creating directories and adding the necessary files.

### Classes and Objects

Python supports object-oriented programming (OOP), allowing you to define classes and create objects based on those classes. A class is a blueprint for creating objects, while an object is an instance of a class that has its own state and behavior.

Classes are defined using the `class` keyword, followed by the name of the class and a colon (`:`). Inside the class definition, you can define methods (functions associated with a class), properties, and other attributes.

Worked Example

Let's create a simple Python program that defines a Rectangle class for calculating the area and perimeter of rectangles.

#!/usr/bin/env python3

class Rectangle:
"""
A class for creating and manipulating rectangles.
"""

def __init__(self, length, width):
"""
Initializes a new rectangle with the given dimensions.

Args:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
"""
self.length = length
self.width = width

def area(self):
"""
Calculates and returns the area of the rectangle.

Returns:
float: The area of the rectangle.
"""
return self.length * self.width

def perimeter(self):
"""
Calculates and returns the perimeter of the rectangle.

Returns:
float: The perimeter of the rectangle.
"""
return 2 * (self.length + self.width)

def main():
rect = Rectangle(5, 10)
print(f"Area: {rect.area()}")
print(f"Perimeter: {rect.perimeter()}")

if __name__ == "__main__":
main()

In this example, we define the Rectangle class to create and manipulate rectangles. The main() function creates a new rectangle with dimensions 5 units by 10 units and calculates its area and perimeter.

Common Mistakes

  1. Forgetting to close indentation: Python uses indentation to determine the structure of your code. Forgetting to close an indentation can lead to syntax errors.
  1. Misusing commas and semicolons: Unlike some other programming languages, Python does not require semicolons to end statements. Using a semicolon instead of a newline can cause unexpected behavior.
  1. Improperly importing modules: Make sure you're importing the correct module or function, and that you're using the correct syntax for imports.
  1. Ignoring the main function: The main function is the entry point for your script. If you forget to define it or call it, your program will not execute as intended.
  1. Not using docstrings: Docstrings help others understand your code more easily. Leaving them out can make your code harder to read and maintain.
  1. Using global variables inappropriately: Global variables can cause conflicts and make code harder to understand. Use them sparingly and with caution.
  1. Not handling exceptions properly: Proper exception handling is essential for writing robust Python programs that can handle unexpected errors gracefully.
  1. Ignoring the __name__ == "__main__" check: This check ensures that your script runs as intended when executed directly, but it's also important to consider when importing the module into other scripts.

Practice Questions

  1. Write a Python script that calculates the sum of the numbers from 1 to 100 using a loop.
  2. Modify the Rectangle example to handle squares (i.e., rectangles with equal length and width) by adding a method to check if the rectangle is a square and returning the diagonal length if it is.
  3. Create a simple Python program that defines a class for a circle with properties radius, area, and circumference, and methods for calculating these values.
  4. Write a Python script that takes a list of numbers as input and returns the second-highest number in the list (assuming there are no duplicates).
  5. Implement a function to find the longest word in a given string.
  6. Create a simple Python program that defines a class for a bank account with properties balance, interest rate, and methods for depositing, withdrawing, and checking the account balance.
  7. Write a Python script that takes a list of words as input and returns the word that appears most frequently.
  8. Implement a function to find all prime numbers up to a given limit.
  9. Create a simple Python program that defines a class for a car with properties make, model, year, and mileage, and methods for printing information about the car, increasing the mileage by a specified amount, and checking if the car has reached a certain mileage threshold.
  10. Write a Python script that takes a list of tuples representing points in a 2D plane and returns the point with the maximum x-coordinate.

FAQ

Q: Do I need to include a shebang line in every Python script?

A: It's not strictly necessary if you always run your scripts using the same interpreter, but including a shebang line can make your scripts more portable and easier for others to execute.

Q: What is the difference between single-line comments and multi-line comments in Python?

A: Single-line comments are enclosed within hashes (#) and are ignored by the interpreter on that line only. Multi-line comments, or docstrings, are defined as strings immediately following the definition of a function, class, or module and can span multiple lines.

Q: Why is proper indentation important in Python?

A: Proper indentation helps the interpreter understand the structure of your code, such as loops and conditional statements. Incorrect indentation can lead to syntax errors.

Q: What happens if I forget to define the main function in my script?

A: If you forget to define the main function or call it, your program will not execute as intended because there's no entry point for the interpreter to start execution.

Q: How do I import a specific function from a module in Python?

A: You can import a specific function using the dot notation, like this: from module_name import function_name. Then you can call the function directly without needing to qualify it with the module name.

Q: What is the purpose of docstrings in Python?

A: Docstrings provide documentation for modules, functions, and classes. They help others understand what your code does, how to use it, and any important details about its behavior or implementation.

Q: Why should I avoid using global variables in Python?

A: Global variables can make code harder to read, maintain, and debug because they can be modified by any part of the program. It's generally best to limit their use and instead use local variables within functions or classes when possible.

Q: How do I handle exceptions in Python?

A: You can catch exceptions using a try/except block, which allows you to specify what should happen if an exception occurs during execution. You can also define custom exceptions for specific use cases.

Q: What is the purpose of the __name__ == "__main__" check in Python?

A: This check ensures that your script runs as intended when executed directly, but it's also important to consider when importing the module into other scripts. If the module is being imported, this check will not be true, and the main function will not be called.

Q: What are packages in Python?

A: Packages are directories containing Python modules that share a common purpose or namespace. They help organize related code and make it easier to manage large projects with multiple developers working together. To create a package, you need to create a directory and add an __init__.py file.

Document Structure (Python Programming) | Python | XQA Learn