Introduction to Operations

What are operations?

Operations are actions you can perform on values and variables in your program. You can think of them as the “verbs” of programming - they tell the computer what to do with data (values and variables).

Example:

# Feel free to play around with this code age = 25 next_year = age + 1 print(next_year)

Here, + is an operation that adds two numbers together.

Operators

An operator is a symbol that performs an operation. It’s like a mathematical symbol that tells the computer what action to take.

Examples of operators:

  • + (addition operator)
  • - (subtraction operator)
  • == (equality operator)
  • * (multiplication operator)

Arithmetic Operations

These operations work with numbers (integers and floats):

1. Addition (+)

The + symbol adds two numbers together.

# Feel free to play around with this code score1 = 85 score2 = 92 total = score1 + score2 print(total)

# Feel free to play around with this code score1 = 85.5 score2 = 92.3 total = score1 + score2 print(total)

2. Subtraction (-)

The - symbol subtracts one number from another.

# Feel free to play around with this code price = 50 discount = 10 final_price = price - discount print(final_price)

3. Multiplication (*)

The * symbol multiplies two numbers.

# Feel free to play around with this code length = 5 width = 3 area = length * width print(area)

4. Division (/)

The / symbol divides one number by another (always gives a float result).

# Feel free to play around with this code total_cookies = 20 people = 4 cookies_per_person = total_cookies / people print(cookies_per_person)

5. Integer Division (//)

The // symbol divides and rounds down to the nearest whole number.

# Feel free to play around with this code total_cookies = 23 people = 4 whole_cookies = total_cookies // people print(whole_cookies)

6. Modulo (%)

The % symbol gives the remainder after division.

# Feel free to play around with this code total_cookies = 23 people = 4 leftover_cookies = total_cookies % people print(leftover_cookies)

7. Exponentiation (**)

** raises a number to a power.

# Feel free to play around with this code base = 2 power = 3 result = base ** power print(result)

Order of Operations

Python follows mathematical order of operations (PEMDAS):

  1. Parentheses ()
  2. Exponents **
  3. Multiplication * and Division /
  4. Addition + and Subtraction -
# Feel free to play around with this code result = 2 + 3 * 4 print(result) result_with_parentheses = (2 + 3) * 4 print(result_with_parentheses) ```


Comparison Operations

These operations compare values and give True or False results:

1. Equal to (==)

The double equals == symbol checks if two values are the same (this is different from a single =, which assigns a value to a variable).

# Feel free to play around with this code age = 18 is_adult = age == 18 print(is_adult)

2. Not equal to (!=)

The symbol ! when combined with = negates equality, therefore != checks if two values are different.

# Feel free to play around with this code password = "secret" is_wrong = password != "password123" print(is_wrong)

3. Greater than (>)

The symbol > checks if the value on the left is greater than the value on the right.

# Feel free to play around with this code score = 85 passed = score > 60 print(passed)

4. Less than (<)

The symbol < checks if the value on the left is less than the value on the right.

temperature = 15 is_cold = temperature < 20 print(is_cold) # Output: True

5. Greater than or equal to (>=)

Combining the > symbol and = in >= checks if the value on the left is greater than or equal to the value on the right.

# Feel free to play around with this code age = 18 can_vote = age >= 18 print(can_vote)

6. Less than or equal to (<=)

Combining the < symbol and = in <= checks if the value on the left is less than or equal to the value on the right.

# Feel free to play around with this code speed = 50 within_limit = speed <= 60 print(within_limit)


String Operations

1. Concatenation (+)

When applied to strings, the + symbol joins strings together.

# Feel free to play around with this code first_name = "Alice" last_name = "Smith" full_name = first_name + " " + last_name print(full_name)

2. Repetition (*)

When applied to strings, the * symbol repeats a string multiple times.

# Feel free to play around with this code laugh = "ha" big_laugh = laugh * 3 print(big_laugh)


Practice Exercises

Test your understanding of operations with these exercises.

Q1: Multiplication and addition

Write a program that asks the user for the length and width of a rectangle, then calculates and displays both the area and perimeter.

Formulas:

  • Area = length × width
  • Perimeter = 2 × (length + width)

Expected output:

Enter length: 5
Enter width: 3
Area: 15.0
Perimeter: 16.0
Example solution
area = length * width
perimeter = 2 * (length + width)

print(f"Area: {area}")
print(f"Perimeter: {perimeter}")

Q2: Integer division and modulo

Write a program that asks how many cookies you have and how many people need to share them. Calculate:

  • How many whole cookies each person gets
  • How many cookies are left over

Expected output:

How many cookies do you have? 23
How many people are sharing? 5
Each person gets: 4 cookies
Leftover cookies: 3
Example solution
cookies_per_person = total_cookies // people
leftover = total_cookies % people

print(f"Each person gets: {cookies_per_person} cookies")
print(f"Leftover cookies: {leftover}")

Q3: Comparison operators

Write a program that asks for a temperature in Celsius and checks if it’s:

  • Below freezing (< 0)
  • At freezing (== 0)
  • Above freezing but cool (> 0 and <= 15)
  • Warm (> 15)

Display an appropriate message for each case.

Expected output:

Enter temperature in Celsius: -5
It's below freezing!

Enter temperature in Celsius: 0
It's exactly freezing point.

Enter temperature in Celsius: 10
It's above freezing but cool.

Enter temperature in Celsius: 20
It's warm!
Example solution
if temp < 0:
    print("It's below freezing!")
elif temp == 0:
    print("It's exactly freezing point.")
elif temp <= 15:
    print("It's above freezing but cool.")
else:
    print("It's warm!")

Q4: String concatenation and repetition

Write a program that asks the user for:

  • Their name
  • A word they want to repeat
  • How many times to repeat it

Then display:

  • A personalized greeting using their name
  • The word repeated the specified number of times

Expected output:

Enter your name: Alice
Enter a word to repeat: Hello
How many times? 3
Hi Alice, nice to meet you!
HelloHelloHello
Example solution
greeting = "Hi " + name + ", nice to meet you!"
repeated_word = word * times

print(greeting)
print(repeated_word)

Alternative using f-strings:

name = input("Enter your name: ")
word = input("Enter a word to repeat: ")
times = int(input("How many times? "))

print(f"Hi {name}, nice to meet you!")
print(word * times)