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 thisif
block. - Lines 5-6: The
else
block runs if theif
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
- Open a text editor or an IDE like VSCode, PyCharm, or simply use IDLE.
- Copy the above code into a new Python file and save it as
voting_check.py
. - Open a terminal or command prompt.
- Navigate to the folder where your file is saved.
- Type
python voting_check.py
and press Enter. - You will see the output based on the value of the
age
variable.