π Exercise Four: Conditional Expressions and Flow Control
As you know, computers basically work off of "Boolean" logicβtrue/false values represented electronically by signals being either on or off. Real computer programming starts when you learn to manipulate these signals to control the flow of logic through a program.
- Boolean constants
TrueandFalse - How to compare values using relational operators
- How to combine conditions using logical operators
- How to control program flow with
if,elif, andelsestatements
π― 1. Boolean Constants
Python contains two Boolean constants that represent the fundamental values of logic:
True and False are capitalized in Python! Writing true or false (lowercase) will cause an error.
# Boolean constants in action
is_sunny = True
is_raining = False
print(is_sunny) # Output: True
print(is_raining) # Output: False
print(type(is_sunny)) # Output: <class 'bool'>βοΈ 2. Relational (Comparison) Operators
It is often necessary to compare the values of two quantities. The result of a comparison is always a Boolean value: either True or False.
For example, the expression:
3 < 4would evaluate to True because 3 is indeed less than 4.
Python's Relational Operators
| Operator | Description | Example (with 3 and 4) | Result |
|---|---|---|---|
== |
Are operands equal? | 3 == 4 |
False |
!= |
Are operands not equal? | 3 != 4 |
True |
> |
Is left operand greater than right? | 3 > 4 |
False |
< |
Is left operand less than right? | 3 < 4 |
True |
>= |
Is left operand greater than or equal to right? | 3 >= 4 |
False |
<= |
Is left operand less than or equal to right? | 3 <= 4 |
True |
= (assignment) with == (comparison)!
x = 5means "assign the value 5 to x"x == 5means "is x equal to 5?"
Examples of Comparisons
>>> 5 == 5
True
>>> 5 == 3
False
>>> 10 > 7
True
>>> 10 < 7
False
>>> 5 >= 5
True
>>> 5 != 5
Falseπ 3. Logical Operators
It is frequently necessary to combine multiple Boolean expressions together. Python provides three logical operators to do this: and, or, and not.
The Three Logical Operators
| Operator | Description | Example |
|---|---|---|
and |
Returns True only if both conditions are true |
(5 > 3) and (2 < 4) β True |
or |
Returns True if at least one condition is true |
(5 > 3) or (2 > 4) β True |
not |
Reverses the Boolean value | not(5 > 3) β False |
Truth Table
This table shows all possible combinations of two Boolean values A and B:
| A | B | A and B | A or B | not A | not B |
|---|---|---|---|---|---|
True |
True |
True |
True |
False |
False |
True |
False |
False |
True |
False |
True |
False |
True |
False |
True |
True |
False |
False |
False |
False |
False |
True |
True |
Complex Example
Consider this mathematical statement: "Is 3 less than 4 AND either 4 is not less than 2 OR 2 is greater than 3?"
In Python, this would be written as:
(3 < 4) and (not(4 < 2) or (2 > 3))Let's trace through this step by step:
3 < 4βTrue4 < 2βFalsenot(False)βTrue2 > 3βFalseTrue or FalseβTrueTrue and TrueβTrue
π¦ 4. Program Flow Control
The reason computer programs need these types of operators is so that expressions in a program can be executed only when specific conditions are met.
The if Statement
The if statement allows Python to execute code only when a condition is True:
A = 5
B = 3
if A > B:
print("A is greater than B")
print(A)5
In Python, indentation is not optionalβit's part of the syntax! All the code that should run when the if condition is true must be indented (typically 4 spaces). The indented block ends when you return to the original indentation level.
The if-else Statement
Use else to specify what happens when the condition is False:
age = 16
if age >= 18:
print("You are an adult")
print("You can vote!")
else:
print("You are a minor")
print("You cannot vote yet")You cannot vote yet
The if-elif-else Statement
Use elif (short for "else if") when you have multiple conditions to check:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")Example: First True Condition Wins
A = 5
B = 6
C = 7
if A < B:
print("first block")
elif (A < B) and (B < C):
print("second block")
else:
print("third block")Why only "first block"? Even though the second condition (A < B) and (B < C) is also true, Python already found a true condition in the first if, so it executes that block and skips the rest.
πͺ 5. Nested if Statements
You can put if statements inside other if statements. This is called nesting.
age = 25
has_license = True
if age >= 16:
print("You are old enough to drive")
if has_license:
print("You have a license - you can drive!")
else:
print("But you need to get a license first")
else:
print("You are too young to drive")You have a license - you can drive!
if statements can become very difficult to read and debug. If you find yourself nesting more than 2-3 levels deep, consider if you can simplify your logic using and/or operators or by restructuring your code.
π 6. Common Patterns
Pattern 1: Checking a Range
Is a number between two values?
temperature = 72
if temperature >= 65 and temperature <= 80:
print("The temperature is comfortable")
else:
print("The temperature is not comfortable")Pattern 2: Checking Multiple Conditions
Does any one of several conditions apply?
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
else:
print("It's a weekday")Pattern 3: Input Validation
Check if user input is valid before using it:
age = int(input("Enter your age: "))
if age < 0:
print("Error: Age cannot be negative!")
elif age > 150:
print("Error: That age seems unrealistic!")
else:
print("Your age is: " + str(age))Your age is: 25
π Complete Example: Simple Login System
# Simple login system
print("=== Login System ===")
print()
# The correct credentials (in a real program, these would be stored securely)
correct_username = "student"
correct_password = "python123"
# Get user input
username = input("Enter username: ")
password = input("Enter password: ")
# Check credentials
if username == correct_username and password == correct_password:
print()
print("Login successful!")
print("Welcome, " + username + "!")
elif username != correct_username:
print()
print("Login failed: Username not found")
else:
print()
print("Login failed: Incorrect password")Enter username: student
Enter password: python123
Login successful!
Welcome, student!
β οΈ Common Mistakes (And How to Fix Them)
Mistake 1: Using = Instead of ==
if x = 5: # ERROR! This is assignment, not comparison
print("x is 5")if x == 5: # Use == for comparison
print("x is 5")Mistake 2: Forgetting the Colon
if x > 5 # ERROR! Missing colon
print("x is greater than 5")if x > 5: # Don't forget the colon!
print("x is greater than 5")Mistake 3: Incorrect Indentation
if x > 5:
print("x is greater than 5") # ERROR! Not indentedif x > 5:
print("x is greater than 5") # Indented with 4 spacesMistake 4: Using true/false (Lowercase)
is_valid = true # ERROR! Python doesn't recognize lowercaseis_valid = True # Boolean constants are capitalizedMistake 5: Writing else if Instead of elif
if x > 10:
print("big")
else if x > 5: # ERROR! Python uses elif, not else if
print("medium")if x > 10:
print("big")
elif x > 5: # Use elif (one word)
print("medium")πͺ Practice Exercises
Try writing these programs on your own!
Exercise 1: Even or Odd
Write a program that:
- Asks the user to enter an integer
- Determines if the number is even or odd
- Prints the result
Hint: A number is even if number % 2 == 0
Exercise 2: Grade Calculator
Write a program that:
- Asks the user to enter a numerical score (0-100)
- Converts it to a letter grade (A: 90+, B: 80-89, C: 70-79, D: 60-69, F: below 60)
- Prints the letter grade
Exercise 3: Leap Year Checker
Write a program that determines if a year is a leap year:
- A year is a leap year if it's divisible by 4
- EXCEPT years divisible by 100 are NOT leap years
- EXCEPT years divisible by 400 ARE leap years
Examples: 2000 (leap), 1900 (not leap), 2024 (leap), 2023 (not leap)
Exercise 4: Triangle Classifier
Write a program that:
- Asks for three side lengths
- First checks if they can form a valid triangle (sum of any two sides must be greater than the third)
- If valid, classifies it as equilateral (all equal), isosceles (two equal), or scalene (none equal)
Exercise 5: Simple Calculator
Write a program that:
- Asks for two numbers
- Asks for an operation (+, -, *, /)
- Performs the calculation and displays the result
- Handles division by zero with an error message
Exercise 6: Ticket Price Calculator
Write a program for a movie theater that calculates ticket prices:
- Children (under 12): $8
- Seniors (65 and over): $9
- Adults: $12
- Matinee shows (before 5 PM) get $2 off any ticket
Ask for age and show time, then display the ticket price.
π Quick Reference
Comparison Operators
x == yx != yx > yx < yx >= yx <= yLogical Operators
x and yx or ynot xIf Statement Structure
if condition1:
# code to run if condition1 is True
elif condition2:
# code to run if condition2 is True
elif condition3:
# code to run if condition3 is True
else:
# code to run if no conditions are Trueβ Key Takeaways
- β Boolean constants are
TrueandFalse(capitalized!) - β Use
==for comparison, not=(which is assignment) - β Relational operators (
<,>,==, etc.) return Boolean values - β Logical operators (
and,or,not) combine Boolean expressions - β
ifstatements must end with a colon (:) - β Indentation is required in Pythonβit defines code blocks
- β Use
elif(notelse if) for additional conditions - β Only the first true condition's block is executed in an if-elif-else chain
- β
elseis optional and catches anything not caught byif/elif
β Need Help?
If your program doesn't work, check these common issues:
- SyntaxError near
ifβDid you forget the colon at the end? - IndentationErrorβIs your code properly indented after the colon?
- NameError: name 'true' is not definedβUse
Truewith a capital T - Logic not working as expectedβPrint your variables to see their actual values
- Wrong comparison resultβAre you using
==instead of=?
if statements work, and practice with simple examples before tackling complex ones. Every programmer uses these concepts daily!