Introduction to Python Programming

Andrew J. Pounds, Ph.D.

πŸ”€ 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.

What You'll Learn:
  • Boolean constants True and False
  • How to compare values using relational operators
  • How to combine conditions using logical operators
  • How to control program flow with if, elif, and else statements

🎯 1. Boolean Constants

Python contains two Boolean constants that represent the fundamental values of logic:

True False
⚠️ Important: Note that 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 < 4

would 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
πŸ’‘ Common Mistake: Don't confuse = (assignment) with == (comparison)!
  • x = 5 means "assign the value 5 to x"
  • x == 5 means "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:

  1. 3 < 4 β†’ True
  2. 4 < 2 β†’ False
  3. not(False) β†’ True
  4. 2 > 3 β†’ False
  5. True or False β†’ True
  6. True and True β†’ 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.

Real-World Example: Imagine you're writing a program to sound an alarm to remind you to go to class. You would only want that alarm executing on the days that you have a specific class. In other words: IF it is a class day, sound the alarm.

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)
A is greater than B
5
πŸ“ Critical: Indentation Matters!

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 are a minor
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")
Grade: B
⚠️ Important: Only the first true condition's block is executed! Even if multiple conditions are true, Python stops checking after the first match.

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")
first 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 are old enough to drive
You have a license - you can drive!
πŸ’‘ Pro Tip: While nesting is sometimes necessary, deeply nested 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")
The temperature is 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")
It's the weekend!

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))
Enter your age: 25
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")
=== Login System ===

Enter username: student
Enter password: python123

Login successful!
Welcome, student!

⚠️ Common Mistakes (And How to Fix Them)

Mistake 1: Using = Instead of ==

❌ Wrong:
if x = 5:  # ERROR! This is assignment, not comparison
    print("x is 5")
βœ… Correct:
if x == 5:  # Use == for comparison
    print("x is 5")

Mistake 2: Forgetting the Colon

❌ Wrong:
if x > 5  # ERROR! Missing colon
    print("x is greater than 5")
βœ… Correct:
if x > 5:  # Don't forget the colon!
    print("x is greater than 5")

Mistake 3: Incorrect Indentation

❌ Wrong:
if x > 5:
print("x is greater than 5")  # ERROR! Not indented
βœ… Correct:
if x > 5:
    print("x is greater than 5")  # Indented with 4 spaces

Mistake 4: Using true/false (Lowercase)

❌ Wrong:
is_valid = true  # ERROR! Python doesn't recognize lowercase
βœ… Correct:
is_valid = True  # Boolean constants are capitalized

Mistake 5: Writing else if Instead of elif

❌ Wrong:
if x > 10:
    print("big")
else if x > 5:  # ERROR! Python uses elif, not else if
    print("medium")
βœ… Correct:
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:

  1. Asks the user to enter an integer
  2. Determines if the number is even or odd
  3. Prints the result

Hint: A number is even if number % 2 == 0

Exercise 2: Grade Calculator

Write a program that:

  1. Asks the user to enter a numerical score (0-100)
  2. Converts it to a letter grade (A: 90+, B: 80-89, C: 70-79, D: 60-69, F: below 60)
  3. Prints the letter grade

Exercise 3: Leap Year Checker

Write a program that determines if a year is a leap year:

  1. A year is a leap year if it's divisible by 4
  2. EXCEPT years divisible by 100 are NOT leap years
  3. 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:

  1. Asks for three side lengths
  2. First checks if they can form a valid triangle (sum of any two sides must be greater than the third)
  3. If valid, classifies it as equilateral (all equal), isosceles (two equal), or scalene (none equal)

Exercise 5: Simple Calculator

Write a program that:

  1. Asks for two numbers
  2. Asks for an operation (+, -, *, /)
  3. Performs the calculation and displays the result
  4. 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

Equal to:
x == y
Not equal to:
x != y
Greater than:
x > y
Less than:
x < y
Greater than or equal:
x >= y
Less than or equal:
x <= y

Logical Operators

Both must be true:
x and y
At least one must be true:
x or y
Reverse the value:
not x

If 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 True and False (capitalized!)
  • βœ“ Use == for comparison, not = (which is assignment)
  • βœ“ Relational operators (<, >, ==, etc.) return Boolean values
  • βœ“ Logical operators (and, or, not) combine Boolean expressions
  • βœ“ if statements must end with a colon (:)
  • βœ“ Indentation is required in Pythonβ€”it defines code blocks
  • βœ“ Use elif (not else if) for additional conditions
  • βœ“ Only the first true condition's block is executed in an if-elif-else chain
  • βœ“ else is optional and catches anything not caught by if/elif

❓ Need Help?

If your program doesn't work, check these common issues:

  1. SyntaxError near ifβ€”Did you forget the colon at the end?
  2. IndentationErrorβ€”Is your code properly indented after the colon?
  3. NameError: name 'true' is not definedβ€”Use True with a capital T
  4. Logic not working as expectedβ€”Print your variables to see their actual values
  5. Wrong comparison resultβ€”Are you using == instead of =?
Remember: Conditional logic is the foundation of all programming! Take your time to understand how if statements work, and practice with simple examples before tackling complex ones. Every programmer uses these concepts daily!