Understanding Python Indentation and Code Blocks

 

 

Introduction

Python uses indentation (whitespace at the beginning of a line) to define the structure of the code.
Unlike many other programming languages that use braces { } to denote code blocks,
Python relies on indentation to determine where blocks of code begin and end.
This makes the code cleaner and more readable.

Objective

In this tutorial, you will learn how Python handles indentation, how to create code blocks correctly,
and how indentation impacts the execution of your Python program. We will demonstrate this with a
simple conditional statement.

Sample Python Code

age = 18

if age >= 18:
    print("You are eligible to vote.")
    print("Please carry a valid ID.")
else:
    print("You are not eligible to vote yet.")
    print("Please wait until you turn 18.")

Explanation of the Program Structure

In the above code:

  • Line 1: We declare a variable age and assign it a value.
  • Lines 3-4: The if condition checks if the person is 18 or older. The indented lines that follow belong to this if block.
  • Lines 5-6: The else block runs if the if condition is not met. Again, proper indentation is used to group the statements.

If you change the indentation or forget to indent after if or else, Python will throw an IndentationError.

How to Run the Program

  1. Open a text editor or an IDE like VSCode, PyCharm, or simply use IDLE.
  2. Copy the above code into a new Python file and save it as voting_check.py.
  3. Open a terminal or command prompt.
  4. Navigate to the folder where your file is saved.
  5. Type python voting_check.py and press Enter.
  6. You will see the output based on the value of the age variable.
© 2025 Learn Programming. All rights reserved.

 

Leave a Reply

Your email address will not be published. Required fields are marked *