Basic If Statement Structure and Indentation
🏷️ Conditional Logic and Decision Making / If, Elif, and Else Statements
đź§ Context Introduction
In Python, decision-making is one of the most fundamental concepts you'll encounter. Every program needs to make choices based on conditions—whether it's checking if a server is online, validating user input, or deciding which configuration to apply. The if statement is the simplest way to introduce logic into your code. It allows your program to execute certain actions only when a specific condition is True. Understanding how to structure these statements correctly, especially with proper indentation, is critical because Python relies on indentation to define blocks of code—unlike other languages that use braces or keywords.
⚙️ The Basic If Statement Structure
The basic if statement follows a simple pattern:
- Start with the keyword if.
- Follow it with a condition (an expression that evaluates to True or False).
- End the line with a colon (:).
- On the next line, indent the code that should run if the condition is true.
Example structure:
- if condition:
- print("Condition is True")
The indentation is not optional—it is mandatory. Python uses indentation to know which statements belong to the if block. Typically, you use 4 spaces for each indentation level.
🛠️ Indentation Rules Explained
Indentation is the backbone of Python's readability. Here are the key rules:
- Always use consistent indentation throughout your code. Mixing tabs and spaces will cause errors.
- The standard is 4 spaces per indentation level.
- Any code that is indented under an if statement will only run when the condition is True.
- Once you return to the original indentation level, that code runs regardless of the condition.
Example of correct indentation:
- if temperature > 30:
- print("It's hot outside")
- print("Stay hydrated")
- print("This line always runs")
Notice that the two print statements are indented under the if, so they only run when the temperature is above 30. The last print is at the same level as the if, so it runs no matter what.
📊 Comparison Table: Correct vs. Incorrect Indentation
| Aspect | ✅ Correct Indentation | ❌ Incorrect Indentation |
|---|---|---|
| Spacing | Use 4 spaces consistently | Mixing tabs and spaces |
| Colon | Always include : after condition | Missing colon |
| Block alignment | All block lines start at same indent | Lines at different indent levels |
| Return to base | Code after block is at original indent | Code after block is still indented |
| Readability | Clear visual structure | Confusing and error-prone |
🕵️ Common Pitfalls and How to Avoid Them
Even experienced engineers make mistakes with indentation. Here are the most common issues:
- Forgetting the colon at the end of the if line. Without it, Python will throw a syntax error.
- Inconsistent indentation—using 2 spaces in one place and 4 in another. This causes an IndentationError.
- Empty if block—if you have no code to run under an if, use the pass keyword as a placeholder:
- if condition:
- pass
- if condition:
- Misaligned code—code that should be inside the block but is at the wrong indent level will either run unconditionally or cause an error.
Example of a common mistake:
- if status == "active":
- print("Server is running")
This will cause an error because the print statement is not indented. The correct version is:
- if status == "active":
- print("Server is running")
đź’ˇ Practical Example for Engineers
Imagine you are writing a script that checks the status of a service. You want to print a message only if the service is down.
Step-by-step logic:
- Store the service status in a variable: service_status = "down"
- Write an if statement to check the condition: if service_status == "down":
- Indent the action to take: print("Alert: Service is down")
- Add a message that always runs: print("Check completed")
How it looks in practice:
- service_status = "down"
- if service_status == "down":
- print("Alert: Service is down")
- print("Check completed")
When you run this, the output will be:
- Alert: Service is down
- Check completed
If you change service_status to "up", the output will be only:
- Check completed
âś… Key Takeaways
- The if statement starts with if, followed by a condition, then a colon.
- Indentation (usually 4 spaces) defines which code belongs to the if block.
- Code at the same indentation level as the if runs unconditionally.
- Always use consistent indentation—never mix tabs and spaces.
- Use pass as a placeholder if you need an empty if block.
- The colon is mandatory—forgetting it will cause a syntax error.
Mastering the basic if statement and its indentation rules is your first step toward writing logical, decision-driven Python code. Once you're comfortable with this foundation, you'll be ready to explore more complex conditions with elif and else.
A basic if statement lets engineers execute code only when a specified condition is true, using indentation to define which statements belong to that condition.
âś… Example 1: Simple True Condition
This example shows the most basic if statement that always runs because the condition is explicitly True.
if True:
print("This will always run")
📤 Output: This will always run
âś… Example 2: Checking a Numeric Condition
This example demonstrates an if statement that checks whether a number meets a comparison condition.
speed = 55
if speed > 50:
print("You are going fast")
📤 Output: You are going fast
âś… Example 3: Condition That Evaluates to False
This example shows that when the condition is false, the indented code block is skipped entirely.
temperature = 30
if temperature > 100:
print("Water is boiling")
print("This line always runs")
📤 Output: This line always runs
âś… Example 4: Multiple Statements Inside One If Block
This example shows that all indented lines after the if statement belong to the same condition block.
engine_status = "running"
if engine_status == "running":
print("Engine is active")
print("Check oil pressure")
print("Monitor temperature")
print("End of check")
📤 Output: Engine is active
Check oil pressure
Monitor temperature
End of check
✅ Example 5: Practical Engineer Check — Temperature Alert
This example uses a real-world engineering scenario to decide whether to issue an alert based on a sensor reading.
coolant_temp = 105
if coolant_temp > 100:
print("WARNING: Coolant temperature exceeds 100°C")
print("Reduce engine load immediately")
print("Check cooling system")
📤 Output: WARNING: Coolant temperature exceeds 100°C
Reduce engine load immediately
Check cooling system
Comparison Table: Condition Outcomes
| Condition Result | Indented Code Runs? | Example Condition |
|---|---|---|
| True | Yes | if True: |
| False | No | if 5 > 10: |
| Variable equals value | Yes | if speed == 55: |
| Variable does not equal value | No | if temp != 30: |
đź§ Context Introduction
In Python, decision-making is one of the most fundamental concepts you'll encounter. Every program needs to make choices based on conditions—whether it's checking if a server is online, validating user input, or deciding which configuration to apply. The if statement is the simplest way to introduce logic into your code. It allows your program to execute certain actions only when a specific condition is True. Understanding how to structure these statements correctly, especially with proper indentation, is critical because Python relies on indentation to define blocks of code—unlike other languages that use braces or keywords.
⚙️ The Basic If Statement Structure
The basic if statement follows a simple pattern:
- Start with the keyword if.
- Follow it with a condition (an expression that evaluates to True or False).
- End the line with a colon (:).
- On the next line, indent the code that should run if the condition is true.
Example structure:
- if condition:
- print("Condition is True")
The indentation is not optional—it is mandatory. Python uses indentation to know which statements belong to the if block. Typically, you use 4 spaces for each indentation level.
🛠️ Indentation Rules Explained
Indentation is the backbone of Python's readability. Here are the key rules:
- Always use consistent indentation throughout your code. Mixing tabs and spaces will cause errors.
- The standard is 4 spaces per indentation level.
- Any code that is indented under an if statement will only run when the condition is True.
- Once you return to the original indentation level, that code runs regardless of the condition.
Example of correct indentation:
- if temperature > 30:
- print("It's hot outside")
- print("Stay hydrated")
- print("This line always runs")
Notice that the two print statements are indented under the if, so they only run when the temperature is above 30. The last print is at the same level as the if, so it runs no matter what.
📊 Comparison Table: Correct vs. Incorrect Indentation
| Aspect | ✅ Correct Indentation | ❌ Incorrect Indentation |
|---|---|---|
| Spacing | Use 4 spaces consistently | Mixing tabs and spaces |
| Colon | Always include : after condition | Missing colon |
| Block alignment | All block lines start at same indent | Lines at different indent levels |
| Return to base | Code after block is at original indent | Code after block is still indented |
| Readability | Clear visual structure | Confusing and error-prone |
🕵️ Common Pitfalls and How to Avoid Them
Even experienced engineers make mistakes with indentation. Here are the most common issues:
- Forgetting the colon at the end of the if line. Without it, Python will throw a syntax error.
- Inconsistent indentation—using 2 spaces in one place and 4 in another. This causes an IndentationError.
- Empty if block—if you have no code to run under an if, use the pass keyword as a placeholder:
- if condition:
- pass
- if condition:
- Misaligned code—code that should be inside the block but is at the wrong indent level will either run unconditionally or cause an error.
Example of a common mistake:
- if status == "active":
- print("Server is running")
This will cause an error because the print statement is not indented. The correct version is:
- if status == "active":
- print("Server is running")
đź’ˇ Practical Example for Engineers
Imagine you are writing a script that checks the status of a service. You want to print a message only if the service is down.
Step-by-step logic:
- Store the service status in a variable: service_status = "down"
- Write an if statement to check the condition: if service_status == "down":
- Indent the action to take: print("Alert: Service is down")
- Add a message that always runs: print("Check completed")
How it looks in practice:
- service_status = "down"
- if service_status == "down":
- print("Alert: Service is down")
- print("Check completed")
When you run this, the output will be:
- Alert: Service is down
- Check completed
If you change service_status to "up", the output will be only:
- Check completed
âś… Key Takeaways
- The if statement starts with if, followed by a condition, then a colon.
- Indentation (usually 4 spaces) defines which code belongs to the if block.
- Code at the same indentation level as the if runs unconditionally.
- Always use consistent indentation—never mix tabs and spaces.
- Use pass as a placeholder if you need an empty if block.
- The colon is mandatory—forgetting it will cause a syntax error.
Mastering the basic if statement and its indentation rules is your first step toward writing logical, decision-driven Python code. Once you're comfortable with this foundation, you'll be ready to explore more complex conditions with elif and else.
Interactive Views
You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.
A basic if statement lets engineers execute code only when a specified condition is true, using indentation to define which statements belong to that condition.
âś… Example 1: Simple True Condition
This example shows the most basic if statement that always runs because the condition is explicitly True.
if True:
print("This will always run")
📤 Output: This will always run
âś… Example 2: Checking a Numeric Condition
This example demonstrates an if statement that checks whether a number meets a comparison condition.
speed = 55
if speed > 50:
print("You are going fast")
📤 Output: You are going fast
âś… Example 3: Condition That Evaluates to False
This example shows that when the condition is false, the indented code block is skipped entirely.
temperature = 30
if temperature > 100:
print("Water is boiling")
print("This line always runs")
📤 Output: This line always runs
âś… Example 4: Multiple Statements Inside One If Block
This example shows that all indented lines after the if statement belong to the same condition block.
engine_status = "running"
if engine_status == "running":
print("Engine is active")
print("Check oil pressure")
print("Monitor temperature")
print("End of check")
📤 Output: Engine is active
Check oil pressure
Monitor temperature
End of check
✅ Example 5: Practical Engineer Check — Temperature Alert
This example uses a real-world engineering scenario to decide whether to issue an alert based on a sensor reading.
coolant_temp = 105
if coolant_temp > 100:
print("WARNING: Coolant temperature exceeds 100°C")
print("Reduce engine load immediately")
print("Check cooling system")
📤 Output: WARNING: Coolant temperature exceeds 100°C
Reduce engine load immediately
Check cooling system
Comparison Table: Condition Outcomes
| Condition Result | Indented Code Runs? | Example Condition |
|---|---|---|
| True | Yes | if True: |
| False | No | if 5 > 10: |
| Variable equals value | Yes | if speed == 55: |
| Variable does not equal value | No | if temp != 30: |