Lesson 1.7: Operators and Data Types

PCEP 1.4: Choose operators and data types adequate to the problem

Opening Question

Think-Pair-Share: What happens when you type 5 + 3 * 2 in Python?

Write your prediction, then discuss with a partner.

Let's test it together!

Today's Learning Objectives

By the end of this lesson, you will:

  • Use all Python operator types correctly
  • Apply operator precedence rules
  • Choose appropriate data types for different problems
  • Perform type casting operations
  • Solve operator precedence puzzles

Arithmetic Operators: The Basics

Let's code together! Open your Python interpreter and try these:

print(10 + 5)    # Addition
print(10 - 5)    # Subtraction
print(10 * 5)    # Multiplication
print(10 / 5)    # Division (float result)

Question for class: What do you think 10 / 3 will give us?

More Arithmetic Operators

Keep coding along:

print(10 // 3)   # Floor division
print(10 % 3)    # Modulo (remainder)
print(10 ** 3)   # Exponentiation

Call on student: Can someone explain what floor division does differently than regular division?

Quick Practice: Arithmetic Operators

Try this in your interpreter:

Calculate the area of a circle with radius 5 using the formula: π × r²

radius = 5
pi = 3.14159
area = pi * radius ** 2
print(area)

Question: Why did we write radius ** 2 instead of radius * radius?

String Operators

Code along with me:

first_name = "Python"
last_name = "Programming"

# String concatenation
full_name = first_name + " " + last_name
print(full_name)

# String repetition
print("Ha" * 5)
print("-" * 20)

Call on student: When might string repetition be useful in programming?

Assignment and Shortcut Operators

Let's explore these step by step:

score = 100
print(score)

score = score + 10   # Traditional way
print(score)

score += 15          # Shortcut way
print(score)

Try these shortcuts:

score -= 5    # Same as score = score - 5
score *= 2    # Same as score = score * 2
score /= 4    # Same as score = score / 4

Practice: Shortcut Operators

Your turn! Start with points = 50 and use shortcut operators to:

  1. Add 25 points
  2. Double the points
  3. Subtract 30 points
  4. Divide by 5

Check with neighbor: Did you get the same final result?

Comparison Operators

Interactive demonstration:

x = 10
y = 20

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

Question for class: What data type do comparison operators return?

Boolean Operators

Let's build logical expressions:

age = 17
has_license = True

can_drive = age >= 16 and has_license
print(can_drive)

is_weekend = True
is_holiday = False
no_school = is_weekend or is_holiday
print(no_school)

print(not has_license)

Call on student: Explain the difference between and and or operators.

Interactive Boolean Practice

Work with a partner - predict the output, then test:

sunny = True
warm = False
rainy = True

good_beach_day = sunny and warm and not rainy
print(good_beach_day)

need_umbrella = rainy or (sunny and not warm)
print(need_umbrella)

Bitwise Operators (Preview)

These work with binary representations:

a = 5    # Binary: 101
b = 3    # Binary: 011

print(a & b)   # AND: 001 = 1
print(a | b)   # OR:  111 = 7  
print(a ^ b)   # XOR: 110 = 6
print(~a)      # NOT: (depends on system)
print(a << 1)  # Left shift: 1010 = 10
print(a >> 1)  # Right shift: 10 = 2

Note: We'll use these more in advanced programming!

Operator Precedence Challenge

Think before you code! What will these print?

result1 = 2 + 3 * 4
result2 = (2 + 3) * 4
result3 = 2 ** 3 ** 2
result4 = 10 / 2 * 3

Partner work: Discuss your predictions, then test them!

Python Operator Precedence Rules

From highest to lowest priority:

  1. () - Parentheses
  2. ** - Exponentiation (right-to-left)
  3. +x, -x, ~x - Unary operators
  4. *, /, //, % - Multiplication, division, modulo
  5. +, - - Addition, subtraction
  6. <<, >> - Bit shifts
  7. & - Bitwise AND
  8. ^ - Bitwise XOR
  9. | - Bitwise OR
  10. ==, !=, <, <=, >, >= - Comparisons
  11. not - Boolean NOT
  12. and - Boolean AND
  13. or - Boolean OR

Type Casting Practice

Let's convert between data types:

# String to number
age_str = "18"
age_num = int(age_str)
print(age_num + 2)

# Number to string
score = 95
score_str = str(score)
print("Your score is: " + score_str)

# Float to int (truncation!)
pi = 3.14159
pi_int = int(pi)
print(pi_int)

Call on student: What happens when we convert 3.9 to an integer?

Floating-Point Accuracy Challenge

Try this surprising example:

result = 0.1 + 0.2
print(result)
print(result == 0.3)

Question for class: Why doesn't this equal exactly 0.3?

Answer: Floating-point representation limitations in binary!

Type Casting Gotchas

Let's see what breaks:

# This works:
number_str = "123"
number = int(number_str)

# This doesn't work - try it and see the error:
invalid_str = "hello"
# number = int(invalid_str)  # ValueError!

# This truncates:
float_str = "3.7"
number = int(float_str)  # Error! Need int(float(float_str))

Group discussion: How can we handle conversion errors safely?

Operator Precedence Puzzle Time!

Work in teams of 3 - solve these without running the code first:

puzzle1 = 5 + 3 * 2 ** 2 - 1
puzzle2 = (5 + 3) * 2 ** (2 - 1)  
puzzle3 = 10 / 2 + 3 * 4 - 2
puzzle4 = not 5 > 3 and 2 < 4 or False

Team competition: First team with all correct answers wins!

Real-World Operator Example

Let's build a tip calculator together:

bill_amount = float(input("Enter bill amount: $"))
tip_percentage = float(input("Enter tip percentage: "))

tip_amount = bill_amount * (tip_percentage / 100)
total_amount = bill_amount + tip_amount

print(f"Tip: ${tip_amount:.2f}")
print(f"Total: ${total_amount:.2f}")

Test it out with different values!

Data Type Selection Strategy

When choosing data types, consider:

  • int: Counting, indexing, whole numbers
  • float: Measurements, calculations, money
  • str: Text, user input, display
  • bool: Flags, conditions, yes/no questions

Quick poll: What data type would you use for:

  • A student's grade (A, B, C, D, F)?
  • The number of students in class?
  • Whether it's raining?

Wrap-up Activity: Operator Olympics

Individual challenge - create a program that:

  1. Takes two numbers as input
  2. Performs all arithmetic operations (+, -, *, /, //, %, **)
  3. Shows comparison results (==, !=, <, >, etc.)
  4. Uses at least one shortcut operator
  5. Demonstrates type casting

Show and tell: Volunteer to share your solution!

Exit Ticket

Before you leave, write down:

  1. One operator precedence rule you learned today
  2. One type casting example
  3. One question you still have about operators

Next lesson: We'll use these operators for Input/Output operations and wrap up Unit 1!