Table of Contents

Comments are short pieces of text added to code to explain what it does. They don’t affect how the program runs, but they make your code more readable - for you and for others. Python supports single-line comments using the # symbol and multi-line documentation using triple quotes (""" """), typically used for functions and modules. Writing clear comments helps structure your thoughts, makes debugging easier, and is a must-have habit for any professional developer. This section helps you practice adding meaningful comments and understanding code written by others.

These tasks focus on developing good habits early - not just writing code, but writing understandable code.

What you should know before starting:

  • How comments work in Python
  • Syntax: # for single-line comments, triple quotes for docstrings
  • Importance of writing clean and self-documented code
  • Best practices: don’t over-comment obvious code, comment why, not how

Beginner Level Practice - Comments in Python

At the beginner level, comments are all about clarity and habit formation. These tasks will help you get used to using # to explain your code - what each part does, why a variable was added, or how a decision was made. You’ll also see how to use comments to disable code temporarily and how to make your logic easier to follow. The goal here is not to write more comments - but to write useful ones. Take your time, and focus on clarity.

1. Comment the Code

Below is a short Python program. Your task is to add appropriate single-line comments using # to explain what each line does. Focus on what the code is doing and why it’s useful.


        name = input("What is your name? ")
        print("Hello, " + name)

        age = int(input("How old are you? "))
        print("You will be", age + 1, "next year!")
      
What this Task Teaches

This task shows how to describe the purpose of code without affecting its behavior. You’ll learn to use comments to walk someone else through your thought process and make code more readable.

Hints and Tips
  • Write comments directly above the line of code, or at the end (if it’s short).
  • Explain what each line does - especially where input or calculations happen.
  • Don’t describe obvious syntax like “this is a print” - explain the logic.
Common Mistakes
  1. Over-commenting every line: Not every line needs a comment. Use them only where needed for understanding.
  2. Explaining the obvious: “This is a print statement” isn’t helpful. Instead, explain what is being printed and why.
  3. Placing comments too far away: Keep them close to the relevant code so they’re easy to connect.
  4. Using incorrect syntax: Comments in Python must start with #, not // or --.
  5. Writing unclear or vague comments: Be specific and concise - the reader should understand your intent in one glance.
Step-by-Step Thinking

Imagine you’re explaining this code to a classmate. Think about what each part of the program does from the user’s point of view.

  1. Start with the input line - what does it collect and store?
  2. Then look at the print - what message is shown and why?
  3. Explain how the age is used and how it’s incremented
  4. Keep comments short and easy to read
  5. Run the code to ensure nothing breaks while commenting
How to Make it Harder
  • Use comments to suggest what could be added or improved later.
  • Write your own 5-line program and fully comment it for another beginner to understand.
  • Challenge yourself to use only 3 comments that explain the entire block of code clearly.

2. Disable a Line with a Comment

Write a simple program that asks the user for a number, then multiplies it by 2 and prints the result. However, you should temporarily “disable” the print line using a comment. Then run the program and see what happens without it. This simulates turning off parts of your code for testing.

What this Task Teaches

This task shows how comments can be used for debugging or temporarily disabling features. You’ll also practice identifying which parts of the code are active and which are not when testing.

Hints and Tips
  • Use # in front of the print() line to disable it.
  • The input and calculation lines should remain active.
  • Run the program before and after removing the comment to compare behavior.
Common Mistakes
  1. Commenting out too much: Only disable one line - not the entire code block.
  2. Forgetting to re-enable code: Remember to remove the comment mark if you want to bring the line back into the program.
  3. Using the wrong comment syntax: Python doesn’t use /* */ - only # for single-line commenting.
  4. Changing indentation while commenting: Keep the formatting consistent to avoid confusion.
  5. Confusing comments with strings: Don’t use quotation marks for comments - they won’t actually disable code.
Step-by-Step Thinking

This is a quick test tool. You’re simulating how developers “turn off” code without deleting it.

  1. Write a program with input(), a calculation line, and print()
  2. Add a comment symbol # before the print() line
  3. Run the program - it should do the work but print nothing
  4. Remove the # and rerun it - now the result appears
  5. Reflect on how useful this is when debugging code blocks
