Fundamentals of Conditional Logic Review
From the advanced conditional srtuctures curriculum
Fundamentals of Conditional Logic Review
TL;DR
Conditional logic lets your programs make decisions by executing different code blocks based on whether a statement is true or false. It's the cornerstone of dynamic behavior, allowing your software to respond intelligently to various inputs and situations. Mastering conditionals is essential for building any useful and interactive application.
1. The Mental Model
Think of conditional logic as asking "if this, then that." You're giving your program a specific question to evaluate, and based on the answer (true or false), it follows a different path. It's like a fork in the road for your code.
2. The Core Material
What is a Condition?
A condition is a statement that can only be evaluated as either true or false. These are often called Boolean expressions. You use comparison operators to create these conditions.
==(equal to): Isxequal toy?!=(not equal to): Isxnot equal toy?>(greater than): Isxgreater thany?<(less than): Isxless thany?>=(greater than or equal to): Isxgreater than or equal toy?<=(less than or equal to): Isxless than or equal toy?
Basic if Statements
The simplest conditional structure, an if statement executes a block of code only if its condition is true.
score = 85
if score >= 70:
print("You passed the exam!")
if-else Statements
When you want to execute one block of code if a condition is true and a different block if it's false, you use an if-else statement.
temperature = 22
if temperature > 25:
print("It's hot outside!")
else:
print("It's not too hot.")
if-elif-else Statements (Chained Conditionals)
For multiple possible conditions, you use elif (short for "else if"). The program checks conditions in order, executing the first code block whose condition is true, then skipping the rest. The else block acts as a catch-all if none of the preceding if or elif conditions are met.
grade = 88
if grade >= 90:
print("You got an A!")
elif grade >= 80:
print("You got a B!")
elif grade >= 70:
print("You got a C.")
else:
print("You need to study more.")
Logical Operators
You can combine multiple conditions using logical operators:
and: Both conditions must be true.or: At least one condition must be true.not: Reverses the truth value of a condition.
age = 20
has_license = True
if age >= 18 and has_license:
print("You can drive.")
if age < 18 or not has_license:
print("You cannot drive yet (or need a license).")
3. Worked Example
Let's say you're building a simple program that recommends an activity based on the weather and time of day.
current_temperature_celsius = 15
is_raining = True
hour_of_day = 10 # 24-hour format
if hour_of_day < 6 or hour_of_day > 22:
print("It's late/early, maybe just relax at home.")
elif current_temperature_celsius < 10 and is_raining:
print("It's cold and wet! Stay inside with a hot drink.")
elif current_temperature_celsius < 18 and not is_raining:
print("It's a bit cool but not raining. A brisk walk might be nice.")
elif current_temperature_celsius >= 18 and not is_raining:
print("Nice weather! How about a picnic in the park?")
elif is_raining: # Catches all remaining cases where it's raining and not cold
print("It's raining, but not too cold. Read a book or watch a movie.")
else:
print("Hmm, I'm not sure what to suggest!")
# If current_temperature_celsius is 15, is_raining is True, hour_of_day is 10:
# 1. `hour_of_day < 6 or hour_of_day > 22` (10 < 6 is False, 10 > 22 is False) -> False
# 2. `current_temperature_celsius < 10 and is_raining` (15 < 10 is False, True) -> False
# 3. `current_temperature_celsius < 18 and not is_raining` (15 < 18 is True, not True is False) -> False
# 4. `current_temperature_celsius >= 18 and not is_raining` (15 >= 18 is False, not True is False) -> False
# 5. `is_raining` (True) -> True. This condition passes.
# Output: It's raining, but not too cold. Read a book or watch a movie.
4. Key Takeaways
- Conditional logic allows your program to execute different code paths based on a condition's truth value.
- You use comparison operators (
==,!=,<,>,<=,>=) to form conditions. - An
ifstatement executes code only if its condition is true. - Use
if-elsefor two distinct paths: one if true, one if false. - Use
if-elif-elsefor multiple exclusive conditions, checked in order. - Logical operators (
and,or,not) combine or modify conditions.
Common Mistakes to Avoid
- Using
=instead of==for comparison:=is for assignment,==is for checking equality. - Incorrect indentation: In Python, indentation defines code blocks; wrong indentation leads to errors or unexpected behavior.
- Thinking all
elifblocks will run: Only the first true condition's block in anif-elif-elsechain will execute. - Not covering all possible cases: Make sure your
elseor finalelifaccounts for all scenarios you expect, or don't. - Overly complex conditions: Break down complex conditions using logical operators or nest
ifstatements to improve readability.
5. Now Try It
Write a Python script that takes a user's numerical input (representing a score from 0-100) and prints out a corresponding letter grade: A (90-100), B (80-89), C (70-79), D (60-69), or F (0-59). Make sure to handle input that's outside the 0-100 range by printing an "Invalid score" message.
What success looks like: Your program correctly assigns the grade, including edge cases like 89 and 90, and flags invalid scores like -5 or 105.
Frequently asked about Fundamentals of Conditional Logic Review
Get the full advanced conditional srtuctures curriculum
Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.
Create Free Account