The if Statement
Overview
The if statement is the foundation of decision-making in Python. You'll learn how to write basic conditional expressions that allow your program to perform actions only when specific conditions are true.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- What an if statement is: Understand how if statements let your program make decisions.
- How to write if statements: Master the syntax and structure of conditional code.
- When code runs: Learn when the code inside an if block executes.
- Proper indentation: Understand why indentation is crucial for if statements.
Why This Matters
The if statement is one of the most important concepts in programming. It lets your program decide what to do based on conditions. Without if statements, every program would do exactly the same thing every time. With if statements, your programs can adapt and respond to different situations.
Step 1: What Is an if Statement?
An if statement lets your program check a condition and run code only if that condition is True. Think of it like a question: "If this is true, then do that." It's like making a decision in real life: "If it's raining, bring an umbrella."
if condition:
# code to run if condition is True
print("Condition is true!")
Start with if
The keyword if tells Python you're starting a conditional statement. It's like saying "if this happens..."
Write the Condition
After if, write a condition that evaluates to True or False. This can be a comparison (like age >= 18), a boolean variable (like is_student), or a logical expression (like age >= 18 and has_license).
Add a Colon
End the condition line with a colon :. This tells Python that the code block is coming next. The colon is required - without it, Python will give you an error.
Indent the Code Block
All code that should run when the condition is True must be indented. Python uses indentation to know what belongs to the if statement. Typically, you use 4 spaces for indentation.
Important: The colon : after the condition is required. Without it, Python will give you a syntax error. Also, remember that indentation matters — all code inside the if block must be indented consistently. If you mix spaces and tabs, or have inconsistent indentation, Python will give you an error.
Mini Practice #1: Your First if Statement
Try It YourselfTry this simple if statement. Notice how it only prints when the condition is True:
What happened? Python first evaluated the condition age >= 18. Since age is 20, and 20 is greater than or equal to 18, the condition evaluated to True. When the condition is True, Python enters the if block and executes all the indented code inside it. That's why "You are an adult!" was printed. If you change age to 15, the condition would be False (15 is not >= 18), so Python would skip the entire if block and nothing would print. This is how if statements make decisions: they only run code when the condition is True.
Step 2: How if Statements Work
Python evaluates the condition after if. If it's True, Python runs all the indented code. If it's False, Python skips the entire block and continues with the rest of your program. This is called "conditional execution" - code only runs under certain conditions.
When Condition Is True
All indented code runs. Python executes every line inside the if block, one after another.
age = 20
if age >= 18:
print("Adult")
print("Can vote")
Output: Adult
Can vote
Both print statements run because the condition is True
When Condition Is False
Python skips the entire if block. Your program continues after the if statement with the next non-indented line.
age = 15
if age >= 18:
print("Adult")
print("Can vote")
print("Program continues")
Output: Program continues
The if block is skipped, but the last print runs
Control Flow with if Statements
When Python encounters an if statement, it evaluates the condition. If True, it enters the if block and runs all indented code. If False, it jumps over the entire block and continues with the next non-indented line. This is how your program can take different paths based on conditions.
Step 3: Types of Conditions
You can use any expression that evaluates to True or False as a condition in an if statement. This gives you flexibility in how you write your conditions:
# Comparison operators
if age >= 18:
print("Adult")
# Boolean variables
if is_student:
print("Student discount")
# Logical expressions
if age >= 18 and has_license:
print("Can drive")
# Direct boolean values
if True:
print("This always runs")
Key Concept: Any expression that can be True or False can be used as a condition. This includes comparisons (like age >= 18), boolean variables (like is_student), logical expressions (like age >= 18 and has_license), and even direct boolean values (though if True: always runs and if False: never runs, so they're not very useful).
Mini Practice #2: Different Conditions
Try It YourselfTry different types of conditions. Notice how each one behaves:
What happened? Python evaluated the first if statement: temperature > 80. Since temperature is 85, and 85 is greater than 80, this condition is True, so "It's hot!" was printed. Then Python moved to the second if statement: not is_raining. Since is_raining is False, and not False equals True, this condition is also True, so "Perfect weather!" was printed. Notice that each if statement is evaluated independently - they don't affect each other. Try changing temperature to 70 or is_raining to True to see how the output changes based on the conditions.
Step 4: Indentation Is Critical
Python uses indentation to determine which code belongs to the if statement. All code inside an if block must be indented at the same level. Typically, you use 4 spaces for indentation. This is different from many other programming languages that use braces {} or keywords like end.
age = 20
if age >= 18:
print("Adult") # 4 spaces - inside if block
print("Can vote") # 4 spaces - inside if block
print("Done") # No indentation - outside if block
age = 20
if age >= 18:
print("Adult") # ERROR: Not indented!
# Python will give you an IndentationError
Remember: After the colon :, you must indent the next line. Python will give you an error if you forget to indent code that should be inside the if block. All code at the same logical level must have the same indentation - don't mix spaces and tabs!
Step 5: Real-World Example
Here's a practical example of using if statements in a real program:
score = 85
if score >= 90:
print("Grade: A")
print("Excellent work!")
if score >= 80:
print("Grade: B")
print("Good job!")
if score >= 70:
print("Grade: C")
print("Keep practicing!")
Multiple if Statements
You can have multiple if statements in a row. Each one is evaluated independently. In the example above, if score is 85, both the "Grade: B" and "Grade: C" messages would print because both conditions are True (85 >= 80 is True, and 85 >= 70 is also True). This is different from using elif, which we'll learn about in the next lesson.
End-of-Lesson Exercises
Exercise 1: Write an if Statement
Create a variable age = 20. Write an if statement that checks if age >= 18, and if true, prints "You are an adult!".
Use if age >= 18: followed by an indented print statement.
Exercise 2: Multiple Conditions
Create variables: temperature = 85 and is_summer = True. Write an if statement that prints "It's hot!" if temperature > 80 AND is_summer is True.
Use the and operator to combine conditions in your if statement.