Chapters List
- A Mental Model for Programming
- What Happens When a Program Runs
- Programming Languages
- Variables and Data
- Decisions: Conditional Logic
- Repetition: Loops
- Functions: Building Reusable Code
- Data Structures: Organizing Information
- Debugging: Fixing Programs
- How Programs Become Real Software
- Different Types of Programming
- Modern Programming and Software Development
programming
Decisions: Conditional Logic
Learn how programs use conditions and branching to choose different behaviors.
In the previous chapter we learned how programs store values.
But storing data is only part of the story.
Programs also need to make choices.
Why Decisions Are Necessary
Real software is full of branching behavior.
Examples:
- if password is correct, allow login
- if stock is unavailable, show error
- if user is admin, show extra controls
Without conditional logic, programs would follow only one fixed path.
Boolean Conditions
A condition evaluates to either:
truefalse
Conditions are usually built from comparisons:
==equal to!=not equal to<,>,<=,>=
Example:
temperature = -2
if temperature < 0:
wear_jacket = True
This is the exact idea: compare values, then choose behavior.
If, Else, and Branching
The most common structure:
if condition:
# run this block when condition is true
else:
# run this block otherwise
You can also chain multiple branches:
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
Visualizing Branches
graph TD
A[Check Condition] --> B{True?}
B -->|Yes| C[Run Branch A]
B -->|No| D[Run Branch B]
At runtime, only one branch is executed for each decision point.
Combining Conditions
Programs often combine multiple checks:
and: both must be trueor: at least one truenot: flips true/false
Example:
if is_logged_in and has_permission:
show_dashboard = True
This is how programs express more realistic rules.
Common Beginner Mistakes
- confusing assignment (
=) with comparison (==) - forgetting edge cases
- writing deeply nested conditions that are hard to read
A practical habit is to test with several inputs, including boundary values.
Key Ideas to Remember
- Conditional logic allows programs to choose behavior.
- Conditions evaluate to true or false.
if/elif/elsestructures create program branches.- Combined logical operators model real-world rules.
- Testing different inputs is essential for reliable decisions.
What Comes Next
Conditions choose between paths.
Now we need a second core control structure:
repetition with loops, so programs can automate repeated tasks.