- What the if statement is ā the simplest decision-making tool
- Syntax of if ā how to write conditional statements
- Indentation rules ā why indentation matters in Python
- Simple conditions ā using relational operators
- Multiple conditions ā using and, or, not
- Real-world examples ā even/odd, number comparison
- Common mistakes ā and how to avoid them
What is the if Statement?
The if statement is the simplest and most important decision-making tool in Python. It allows you to execute a block of code only when a certain condition is true. Think of it as a gatekeeper ā it checks a condition and decides whether to let the code pass through or skip it.
š” Key insight: The if statement is the foundation of all conditional logic in Python. Every other decision-making statement builds upon it. Master the if statement, and you've mastered the core of Python's control flow.
A programmer may have to make different choices. These choices execute different Python statements or parts of a script depending on certain conditions. The if statement is used for the conditional execution of statements. It decides whether a certain statement or block of statements will be executed or not ā if a given condition is true, then the statements or block of statements is executed; otherwise, it's skipped.
Syntax of if Statement
# Syntax of if Statement
if condition:
# Body of if
# Python statements to execute if condition is true
# Example
age = 18
if age >= 18:
print("You are eligible to vote!")
# Output: You are eligible to vote!
š Breaking it down: The if keyword is followed by a condition (an expression that evaluates to True or False). The condition is followed by a colon (:). The body of the if statement is indented (usually 4 spaces). Python evaluates the condition. If it's True, the indented code runs. If it's False, the indented code is skipped.
ā ļø Important: Python uses indentation to define blocks of code. All statements in the body of an if must be indented at the same level. This is different from many other languages that use curly braces {}.
Flowchart of if Statement
Let's visualize how the if statement works using a flowchart:
Flowchart:
āāāāāāāāāāāāāāā
ā START ā
āāāāāāāā¬āāāāāāā
ā¼
āāāāāāāāāāāāāāā
ā Condition ā āāāā Test the condition
ā (True?) ā
āāāāāāāā¬āāāāāāā
ā
True ā
ā¼
āāāāāāāāāāāāāāā
ā Execute ā
ā Body of if ā
āāāāāāāā¬āāāāāāā
ā
ā¼
āāāāāāāāāāāāāāā
ā END ā
āāāāāāāāāāāāāāā
What happens:
1. The flow enters the if statement
2. The condition is tested
3. If True ā body of if executes
4. If False ā body of if is skipped
5. Program continues with the next statement after if
Simple Condition Example
Let's look at a simple example that checks which number is smaller:
# Find the smaller of two numbers
p = 8
q = 6
if p < q: # Test condition
print(p, "is smaller than", q)
if q < p: # Test condition
print(q, "is smaller than", p)
# Output:
# 6 is smaller than 8
š Explanation: In this example, we used two separate if statements. The first condition p < q evaluates to False (8 is not less than 6), so its body is skipped. The second condition q < p evaluates to True (6 is less than 8), so its body executes and displays the output.
Even or Odd Example
This is a classic example that checks if a number is even or odd using the modulus operator:
# Python script to find if a number is even or odd
n = int(input("Enter Any Number: "))
if n % 2 == 0:
print(n, "is Even")
if n % 2 == 1:
print(n, "is Odd")
# Output:
# Enter Any Number: 5
# 5 is Odd
š Explanation:
1. n = int(input("Enter Any Number: ")) ā accepts user input and converts it to an integer.
2. if n % 2 == 0: ā checks if the remainder when divided by 2 is 0. If true, the number is even.
3. if n % 2 == 1: ā checks if the remainder is 1. If true, the number is odd.
4. Since 5 % 2 = 1, the second condition is true and "5 is Odd" is displayed.
Multiple Conditions
You can combine multiple conditions using logical operators ā and, or, and not:
# Using 'and' operator
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive!")
# Using 'or' operator
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("You can relax!")
# Using 'not' operator
is_raining = False
if not is_raining:
print("Go outside and enjoy!")
# Output:
# You can drive!
# You can relax!
# Go outside and enjoy!
š” Remember: When using multiple conditions, parentheses can make your code clearer: if (age >= 18) and (has_license):.
Common Mistakes to Avoid
ā Mistake 1: Using = instead of ==
This is the most common mistake in conditional statements!
# WRONG (assignment instead of comparison)
if x = 5: # This will cause a SyntaxError!
print("x is 5")
# CORRECT (comparison)
if x == 5:
print("x is 5")
ā Mistake 2: Missing Colon
Every if statement needs a colon at the end.
# WRONG
if x > 0 # Missing colon!
print("Positive")
# CORRECT
if x > 0:
print("Positive")
ā Mistake 3: Incorrect Indentation
Python relies on indentation to define code blocks. Inconsistent indentation causes errors.
# WRONG (inconsistent indentation)
if x > 0:
print("Positive") # IndentationError!
# CORRECT (consistent indentation)
if x > 0:
print("Positive")
Try It Yourself!
Experiment with the if statement directly in your browser. Modify the code and see the results in real time.
IF STATEMENT
========================================
1. SIMPLE IF
You can vote!
2. EVEN OR ODD
7 is odd
3. MULTIPLE CONDITIONS
10 is between 0 and 20
4. USER INPUT
ā Explore different if conditions!
š You've Mastered Python if Statement!
You understand the if statement, syntax, indentation, and how to use conditions. This is the foundation of all decision-making in Python!
Quick Quiz ā Test Your Knowledge
Let's see what you've learned about the if statement:
if statement?if statement is False?if 5 > 3: print("True")?if statement?and operator do in a condition?Frequently Asked Questions
š¤ What is the difference between = and ==?
= is the assignment operator used to assign values to variables. == is the equality operator used to compare two values. Using = in a condition causes a SyntaxError.
š§ Does Python require indentation in if statements?
if must be indented at the same level (usually 4 spaces). Inconsistent indentation causes errors.
š Can I have multiple if statements?
if statements to check different conditions independently. Each if is evaluated separately, and multiple blocks can execute if their conditions are true.
š Can I use logical operators in if conditions?
and, or, and not. For example: if age >= 18 and has_license:.
ā” What happens if the condition is True?
True, the indented block of code inside the if statement executes. After that, the program continues with the next statement after the if block.
šÆ Can I put another if inside an if?
if. The inner if only runs if the outer if condition is true. However, deep nesting can make code hard to read, so use it sparingly.
š Where to Go From Here
Now that you've mastered the if statement, here are the next topics to explore:
š The if-else Statement
Learn how to handle two-way decision making with if-else.
š The if-elif-else Ladder
Handle multiple conditions with the if-elif-else ladder.
š Nested if Statements
Master complex decision making with nested if statements.