3Lesson 3 of 5

Conditions & Decision Making

Learn how to make your programs make decisions using if, elif, and else statements.

Real programs need to make decisions. Should we show an error message? Is the user logged in? Is the number positive? In this lesson, you will learn how to use conditional statements to control the flow of your program based on different conditions.

The if Statement

The if statement executes code only when a condition is True. The syntax is: if condition: followed by indented code. Python uses indentation (usually 4 spaces) to define code blocks. For example: if temperature > 30: print('It is hot today!')

Adding else for Alternatives

Often you want to do one thing if a condition is true, and something else if it's false. The else clause handles the 'otherwise' case: if age >= 18: print('You can vote') else: print('Too young to vote')

Multiple Conditions with elif

When you have more than two possibilities, use elif (else if) to check additional conditions. Python checks each condition in order and executes the first one that's True: if score >= 90: grade = 'A' elif score >= 80: grade = 'B' elif score >= 70: grade = 'C' else: grade = 'F'

Combining Conditions

You can combine multiple conditions using logical operators: 'and' (both must be true), 'or' (at least one must be true), and 'not' (inverts the condition). For example: if age >= 18 and has_license: print('You can drive')

Key Takeaways

  • if statements execute code when conditions are True
  • else handles the alternative when conditions are False
  • elif allows checking multiple conditions in sequence
  • and, or, not combine conditions for complex logic