Indentation
Indentation in Python means adding spaces or tabs at the beginning of a line to show that it belongs to a block of code. It is like grouping instructions together to tell Python which steps to follow under certain conditions or inside a function.
- In other languages, we use to group code.
- In Python, indentation replaces and shows where a block of code starts and ends.
Simple English sentences where punctuation changes meaning
-
Let's eat Grandma.
- Means: We are about to eat Grandma (cannibalism)!
-
I like cooking my family and my dog.
- Means: I enjoy cooking my family and my dog (yikes!).
-
The panda eats, shoots, and leaves.
- Means: The panda eats food, then shoots (a gun), and leaves.
Examples of indentation in Python
if 5 > 3:
print("Five is greater than three.") # This line is indented, so it's part of the 'if' block.
print("This is outside the block.") # Not indented, so it's not part of the 'if' block.
if 5 > 3:
print("This line is not indented!") # Error because Python expects an indented block.
number = 5
print("Line 1: Hello")
if number < 0:
print("Line 2: Processing.....")
print("Line 3: The number is negative.")
print("Line 4: Goodbye")
Indentation Check:
- The indentation is correct because:
- The if statement checks if number < 0, and the indented block under it contains two print statements.
- After the if block, print("Line 4: Goodbye") is at the same level as the if statement, meaning it is outside the conditional block and will always execute.
time_of_day = "morning"
if time_of_day == "morning":
print("Good morning!") # Only runs if the condition is True.
time_of_day = "afternoon"
if time_of_day == "afternoon":
print("Good afternoon!") # Only runs if the condition is True.
Indentation Check:
- The if statements are correctly structured:
- The conditions (if time_of_day == "morning": and if time_of_day == "afternoon":) are at the correct indentation level.
- The print statements inside the if blocks are indented exactly one level (4 spaces) inside the block, which is correct in Python.
- No unnecessary or incorrect indentation is present.