Lesson 3: Basic Operations and Conditionals#

Learn how to perform calculations and make your code make decisions! This is where programming becomes truly powerful.

What You’ll Learn#

  • Arithmetic operations (math!)

  • Comparison operators

  • Logical operators (and, or, not)

  • If/elif/else statements

  • Decision-making patterns

  • Common pitfalls and best practices

💡 Real-World Analogy#

Think of conditionals like everyday decisions:

  • If it’s raining, take an umbrella

  • If you’re hungry, eat food

  • If the light is red, stop; else go

Programming works the same way - your code makes decisions based on conditions!


1. Arithmetic Operations#

Python is a powerful calculator! Let’s explore all the math operations.

Basic Operations#

Operator

Name

Example

Result

+

Addition

5 + 3

8

-

Subtraction

10 - 4

6

*

Multiplication

6 * 7

42

/

Division

20 / 4

5.0

//

Floor Division

20 // 3

6

%

Modulo (Remainder)

20 % 3

2

**

Exponentiation

2 ** 3

8

# Addition
result = 5 + 3
print("5 + 3 =", result)

# Subtraction
result = 10 - 4
print("10 - 4 =", result)

# Multiplication
result = 6 * 7
print("6 * 7 =", result)

# Division (always returns a float)
result = 20 / 4
print("20 / 4 =", result)
print("Type:", type(result))  # Notice it's a float!

Special Operations#