How to Make it Harder
  • Disable both input and print lines - what happens then?
  • Use comments to describe what each line should do when active.
  • Try disabling only part of a line (e.g., a parameter inside print()).

Intermediate Level Practice - Comments in Python

At the intermediate level, comments become more than just explanations - they become tools for organizing logic, guiding readers, and even documenting functions. In real projects, your code will contain multiple decision branches, variables, and inputs, so clear commenting is essential to help others (and future you) understand what’s happening. These tasks focus on adding purposeful comments to more structured code and using docstrings to describe the role of functions. You’ll practice clean, professional documentation habits that are standard in real-world development.

1. Explain the Logic in a Multi-Branch Program

Here’s a simple Python program that checks the temperature and gives a message. Your task is to add comments that explain what each part does and why the condition is written the way it is.


      temp = int(input("Enter the temperature in °C: "))
      if temp > 30:
          print("It’s hot outside.")
      elif temp >= 20:
          print("Nice weather!")
      elif temp >= 10:
          print("A bit chilly.")
      else:
          print("It’s cold!")
  
What this Task Teaches

You’ll learn how to comment complex conditional logic by explaining not what the code says, but what the different temperature ranges mean from a user’s perspective. This helps document the reasoning behind your logic.

Hints and Tips
  • Comment what each temperature range represents (not just the syntax).
  • Explain why the elif conditions are ordered this way.
  • Use comments to show the intended “story” of the logic.
Common Mistakes
  1. Repeating code in comments: Avoid writing “if temperature > 30” as your comment - explain the intent (“Check if it’s a hot day”).
  2. Ignoring the logic structure: Explain the range logic and why this order matters.
  3. Writing vague comments: “Check temp” is too broad - specify what’s being checked and why.
  4. Forgetting the user perspective: Always think in terms of how the user would interpret the result.
  5. Using inconsistent format: Keep all comments aligned in style and placement.
Step-by-Step Thinking

Think about what each branch is trying to describe to the user - not just what it does technically.

  1. Start by describing what the temp variable represents
  2. Explain the range for “hot”, “warm”, “cool”, and “cold” conditions
  3. Comment on why the logic uses elif instead of multiple if blocks
  4. Make the comment tell a story: “If it’s above 30, warn about heat”
  5. Focus on clarity and helping someone else follow your reasoning
How to Make it Harder
  • Rewrite the logic using a function and document it with a docstring.
  • Add comments to suggest where localization (multi-language support) could be added.
  • Include feedback for humidity and describe how it could be integrated.

2. Add a Docstring to a Function

You are given a function that calculates the area of a rectangle. Your task is to write a proper Python docstring for it using triple quotes. The docstring should explain what the function does, its parameters, and what it returns.


    def get_area(width, height):
        return width * height
  
What this Task Teaches

This task introduces the standard way to document functions in Python using docstrings. You’ll learn to write clear and informative documentation that helps users understand what the function expects and what it gives back.

Hints and Tips
  • Use triple quotes right after the def line.
  • Explain what the function does in plain English.
  • List and describe the parameters (e.g., width: int).
  • Describe what the return value represents.
Common Mistakes
  1. Leaving out return description: Always explain what the function returns - even if it's obvious.
  2. Not using triple quotes: Python docstrings use """, not single quotes or comment symbols.
  3. Being too vague: “This function calculates” is not enough - include input, output, and usage.
  4. Mislabeling types: If you say height: float but actually use integers, that’s misleading.
  5. Skipping edge cases: Optionally mention assumptions, like positive dimensions only.
Step-by-Step Thinking

Pretend someone else will use this function - your docstring is your explanation to them.

  1. Open the docstring using """ right after the def line
  2. Write one sentence describing the function’s purpose
  3. List the parameters with short explanations and expected types
  4. Write what the function returns and in what form
  5. Close the docstring and keep it properly indented
How to Make it Harder
  • Add an example usage inside the docstring.
  • Rewrite the function with optional default parameters and document those too.
  • Add input validation and explain it in the docstring.

