Web Analytics

If Statements

Beginner ~20 min read

Conditional statements let your program make decisions! The if statement is the cornerstone of control flow - it executes code only when a specific condition is true, allowing your programs to respond dynamically to different situations.

The Basic if Statement

The if statement executes a block of code only when the condition evaluates to True. Python uses indentation to define the code block.

Output
Click Run to execute your code
Indentation Matters! Python uses indentation (typically 4 spaces) to define code blocks. All lines with the same indentation after an if statement belong to that block. This is different from languages that use braces {}.

The if...else Statement

Add an else clause to handle the case when the condition is False. Either the if block OR the else block will execute - never both!

Output
Click Run to execute your code
Pro Tip: You can check if a list is empty by using it directly as the condition: if my_list: is True when the list has items, False when empty. This works for strings, dicts, and other collections too!

The if...elif...else Chain

Use elif (short for "else if") when you have multiple conditions to check. Python evaluates conditions from top to bottom and executes only the FIRST matching block.

Output
Click Run to execute your code
Order Matters! In an if-elif chain, conditions are checked top to bottom. Once a condition is True, the rest are skipped. Put more specific conditions before general ones: check score >= 90 before score >= 80.

Nested If Statements

You can place if statements inside other if statements for more complex decision trees. Each level adds another 4 spaces of indentation.

Output
Click Run to execute your code
Readability Tip: Deeply nested if statements (more than 3 levels) are hard to read. Consider using early returns, breaking into functions, or using and/or to combine conditions.

Truthy and Falsy Values

Python treats certain values as "falsy" (equivalent to False in a condition) and everything else as "truthy". This allows for cleaner condition checks!

Output
Click Run to execute your code

Common Mistakes

1. Using = instead of == in conditions

# Wrong - this is assignment, not comparison!
if x = 5:  # SyntaxError!
    print("x is 5")

# Correct - use == for comparison
if x == 5:
    print("x is 5")

2. Forgetting the colon

# Wrong - missing colon!
if age >= 18
    print("Adult")  # SyntaxError!

# Correct
if age >= 18:
    print("Adult")

3. Inconsistent indentation

# Wrong - mixed indentation!
if condition:
    print("Line 1")
  print("Line 2")  # IndentationError!

# Correct - consistent 4 spaces
if condition:
    print("Line 1")
    print("Line 2")

4. Comparing with True/False explicitly

# Not recommended
if is_valid == True:
    print("Valid")

# Better - cleaner and more Pythonic
if is_valid:
    print("Valid")

# For checking False, use 'not'
if not is_valid:
    print("Not valid")

Exercise: Grade Calculator

Task: Create a grading system that assigns letter grades based on scores.

Requirements:

  • 90-100: Grade "A"
  • 80-89: Grade "B"
  • 70-79: Grade "C"
  • 60-69: Grade "D"
  • Below 60: Grade "F"
Output
Click Run to execute your code
Show Solution
score = 75
grade = ""

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Score: {score}, Grade: {grade}")

Summary

  • if: Executes code block when condition is True
  • else: Executes when no preceding condition was True
  • elif: Checks additional conditions (can have multiple)
  • Indentation: Python uses 4 spaces to define code blocks
  • Colon: Every if/elif/else line must end with :
  • Falsy values: False, None, 0, "", [], {}, (), set()
  • Truthy: Everything else is considered True in conditions

What's Next?

Now that you can make decisions with if statements, let's learn about the ternary operator - a concise one-line way to write simple if-else expressions that's perfect for assigning values based on conditions!