# Floor Division - divides and rounds DOWN to nearest integer
print("20 // 3 =", 20 // 3)  # 6, not 6.666...
print("20 / 3 =", 20 / 3)    # Compare with regular division

# Modulo - gives the REMAINDER after division
print("20 % 3 =", 20 % 3)    # 2 (because 20 = 3*6 + 2)
print("10 % 2 =", 10 % 2)    # 0 (no remainder - 10 is even!)

# Exponentiation - raising to a power
print("2 ** 3 =", 2 ** 3)    # 2 * 2 * 2 = 8
print("10 ** 2 =", 10 ** 2)  # 10 * 10 = 100

🎯 Use Cases for Special Operations#

Floor Division (//):

  • Splitting items into groups: “How many full teams of 5 can I make from 23 people?”

  • Converting units: “How many hours in 135 minutes?” → 135 // 60

Modulo (%):

  • Check if even/odd: number % 2 == 0 → even!

  • Cycle through values: Day of week, rotating banners

  • Get leftovers: “23 people, teams of 5, how many left over?” → 23 % 5

# Practical example: Is a number even or odd?
number = 42

remainder = number % 2
print(f"{number} divided by 2 has remainder: {remainder}")

if remainder == 0:
    print(f"{number} is EVEN!")
else:
    print(f"{number} is ODD!")

2. Order of Operations#

Python follows PEMDAS (just like math class!):

  1. Parentheses ()

  2. Exponents **

  3. Multiplication/Division *, /, //, % (left to right)

  4. Addition/Subtraction +, - (left to right)

# Without parentheses
result = 2 + 3 * 4
print("2 + 3 * 4 =", result)  # 14 (multiplication first!)

# With parentheses
result = (2 + 3) * 4
print("(2 + 3) * 4 =", result)  # 20 (parentheses first!)

# Complex example
result = 2 ** 3 + 10 / 2 - 3
print("2 ** 3 + 10 / 2 - 3 =", result)  # 8 + 5.0 - 3 = 10.0

# Pro tip: Use parentheses to make your intent clear!
result = (2 ** 3) + (10 / 2) - 3
print("With clarity:", result)  # Same result, easier to read

Operations with Variables#

# Variables in calculations
price = 19.99
quantity = 3
tax_rate = 0.08

subtotal = price * quantity
tax = subtotal * tax_rate
total = subtotal + tax

print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax (8%): ${tax:.2f}")
print(f"Total: ${total:.2f}")

Compound Assignment Operators#

Shorthand for updating variables!

score = 10
print("Starting score:", score)

# Instead of: score = score + 5
score += 5  # Same as: score = score + 5
print("After += 5:", score)

score -= 3  # Same as: score = score - 3
print("After -= 3:", score)

score *= 2  # Same as: score = score * 2
print("After *= 2:", score)

score //= 4  # Same as: score = score // 4
print("After //= 4:", score)

3. Comparison Operators#

Compare values and get boolean results (True or False).

Operator

Meaning

Example

Result

==

Equal to

5 == 5

True

!=

Not equal to

5 != 3

True

>

Greater than

10 > 5

True

<

Less than

3 < 8

True

>=

Greater than or equal

5 >= 5

True

<=

Less than or equal

4 <= 4

True

x = 10
y = 5

print("x =", x)
print("y =", y)
print()

print("x > y:", x > y)   # Greater than
print("x < y:", x < y)   # Less than
print("x == y:", x == y) # Equal to
print("x != y:", x != y) # Not equal to
print("x >= y:", x >= y) # Greater than or equal
print("x <= y:", x <= y) # Less than or equal

⚠️ Common Mistake: = vs ==#

  • = assigns a value (makes something equal)

  • == compares values (checks if equal)

# Assignment (one equals sign)
age = 25  # Sets age to 25
print("Age is now:", age)

# Comparison (two equals signs)
is_adult = age == 18  # Checks if age equals 18
print("Is age equal to 18?", is_adult)  # False

# This is a common error:
# if age = 18:  # ERROR! This tries to assign, not compare
# if age == 18:  # CORRECT! This compares

Comparing Strings#

# Strings can be compared too!
name = "Alice"

print("name == 'Alice':", name == "Alice")   # True
print("name == 'alice':", name == "alice")   # False (case-sensitive!)
print("name != 'Bob':", name != "Bob")       # True

# Strings also have ordering (alphabetical)
print("'apple' < 'banana':", "apple" < "banana")  # True (alphabetically)
print("'zoo' > 'aardvark':", "zoo" > "aardvark")  # True

4. Logical Operators#

Combine multiple conditions using logical operators:

  • and - Both conditions must be True

  • or - At least one condition must be True

  • not - Reverses the condition

# AND - both must be true
age = 25
has_license = True

can_drive = age >= 16 and has_license
print("Can drive?", can_drive)  # True (both conditions met)

# OR - at least one must be true
is_weekend = True
is_holiday = False

can_sleep_in = is_weekend or is_holiday
print("Can sleep in?", can_sleep_in)  # True (weekend!)

# NOT - reverses the condition
is_raining = False
is_sunny = not is_raining
print("Is it sunny?", is_sunny)  # True

Truth Tables#

AND Truth Table:

A

B

A and B

True

True

True

True

False

False

False

True

False

False

False

False

OR Truth Table:

A

B

A or B

True

True

True

True

False

True

False

True

True

False

False

False

# Complex logical expressions
temperature = 22
is_sunny = True
has_jacket = False

# Good weather for a walk?
good_for_walk = (temperature > 15 and temperature < 30) and is_sunny
print("Good for a walk?", good_for_walk)

# Need to buy a jacket?
need_jacket = (temperature < 15) and (not has_jacket)
print("Need to buy a jacket?", need_jacket)

5. If Statements#

Make decisions in your code! The basic syntax:

if condition:
    # Code to run if condition is True

Important: Notice the colon : and indentation! Python uses indentation to group code.

# Simple if statement
age = 20

if age >= 18:
    print("You are an adult!")
    print("You can vote!")

print("This always prints (not indented)")

If-Else Statements#

Do one thing if True, another if False:

age = 15

if age >= 18:
    print("You are an adult!")
else:
    print("You are a minor.")
    years_until_adult = 18 - age
    print(f"You'll be an adult in {years_until_adult} years.")

If-Elif-Else Statements#

Check multiple conditions in order:

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Score: {score}")
print(f"Grade: {grade}")

🔍 How If-Elif-Else Works#

Python checks conditions in order and stops at the first True condition:

  1. Checks if condition

    • If True → runs that block and stops

    • If False → checks next elif

  2. Checks each elif condition in order

    • If True → runs that block and stops

    • If False → checks next elif

  3. If all are False → runs else block (if present)

# Temperature checker
temperature = 25

if temperature > 30:
    print("It's hot! 🌞")
elif temperature > 20:
    print("It's comfortable! 😊")
elif temperature > 10:
    print("It's cool. 🍂")
else:
    print("It's cold! ❄️")

6. Nested Conditionals#

You can put if statements inside other if statements!

age = 20
has_ticket = True

if age >= 18:
    print("You're old enough to enter the concert.")
    if has_ticket:
        print("You have a ticket! Enjoy the show! 🎵")
    else:
        print("But you need to buy a ticket first.")
else:
    print("Sorry, you must be 18 or older.")

💡 Tip: Use and Instead of Nesting When Possible#

These are equivalent, but the second is cleaner:

# Nested (harder to read)
if age >= 18:
    if has_ticket:
        print("Welcome!")

# Better: use 'and' (cleaner)
if age >= 18 and has_ticket:
    print("Welcome!")

7. Truthiness and Falsiness#

In Python, any value can be used in a condition. Some values are considered “truthy” or “falsy”.

Falsy Values (evaluate to False):#

  • False (the boolean)

  • 0 (zero)

  • 0.0 (zero float)

  • "" (empty string)

  • [] (empty list)

  • None

Truthy Values (evaluate to True):#

  • Everything else!

  • True, any non-zero number, any non-empty string/list

# Examples of truthy/falsy
name = "Alice"

if name:
    print(f"Hello, {name}!")
else:
    print("No name provided.")

# Try with empty string
name = ""

if name:
    print(f"Hello, {name}!")
else:
    print("No name provided.")  # This will print!
# Checking if a number is non-zero
score = 0

if score:
    print("You scored points!")
else:
    print("No points yet.")  # This prints (0 is falsy)

8. Practical Examples#

Let’s apply what we’ve learned to real-world scenarios!

# Example 1: Login validator
username = "alice"
password = "secret123"

correct_username = "alice"
correct_password = "secret123"

if username == correct_username and password == correct_password:
    print("✅ Login successful!")
else:
    print("❌ Invalid username or password.")
# Example 2: Discount calculator
price = 100
is_member = True
quantity = 5

# Calculate discount
if is_member:
    discount = 0.10  # 10% discount
else:
    discount = 0

# Bulk discount
if quantity >= 10:
    discount += 0.05  # Additional 5% for bulk

final_price = price * quantity * (1 - discount)

print(f"Items: {quantity}")
print(f"Price each: ${price}")
print(f"Discount: {discount * 100}%")
print(f"Total: ${final_price:.2f}")
# Example 3: BMI Calculator with categories
weight_kg = 70
height_m = 1.75

bmi = weight_kg / (height_m ** 2)

print(f"Your BMI: {bmi:.1f}")

if bmi < 18.5:
    category = "Underweight"
elif bmi < 25:
    category = "Normal weight"
elif bmi < 30:
    category = "Overweight"
else:
    category = "Obese"

print(f"Category: {category}")

9. Common Mistakes#

Watch out for these pitfalls!

# Mistake 1: Forgetting the colon
# if age >= 18  # ERROR: Missing colon!
#     print("Adult")

# Correct:
age = 20
if age >= 18:  # Don't forget the colon!
    print("Adult")
# Mistake 2: Wrong indentation
if age >= 18:
print("This will error!")  # ERROR: Not indented!

# Correct:
if age >= 18:
    print("This works!")  # Must be indented!
# Mistake 3: Using = instead of ==
age = 25

# if age = 18:  # ERROR: Assignment, not comparison!
#     print("18 years old")

# Correct:
if age == 18:  # Use == to compare!
    print("18 years old")
# Mistake 4: Order matters in elif chains!
score = 95

# BAD: The first condition catches everything!
if score >= 60:
    print("You passed!")  # This will print for 95
elif score >= 90:
    print("Excellent!")  # This never runs!

# GOOD: Most specific conditions first!
if score >= 90:
    print("Excellent!")  # This prints for 95
elif score >= 60:
    print("You passed!")

📝 Exercises#

Exercise 1: Calculator#

Create variables for two numbers and perform all arithmetic operations on them. Print the results with labels.

# Your code here

Exercise 2: Even or Odd#

Create a program that:

  1. Stores a number in a variable

  2. Uses the modulo operator to check if it’s even or odd

  3. Prints “Even!” or “Odd!” accordingly

# Your code here

Exercise 3: Temperature Checker#

Create a program that:

  1. Stores a temperature value

  2. Prints “It’s hot!” if temperature is above 30

  3. Prints “It’s cold!” if temperature is below 10

  4. Prints “It’s comfortable!” otherwise

# Your code here

Exercise 4: Age Categorizer#

Write a program that categorizes age into:

  • “Child” (0-12)

  • “Teenager” (13-19)

  • “Adult” (20-64)

  • “Senior” (65+)

Print the category for a given age.

# Your code here

Exercise 5: Login System#

Create a simple login checker:

  1. Set correct username and password as variables

  2. Create user input variables for entered username and password

  3. Check if both match using and

  4. Print “Login successful!” or “Invalid credentials”

# Your code here

Exercise 6: Ticket Pricing#

Create a movie ticket price calculator:

  • Base price: $15

  • Children (under 12): 50% discount

  • Seniors (65+): 30% discount

  • Adults: Full price

  • Weekend: Add $3 to any ticket

Given an age and whether it’s a weekend, calculate and print the ticket price.

# Your code here

✅ Self-Check Quiz#

Before moving on, make sure you can answer these:

  1. What’s the difference between / and //?

  2. What does the % operator do?

  3. What’s the difference between = and ==?

  4. What are the three logical operators?

  5. What does and require to return True?

  6. What does or require to return True?

  7. Why is the colon : important in if statements?

  8. What happens if you don’t indent code after an if statement?

  9. In an if-elif-else chain, can multiple blocks run?

  10. Name three “falsy” values in Python.


🎯 Key Takeaways#

  • Arithmetic operators: +, -, *, /, //, %, **

  • Comparison operators: ==, !=, >, <, >=, <= (return True/False)

  • Logical operators: and (both), or (at least one), not (reverse)

  • If statements make decisions based on conditions

  • Elif checks multiple conditions in order

  • Else runs when all conditions are False

  • Indentation matters! It defines code blocks

  • Only one block runs in an if-elif-else chain

  • Some values are truthy (True-like) or falsy (False-like)


🚀 Next Steps#

Excellent work! You now know how to:

  • Perform calculations in Python

  • Compare values

  • Make your code make decisions!

These are the building blocks of all programs. Every app, website, and game uses conditionals!

Next, you’ll explore different topics based on your interests:

  • AI & ML Track: 04_intro_to_ai_and_ml.ipynb

  • Computing Fundamentals: 05_computing_fundamentals.ipynb

  • Continue Python: Move to Medium level for loops and functions!


💡 Pro Tips#

  1. Use parentheses in complex expressions for clarity

  2. Order matters in elif chains - put most specific conditions first

  3. Use and instead of nesting when possible

  4. Remember: One = assigns, two == compares

  5. Modulo (%) is your friend for even/odd checks and cycles

  6. Compound operators (+=, -=) make code cleaner

  7. Test edge cases: What happens with 0? Negative numbers? Empty strings?

  8. Comment complex conditions to explain the logic