You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit eacd892
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: curriculum/01-foundations/07-if-statements.md
+63-56Lines changed: 63 additions & 56 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -5,90 +5,97 @@ sidebar_label: 7. If Statements
5
5
sidebar_position: 7
6
6
---
7
7
8
-
#If Statements: The Fork in the Road
8
+
## Introduction (The "Why")
9
9
10
-
In a real-world ledger, you don't treat every entry the same way. If an account is overdrawn, you flag it. If a payment is massive, you verify it. In Python, we use **Conditional Statements** (`if`, `elif`, and `else`) to control the flow of our program.
10
+
Imagine building an automated ledger system that processes thousands of transactions a minute. If a transaction amount is standard, it passes right through. But what if a user attempts to withdraw more money than they possess, or tries to execute a multi-million dollar transfer? If your code treats every single line of data exactly the same way, your system will either crash or allow fraudulent activity.
11
11
12
+
In programming, we cannot rely on linear execution where every line of code runs sequentially from top to bottom. We need our code to make decisions at runtime based on dynamic data. Python solves this using **Conditional Statements** (`if`, `elif`, and `else`), which act as the decision-making forks in your program's execution path.
12
13
14
+
---
13
15
14
-
### The Basic `if` Statement
15
-
The structure of an `if` statement is simple but strict. You provide a condition, followed by a **colon** (`:`). The code that follows must be **indented** (usually 4 spaces).
16
-
17
-
```python interactive
18
-
balance =100
19
-
20
-
if balance >0:
21
-
print("Account is in good standing.")
22
-
```
16
+
## Learning Outcomes
23
17
24
-
### Adding an `else`
25
-
What happens if the condition is `False`? We use the `else` block to provide a backup plan.
18
+
By the end of this lesson, you will confidently be able to:
19
+
***Explain** how Python evaluates conditions to boolean values (`True` or `False`) to determine execution flow.
***Implement** multi-branched decision pathways using nested and chained `if`, `elif`, and `else` logic.
22
+
***Analyze** the performance implications of conditional ordering (short-circuiting logic).
26
23
27
-
```python interactive
28
-
balance =-50
24
+
---
29
25
30
-
if balance >0:
31
-
print("Account is in good standing.")
32
-
else:
33
-
print("WARNING: Negative balance detected!")
34
-
```
26
+
## Conceptual Overview
35
27
36
-
---
28
+
Under the hood, conditional statements are controlled by **control flow branching**.
37
29
38
-
### The `elif` (Else If)
39
-
Sometimes you have more than two options. For example, a ledger might have "Positive," "Zero," and "Negative" states. We use `elif` to check multiple specific conditions in order.
40
30
41
-
```python interactive
42
-
balance =0
43
-
44
-
if balance >0:
45
-
print("Profit detected.")
46
-
elif balance ==0:
47
-
print("Break even.")
48
-
else:
49
-
print("Loss detected.")
50
31
```
32
+
[ Evaluate Condition ]
33
+
/
34
+
True / \ False
35
+
v v
36
+
[ Execute Block ] [ Skip Block / Check Next ]
37
+
```
38
+
39
+
When Python encounters an `if` statement, it evaluates the expression next to it. This expression *must* resolve to a boolean value: either `True` or `False`.
51
40
52
-
### ⚠️ The Golden Rule: Indentation
53
-
In Python, indentation isn't just for looks—it's part of the grammar. Everything indented under the `if` statement "belongs" to that decision. If you forget to indent, Python will throw an `IndentationError`.
41
+
### Memory and the Execution Context
42
+
Unlike some languages that use curly braces `{}` to define scope, Python relies entirely on **indentation** (whitespace) to define execution blocks. When a condition evaluates to `True`, the interpreter steps *into* the indented block of code and creates a localized execution context for those statements. If the condition evaluates to `False`, the interpreter physically skips past that entire indented block in memory, jumping directly to the next unindented line of code.
54
43
44
+
Because of this, incorrect indentation isn't just a stylistic issue—it changes the actual structural logic of your program, leading to either an immediate `IndentationError` or silent logical bugs where code runs under the wrong conditions.
55
45
46
+
### The Chained Evaluation Pipeline
47
+
When chaining conditions with `if`, `elif`, and `else`, Python evaluates them sequentially from **top to bottom**:
48
+
1.**The `if` statement** is always evaluated first.
49
+
2.**The `elif` (else-if) statements** are evaluated sequentially *only if* all preceding conditions evaluated to `False`. The moment one `elif` evaluates to `True`, its block runs, and Python skips the rest of the chain entirely.
50
+
3.**The `else` statement** acts as a catch-all. It has no condition of its own and executes *only* if every single preceding condition in the chain evaluated to `False`.
56
51
57
52
---
58
53
59
-
### 🏆 The Ledger Challenge: The Security Gate
60
-
You are writing a login check for **The Python Ledger** database.
54
+
## Assignments
61
55
62
-
**Task:**
63
-
1. Create a variable `username` and set it to a string.
64
-
2. Create a variable `is_admin` and set it to a Boolean.
65
-
3. Write an `if/elif/else` structure:
66
-
***IF** the `username` is "Admin" **AND**`is_admin` is `True`, print: "Full Access Granted."
67
-
***ELIF** the `username` is "Admin" but `is_admin` is `False`, print: "Admin access denied. Check permissions."
68
-
***ELSE**, print: "Standard User Access Granted."
56
+
To understand how Python evaluates conditions under the hood, read the following resources. Focus your energy on the specified sections:
69
57
70
-
**Write your code below:**
58
+
1.**[Python Official Docs: More Control Flow Tools](https://docs.python.org/3/tutorial/controlflow.html)**
59
+
**Focus Area:* Read Section 4.1 closely. Pay attention to how `if`, `elif`, and `else` chain together.
60
+
2.**[Real Python: Conditional Statements in Python](https://realpython.com/python-conditional-statements/)**
61
+
**Focus Area:* Read the sections on "Grouping Statements: Indentation and Blocks" and "The `elif` Clause". Understand how Python groups statements using indentation levels.
62
+
3.**[Python Official Docs: Truth Value Testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)**
63
+
**Focus Area:* Study the "Truth Value Testing" section. Learn which built-in Python objects naturally evaluate to `False` (implicitly falsy) and which evaluate to `True`.
71
64
72
-
```python interactive
73
-
# 1. Define your variables
65
+
---
74
66
67
+
## Knowledge Checks
75
68
76
-
# 2. Build your security logic
69
+
Before writing any code, you must be able to confidently answer the following questions. Utilize the assigned readings above to discover these answers:
77
70
78
-
```
71
+
1. What is the difference between an implicit truth value (truthy/falsy) and an explicit boolean value (`True`/`False`) in a Python conditional statement? Which objects in Python naturally evaluate to `False`?
72
+
2. If an `if` statement evaluates to `True` and executes its block, will any of the subsequent `elif` blocks in that same chain be evaluated? Why or why not?
73
+
3. How does Python's execution environment distinguish between a nested `if` statement (an `if` inside another `if`) and a chained `elif` statement?
79
74
80
75
---
81
76
82
-
<details>
83
-
<summary>📚 Deep Dive</summary>
77
+
## 🏆 The Ledger Challenge: The Security Gate
84
78
85
-
Official python documentation:
86
-
*[Python Docs: More Control Flow Tools](https://docs.python.org/3/tutorial/controlflow.html)
79
+
You are writing a secure gateway checkpoint for **The Python Ledger** database.
80
+
81
+
### Task
82
+
Write an authentication check using an `if/elif/else` structure:
83
+
1. Create a variable named `username` and set it to a string of your choice.
84
+
2. Create a variable named `is_admin` and set it to a Boolean value.
85
+
3. Build a conditional structure that evaluates these variables:
86
+
***IF** the `username` is `"Admin"`**and**`is_admin` is `True`, print: `"Full Access Granted."`
87
+
***ELIF** the `username` is `"Admin"` but `is_admin` is `False`, print: `"Admin access denied. Check permissions."`
88
+
***ELSE**, print: `"Standard User Access Granted."`
89
+
90
+
> 💡 **Documentation Hunting Tip:** Look at the assignment links regarding logical operators. You will need to combine two checks in your first conditional block. Look up how Python uses the `and` operator to combine multiple boolean conditions into a single evaluation.
91
+
92
+
```python interactive
93
+
# 1. Define your variables (Change these to test different pathways)
94
+
username ="Admin"
95
+
is_admin =False
87
96
88
-
Other resources:
89
-
*[Real Python: Conditional Statements in Python](https://realpython.com/python-conditional-statements/)
97
+
# 2. Build your security logic below using if, elif, and else
90
98
91
-
</details>
92
99
93
100
## Next Steps
94
-
Congratulations! You've mastered the basics of logic. You are now ready for your first **Project**. We will be building a text-based adventure right inside our browser terminal.
101
+
Now that you've mastered how to branch your execution path using single-variable logic, we are going to supercharge our decisions. In the next lesson, we'll explore **Logical Operators** (and, or, not) to construct sophisticated, multi-layered logical expressions.
0 commit comments