Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
Comments and Docstrings
Writing code is not just about making it work—it’s also about making it understandable for others (and your future self!). In Python, comments and docstrings are essential tools for improving code readability and maintainability. This guide will explain what comments and docstrings are, how to use them, and why they are important in Python programming.
What Are Comments?
Comments are notes or explanations added to your code that are ignored by the Python interpreter. They help you and others understand the purpose of the code, how it works, or why certain decisions were made.
Types of Comments
-
Single-Line Comments:
Use the#
symbol to write a comment on a single line. For example:# This is a single-line comment print("Hello, World!") # This comment is after the code
-
Multi-Line Comments:
Python doesn’t have a specific syntax for multi-line comments, but you can use multiple#
symbols or triple quotes ('''
or"""
). For example:# This is a multi-line comment # using multiple # symbols. """ This is also a multi-line comment using triple quotes. """ print("Hello, World!")
Why Are Comments Important?
- Code Readability: Comments make your code easier to understand, especially for others who may read it later.
- Debugging: Comments can help you identify and fix issues by explaining what each part of the code does.
- Collaboration: When working in a team, comments ensure everyone understands the code’s purpose and functionality.
- Documentation: Comments serve as a form of documentation, explaining how the code works and why it was written a certain way.
Best Practices for Writing Comments
-
Be Clear and Concise: Write comments that are easy to understand and to the point.
-
Avoid Over-Commenting: Don’t comment on every line—only explain complex or non-obvious parts of the code.
-
Update Comments: Keep your comments up-to-date with the code. Outdated comments can be misleading.
-
Use Comments for TODOs: Use comments to mark areas of the code that need improvement or further work. For example:
# TODO: Optimize this function for better performance def calculate_sum(numbers): return sum(numbers)
What Are Docstrings?
Docstrings (documentation strings) are a special type of comment used to describe the purpose and functionality of modules, functions, classes, and methods. Unlike regular comments, docstrings are retained at runtime and can be accessed using the __doc__
attribute or the help()
function.
How to Write Docstrings
Docstrings are enclosed in triple quotes ('''
or """
) and are placed immediately after the definition of a module, function, class, or method. For example:
def greet(name):
"""
This function greets the user by name.
Parameters:
name (str): The name of the user.
Returns:
str: A greeting message.
"""
return f"Hello, {name}!"
Why Are Docstrings Important?
- Documentation: Docstrings provide a clear and structured way to document your code.
- Accessibility: Docstrings can be accessed at runtime using
__doc__
orhelp()
, making it easy to understand how a function or class works. - Professionalism: Well-written docstrings make your code look more professional and polished.
- Auto-Generated Documentation: Tools like Sphinx can generate documentation from docstrings.
Types of Docstrings
-
One-Line Docstrings:
Use a single line to describe the purpose of the function or class. For example:def add(a, b): """Return the sum of two numbers.""" return a + b
-
Multi-Line Docstrings:
Use multiple lines to provide detailed information about the function or class. For example:def multiply(a, b): """ Return the product of two numbers. Parameters: a (int): The first number. b (int): The second number. Returns: int: The product of a and b. """ return a * b
Best Practices for Writing Docstrings
-
Follow PEP 257: Python’s official style guide (PEP 257) provides conventions for writing docstrings.
-
Be Descriptive: Clearly explain the purpose, parameters, and return values of the function or class.
-
Use Consistent Formatting: Stick to a consistent format for all docstrings in your project.
-
Include Examples: Add examples to show how the function or class should be used. For example:
def divide(a, b): """ Return the division of two numbers. Parameters: a (int): The numerator. b (int): The denominator. Returns: float: The result of a divided by b. Example: >>> divide(10, 2) 5.0 """ return a / b
Examples of Comments and Docstrings
Example 1: Comments in a Function
# Function to calculate the area of a rectangle
def calculate_area(length, width):
# Multiply length by width to get the area
return length * width
Example 2: Docstrings in a Function
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
Parameters:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
Returns:
float: The area of the rectangle.
"""
return length * width
Example 3: Docstrings in a Class
class Rectangle:
"""
A class to represent a rectangle.
Attributes:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
"""
def __init__(self, length, width):
"""
Initialize a Rectangle instance.
Parameters:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
"""
self.length = length
self.width = width
def area(self):
"""
Calculate the area of the rectangle.
Returns:
float: The area of the rectangle.
"""
return self.length * self.width
Accessing Docstrings
You can access docstrings using the __doc__
attribute or the help()
function. For example:
print(calculate_area.__doc__) # Access the docstring directly
help(calculate_area) # Display the docstring using help()