Advanced Level Practice - Comments in Python

At the advanced level, comments help manage complexity in larger programs. Now, it’s not just about explaining a line of code - it’s about documenting logic across multiple steps, clarifying edge cases, and guiding future changes. You'll also practice writing structured docstrings for functions and modules, which are essential in collaborative environments. These exercises will help you think like a professional developer: write code that’s clean and maintainable - and comments that serve as documentation, not just decoration.

1. Refactor and Document a Function

You’re given a function that checks whether a user is eligible for a loan. It works, but there are no comments or docstrings. Your task is to add both: a full docstring for the function, and inline comments explaining the logic step by step.


    def is_eligible(age, income, credit_score):
        if age >= 18 and income >= 30000 and credit_score >= 650:
            return True
        else:
            return False
    
What this Task Teaches

This task trains you to document multi-condition logic clearly. You’ll explain the logic for each requirement (age, income, score), write a proper docstring, and add comments that could guide future developers or teammates.

Hints and Tips
  • Use a triple-quoted docstring below the def line.
  • Explain the purpose, parameters, and return value.
  • Add inline comments describing each condition’s purpose.
  • Mention why specific thresholds (like 650) might matter.
Common Mistakes
  1. Explaining the syntax instead of the logic: Don’t write “checks age” - explain why age must be 18 or higher.
  2. Skipping the docstring: Advanced functions should always include documentation for others to understand their use.
  3. Not aligning comments with conditions: Keep each comment close to the logic it explains.
  4. Hardcoding values without context: Explain what the credit score threshold represents - don’t assume it's self-explanatory.
  5. Forgetting the return meaning: Document what True or False means for the program.
Step-by-Step Thinking

Imagine this function is used in a loan processing system. You need to ensure the next developer immediately understands what’s required and why.

  1. Start by writing a clear docstring: what does the function do, and what are the rules?
  2. Then write inline comments before or next to each condition
  3. Clarify any numeric thresholds (e.g., age 18, income 30k)
  4. Explain what returning True or False means in context
  5. Keep your comments professional and focused on the purpose, not just the code
How to Make it Harder
  • Add optional conditions (e.g., allow co-signer if credit_score is low).
  • Document the revised logic with updated comments and docstrings.
  • Log rejection reasons using print() or return strings.

2. Use Comments to Plan a Program

You’re going to write a small program that calculates the total cost of a meal with tax and tip. But before writing any actual code, write comments describing each step. You’re using comments as a planning tool - outlining the structure of your solution before coding.

What this Task Teaches

This task shows how experienced developers use comments for planning and outlining programs before implementation. It reinforces the concept that comments can support both communication and structure.

Hints and Tips
  • Think about the steps a program like this would take.
  • Write one comment per step, in order.
  • Use future-tense phrasing, like “Ask user for meal price.”
  • After writing the comments, use them as a to-do list to build the real program later.
Common Mistakes
  1. Writing vague comments: Don’t just write “do calculation” - describe what you’ll calculate (e.g., “Calculate 10% tip based on subtotal”).
  2. Using comments as code: At this stage, the file should only contain comments - no variables or print() yet.
  3. Out-of-order logic: Plan the steps in real-world order (first input, then math, then output).
  4. Overlooking edge cases: Add comments for possible future checks (e.g., “Check if input is a valid number”).
  5. Using inconsistent phrasing: Stick to the same voice/style in each comment (e.g., all steps in present or future tense).
Step-by-Step Thinking

Treat this like writing pseudocode in the form of comments. You’re laying the foundation of your solution.

  1. Start by writing a comment to describe the overall purpose
  2. Add a comment to collect the meal price from the user
  3. Include steps for calculating tax and tip using percentages
  4. Write a comment for summing everything to get the total
  5. Plan a final step to display the formatted result to the user
How to Make it Harder
  • Include optional steps like coupon discount or minimum tip enforcement.
  • Plan for input validation (e.g., checking for negative prices).
  • Group steps using section headers like # Step 1: Input.