Back to Python
2025-12-065 min read

Indentation in Loop

Learn Indentation in Loop step by step with clear examples and exercises.

Title: Mastering Indentation in Python Loops - Syntax, Best Practices, and Common Pitfalls

Why This Matters

Indentation is a fundamental aspect of Python's syntax, playing an essential role in structuring code within loops, functions, and classes. Understanding the correct indentation in loops can help you avoid runtime errors, make your code more readable for others, and ensure that your programs run smoothly. This knowledge will be beneficial during coding interviews, real-world programming tasks, and debugging complex programs.

Prerequisites

Before diving into Python's loop indentation, it is essential to have a good understanding of the following concepts:

  1. Basic Python syntax (variables, operators, expressions)
  2. Control structures (if-else statements, conditional expressions)
  3. Loops (for and while loops)
  4. Functions and function definitions
  5. Data structures like lists and dictionaries
  6. Error handling with try-except blocks

Core Concept

In Python, indentation is used to define the block of code that belongs to a particular loop or control structure. The indentation level determines whether a line of code falls within the body of the loop or not. Python uses four spaces for indentation by default. However, you can customize your editor's settings if needed.

Here is an example of a simple for loop with proper indentation:

for i in range(5):
print("Iteration:", i)

In this example, the print() statement is indented and falls within the body of the for loop, which means it will be executed for each iteration.

Indentation Rules

  1. Python uses spaces (not tabs) for indentation.
  2. The recommended number of spaces for indentation is four.
  3. All lines within a loop or control structure should be aligned to the same indentation level.
  4. If you need to include comments within a loop, make sure they are properly indented as well.

Worked Example

Let's consider a more complex example where we calculate the sum of all even numbers between 1 and 100 using a for loop:

sum_even = 0
for i in range(1, 101):
if i % 2 == 0:
sum_even += i
print("Sum of even numbers between 1 and 100:", sum_even)

In this example, the if statement is used to check whether the current number i is even or odd. If it's even, the number is added to the sum_even variable, which falls within the body of the for loop due to proper indentation.

Common Mistakes

  1. Incorrect Indentation: Misaligned indentation can lead to syntax errors. Make sure all lines within a loop or control structure are properly indented.
  2. Mixed Tabs and Spaces: Using both tabs and spaces for indentation can cause inconsistencies in your code, making it harder to read and understand. Stick to using either tabs or spaces consistently.
  3. Not Indenting the Loop Condition: The loop condition should be placed on the same line as the loop keyword (for or while) and properly indented.
  4. Forgetting to Update Variables: In some cases, you may forget to update a variable within the loop body, which can lead to incorrect results.
  5. Improper Indentation in Nested Loops: When working with nested loops, ensure that each level of indentation is consistent and clearly defines the scope of the corresponding loop.
  6. Inconsistent Indentation Styles: Maintaining a consistent indentation style throughout your codebase can help prevent errors and make it easier to read and understand.
  7. Ignoring PEP 8 Guidelines: The Python Style Guide (PEP 8) provides recommendations for coding styles, including indentation, that are widely accepted in the Python community. Familiarize yourself with these guidelines to write cleaner, more maintainable code.

Practice Questions

  1. Write a for loop that prints the multiplication table for 5 up to 10.
  2. Modify the previous example to calculate the sum of odd numbers between 1 and 100.
  3. Write a while loop that continuously asks the user for input until they enter "quit".
  4. Given an array of integers, write a function that finds the second largest number in the array using a for loop.
  5. Write a nested for loop to find all pairs of numbers within an array that add up to a given target sum.
  6. Implement a function that calculates the factorial of a given number using a while loop.
  7. Write a function that generates Fibonacci sequence up to a given number using a for loop.
  8. Create a program that simulates rolling dice multiple times and calculates the frequency of each number appearing.
  9. Implement a function that finds the longest common subsequence between two strings using dynamic programming and nested loops.
  10. Write a program that generates all possible permutations of a given list using recursion and nested for loops.

FAQ

Why does Python use indentation instead of curly braces?

Python's creator, Guido van Rossum, chose to use indentation because it makes the code more readable and easier to understand. The lack of curly braces also simplifies the syntax, making Python a great language for beginners.

Can I change the number of spaces used for indentation?

Yes, you can change the number of spaces used for indentation by modifying your editor's settings or using a code formatter tool like autopep8. However, it is recommended to stick with the default four-space indentation for consistency and readability.

What happens if I don't follow proper indentation in Python?

If you don't follow proper indentation in Python, your code will not run as expected or may even produce runtime errors. It can also make your code harder to understand and maintain for others.

Indentation in Loop | Python | XQA Learn