Chapter 5 of 11
Making Decisions: Conditions and Branching Logic
Turn your programs from passive calculators into decision-makers that behave differently depending on the situation. With conditions, your code can react to user input, compare values, and choose the right path automatically.
Making Decisions: Why Programs Need Choices
Why Programs Need Choices
So far, your Python programs mostly follow one straight path: line 1, then line 2. Real programs often need to choose what to do, like checking a password or deciding if a player won a game.
What Is a Condition?
A condition is a question that can be answered with True or False. Depending on the answer, your program can branch and run different code paths.
What You Will Learn
You will learn if, elif, else, comparison and logical operators, correct indentation, and how to build scripts that react to user input using branching logic.
Comparison Operators: Asking Yes/No Questions
Comparison Operators
Comparison operators let you compare values. They always return True or False. They are the base of conditions in Python.
Common Operators
`==` equal, `!=` not equal, `<` less than, `>` greater than, `<=` less than or equal, `>=` greater than or equal.
Examples
`5 == 5` is True, `3 != 4` is True, `7 < 2` is False, `10 >= 10` is True. You can also compare variables like `age >= 18`.
Try It: Simple Comparisons in Python
Run this code in a Python shell or an online editor. Read the output and see which expressions are True or False.
```python
print(5 == 5)
print(3 != 4)
print(7 < 2)
print(10 >= 10)
age = 15
print("Is age at least 18?", age >= 18)
name = "Alex"
print("Is the name Sam?", name == "Sam")
```
If Statements and Indentation
Basic If Statement
An if statement lets your program choose what to run. It has `if`, a condition, a colon, and an indented block of code underneath.
Example With Age
```python
age = 16
if age >= 18:
print("You can vote.")
print("Program finished.")
``` If age >= 18 is True, the message prints; otherwise it is skipped.
Why Indentation Matters
Indentation (spaces at the start of a line) shows which lines belong to the if. Python uses this instead of braces. Wrong indentation can cause errors or wrong behavior.
If, Else, and Elif: Multiple Paths
If and Else
Use if and else when you want one thing if a condition is True and another if it is False. Only one of the two blocks will run.
If/Else Example
```python
temperature = 30
if temperature > 25:
print("It is warm outside.")
else:
print("It is not very warm.")
```
Elif for More Options
Use elif (else if) when you have several different conditions. Python checks them from top to bottom and runs the first one that is True.
Grading Example
```python
score = 82
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D or below")
```
Thought Exercise: Predict the Output
Read the code and predict what it will print before you run it.
```python
age = 13
if age >= 18:
print("Adult ticket")
elif age >= 13:
print("Teen ticket")
else:
print("Child ticket")
print("Done")
```
- Which condition is True?
- `age >= 18`
- `age >= 13`
- Which `print` line will run inside the if/elif/else chain?
- What is the full output, line by line?
After you decide, run the code in Python and check your answers. If you were wrong, look back at the order of the conditions and how `elif` works.
Logical Operators: Combining Conditions
Why Combine Conditions?
Sometimes one condition is not enough. You might want to check two things at once, like age and permission, or weather and time.
Logical Operators
`and` means both conditions must be True. `or` means at least one must be True. `not` flips True to False and False to True.
Example With and/or/not
```python
age = 17
has_permission = True
if age >= 16 and has_permission:
print("You can drive with permission.")
```
Not Example
```python
is_raining = False
if not is_raining:
print("You do not need an umbrella.")
```
Mini Project: Simple Menu-Based Calculator
Here is a small script that uses `if`, `elif`, and `else` to choose an operation based on user input.
```python
print("Simple Calculator")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
choice = input("Choose an option (1, 2, or 3): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == "1":
result = num1 + num2
print("Result:", result)
elif choice == "2":
result = num1 - num2
print("Result:", result)
elif choice == "3":
result = num1 * num2
print("Result:", result)
else:
print("Invalid choice.")
```
Try changing the menu to add division as option 4. Remember to handle the case where `num2` is 0 before dividing.
Check Understanding: If/Elif/Else and Logic
Answer this question to test your understanding of branching logic.
What will this code print? ```python age = 20 has_id = False if age >= 18 and has_id: print("You may enter.") elif age >= 18 and not has_id: print("You are old enough, but need ID.") else: print("You may not enter.") ```
- You may enter.
- You are old enough, but need ID.
- You may not enter.
Show Answer
Answer: B) You are old enough, but need ID.
age >= 18 is True, but has_id is False. The first if uses `and` and needs both True, so it is skipped. The elif checks `age >= 18 and not has_id`, which is True, so it prints "You are old enough, but need ID.".
Review Key Terms: Conditions and Branching
Use these flashcards to review the main ideas from this module.
- Condition
- An expression that can be either True or False, such as `age >= 18` or `password == "abc"`.
- If statement
- A structure that runs a block of code only if its condition is True.
- Elif
- Short for else if. Used after an if to check another condition if previous ones were False.
- Else
- The block that runs if all previous if/elif conditions in the chain are False.
- Indentation
- Spaces at the start of a line that show which lines belong to a block, such as inside an if statement.
- Comparison operators
- Operators like `==`, `!=`, `<`, `>`, `<=`, `>=` that compare values and return True or False.
- Logical operators
- `and`, `or`, and `not`, which combine or modify conditions to create more complex True/False expressions.
Key Terms
- elif
- Short for else if. Used to test another condition if the previous if or elif was False.
- else
- The final part of an if chain that runs if no previous condition was True.
- branching
- The idea that a program can follow different paths of execution depending on conditions.
- condition
- An expression that evaluates to True or False, used to decide which code should run.
- indentation
- Spaces at the beginning of a line that group lines into blocks in Python (commonly 4 spaces per level).
- if statement
- A Python structure that runs an indented block of code only when its condition is True.
- logical operator
- An operator (and, or, not) used to combine or flip conditions in Python.
- comparison operator
- An operator (==, !=, <, >, <=, >=) used to compare two values and produce True or False.