Back to Python Notes
Topic #216

Python If

Learn how to control program flow by executing specific code blocks only when a condition evaluates to True.

What it is

The if statement is the fundamental building block of decision-making in Python. It allows your program to branch: if a specified condition is true, the indented block of code following it runs; otherwise, it is skipped. This mechanism relies on boolean logic, where expressions evaluate to either True or False. Related concepts include elif (else if) for checking multiple conditions and else for catching all remaining cases.

Why it matters

  • Data Validation: Ensures user input meets requirements before processing.
  • Error Handling: Checks for edge cases like division by zero or empty lists.
  • Game Logic: Determines win/loss states based on player scores or moves.
  • Filtering: Selects specific items from a dataset that match criteria.
  • State Management: Updates variables differently depending on current system status.

Syntax or steps

The basic structure requires three elements: the keyword if, a condition ending with a colon :, and an indented block of code. Python uses indentation (typically 4 spaces) to define scope, not curly braces.

if condition:
    # Code to run if condition is True

You can extend this with elif and else clauses to handle mutually exclusive scenarios.

Example

Consider a simple temperature checker that categorizes weather conditions.

temperature = 15

if temperature > 30:
    print("It is hot.")
elif temperature > 20:
    print("It is warm.")
elif temperature > 10:
    print("It is cool.")
else:
    print("It is cold.")

Explanation:

  1. temperature = 15: Initializes the variable.
  2. if temperature > 30:: Checks if it's hot. Since 15 is not greater than 30, this block is skipped.
  3. elif temperature > 20:: Checks if it's warm. Since 15 is not greater than 20, this block is skipped.
  4. elif temperature > 10:: Checks if it's cool. Since 15 is greater than 10, this condition is True.
  5. print("It is cool."): Executes because the previous condition was met.
  6. The final else block is ignored because a prior condition was satisfied.

Common mistakes

  • Missing Colon: Forgetting the : at the end of the if line causes a SyntaxError.
  • Inconsistent Indentation: Mixing tabs and spaces or failing to indent the body correctly leads to IndentationError.
  • Assignment vs. Comparison: Using = instead of == inside the condition assigns a value rather than comparing them, often resulting in unexpected behavior or errors.
  • Unreachable Code: Placing a broad condition (like else) before specific ones prevents the specific checks from ever running.

When to use it

Use if statements for binary decisions or small sets of mutually exclusive branches. For complex routing based on many discrete values, consider alternatives.

Scenario Recommended Approach
Checking ranges (e.g., grades) if / elif / else
Matching exact strings/integers match-case (Python 3.10+)
Simple one-line assignment Ternary operator (x if cond else y)

Practice

Guided Exercise: Write a script that takes a number n and prints "Even" if divisible by 2, otherwise "Odd". Use the modulo operator %.

Challenge: Extend the exercise to check if the number is also positive. Print "Positive Even", "Negative Even", etc.

Hint: Combine conditions using and or nest if statements.

Quick check

Q: What happens if the condition in an if statement evaluates to False?

A: The indented block of code immediately following the if is skipped entirely, and execution continues with the next line after the block (or the next elif/else).

Summary

The if statement enables dynamic behavior by executing code based on runtime conditions. Mastering proper syntax, including colons and indentation, along with logical operators, is essential for writing robust and readable Python programs.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Python If – FAQs

Quick answers about learning Python If in Python.

This free note from Coding Now Tech Institute explains Python If in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Python If, is 100% free with no signup required.
With focused practice, most students grasp Python If in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now