If staments
Learn about If staments in COS 102. Comprehensive study materials and practice questions.
Study Notes
COS 102COS102: Problem Solving Using Python - IF Statements & Logic
Learning Outcomes
- Explain decision making in programming.
- Understand the `if`, `elif`, and `else` logic.
- Use relational operators correctly (`==`, `>`, `<=`).
- Identify and fix common syntax & indentation errors.
- Develop programs that respond to user input.
Daily Decision Making & Programming Logic
Just like humans make daily decisions based on questions (e.g., "Am I hungry?"), computers need rules to choose what to do next. This is called decision making in programming.
Real-World Logic Examples:
- Traffic Light:
- Condition: Is light Green?
- Action: If Yes → Move. If No → Stop.
- ATM Transaction:
- Condition: PIN correct?
- Action: If Yes → Give Cash. If No → Reject.
Binary Choices (True/False)
Decision making is a computer's ability to choose an action based on a Boolean result (True or False). In Python, the if keyword initiates this process.
The "If" Syntax
The basic structure for conditional execution:
if score >= 50:
print("Pass")
- Keyword: Starts with
if. - The Colon: Must end with `:`.
- Indentation: The "action" (code block) must be spaced in (typically 4 spaces) to indicate it belongs to the `if` statement.
Visualizing the Flow (Flowchart Logic)
When an `if` statement is encountered:
- Step 1: Ask the question (Condition).
- Step 2: Check the answer (evaluates to True or False).
- YES (True): Run the indented code block.
- NO (False): Skip the indented code entirely.
The "Else" Clause (The Backup)
The else clause provides a backup plan when the `if` condition is False.
if score >= 50:
print("Pass")
else:
print("Fail")
Think of it: "If the ID is valid, open gate. Else, sound the alarm."
The "Elif" (Multiple Choices)
Use elif (short for "else if") when you have more than two options.
if score >= 70:
print("Grade: A")
elif score >= 60:
print("Grade: B")
else:
print("Grade: C")
Python checks these conditions one by one until it finds a True one. Once a True condition is found, its associated code block is executed, and the rest of the `elif`/`else` chain is skipped.
Relational Operators
These operators are used to compare values and return a Boolean result (True or False).
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal To | 5 == 5 |
True |
!= |
Not Equal To | 5 != 4 |
True |
>= |
Greater than or Equal | 18 >= 18 |
True |
< |
Less than | 10 < 5 |
False |
> |
Greater than | ||
<= |
Less than or Equal |
Code Examples
- ATM Security Check: Comparing `entered_pin` to `stored_pin`.
- Password Comparison: Checking if `pwd` matches "python123".
- Multi-way Logic (Weather): Using `if`, `elif`, `else` to describe weather based on temperature.
Common Mistakes
-
Mistake #1: `=` vs. `==`
=is for Assignment (giving a value).==is for Comparison (checking if two values are equal).
WRONG ❌:
if age = 18:CORRECT ✅:
if age == 18: -
Mistake #2: Colon & Indent
- The Colon: Missing the colon at the end of `if`, `elif`, or `else` statement. (e.g.,
if score > 50← Error! Missing :) - Indentation: Not indenting the code block belonging to the conditional statement. Python uses whitespace to define code blocks.
WRONG:
if score > 50: print("Pass") # Error! Not IndentedCORRECT:
if score > 50: print("Pass") - The Colon: Missing the colon at the end of `if`, `elif`, or `else` statement. (e.g.,
Key Takeaways
- Decision making depends on Conditions (True/False).
- Use
if,elif, andelsefor multiple paths. - Always include the Colon (
:) and proper Indentation. ==compares,=assigns.
What's Next? (Chapter 14: Processing Data)
We will learn about:
- Counting & Summing items
- Swapping variables
- Using Flag variables
Happy Coding!