9. Operators

Arithmetic Operators: Perform standard mathematical calculations.
Assignment operators are used to assign values to variables.
The compound assignment operators consist of two operators as a shorthand.
Comparison operators are used to compare two values.
Booleans represent one of two values: True or False.
Logical operators are used to combine conditional statements.
Membership operators are used to test if a sequence is presented in an object.
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location.
The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own and only None can be None.
# Arithmetic calculation
result = 10 + 5 * 2  # Result is 20

# Comparison check
is_valid = result > 15  # Result is True

9.1. Arithmetic Operators

Arithmetic operators are used to carry out mathematical calculations:

  • Addition (+) and Subtraction (-): Standard arithmetic sum and difference.

  • Multiplication (*) and Division (/): Multiplication and true division (always returns a float).

  • Floor Division (//): Divides and rounds down to the nearest whole integer.

  • Modulus (%): Returns the remainder left over after division.

  • Exponentiation ()**: Raises a base number to a power.

print(10 / 3)   # True Division -> 3.3333333333333335
print(10 // 3)  # Floor Division -> 3
print(10 % 3)   # Modulus (Remainder) -> 1
print(2 ** 3)   # Exponentiation (2^3) -> 8

9.1.1. Quiz: Arithmetic Operators

9.1.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
division
floor division
modulus
order
power

1. The / operator performs Drop here and always returns a floating-point number.
2. The % operator (Drop here) returns the remainder of a division.
3. The // operator performs Drop here, rounding down to the nearest integer.
4. The symbol for exponentiation (raising a number to a Drop here) in Python is **.
5. Python follows the Drop here of operations, meaning multiplication occurs before addition.

9.1.1.2. Code Ordering Examples

Example 1: Compute the total price of 3 items costing 5 dollars each with a 2-dollar discount.

Drag and drop lines into the correct order and click to adjust indentation:
☰
price = 5
☰
total = price * quantity - discount
☰
print(total)
☰
quantity = 3
☰
discount = 2

Example 2: Calculate both the quotient and remainder of 17 divided by 5.

Drag and drop lines into the correct order and click to adjust indentation:
☰
remainder = 17 % 5
☰
quotient = 17 // 5
☰
print(quotient, remainder)

Example 3: Calculate the area of a square with a side length of 4 using the exponentiation operator.

Drag and drop lines into the correct order and click to adjust indentation:
☰
side = 4
☰
print(area)
☰
area = side ** 2

9.1.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What is the result of 15 % 4 in Python?

Correct! 15 divided by 4 is 3 with a remainder of 3.

Incorrect. % returns the remainder as an integer, not floating-point division.

Incorrect. While 15 // 4 is 3, the remainder itself is also 3.

Incorrect. 15 is not evenly divisible by 4.

Which operator always outputs a value of type float?

Correct! Standard division / always returns a float in Python 3.

Incorrect. Floor division yields an integer when given integer inputs.

Incorrect. Integer multiplication yields an integer.

Incorrect. Integer addition yields an integer.

What does 2 ** 4 evaluate to in Python?

Correct! 2 raised to the power of 4 ($2 times 2 times 2 times 2$) is 16.

Incorrect. 2 * 4 is 8, but ** is the exponentiation operator.

Incorrect. Exponentiation multiplies base by itself power times.

Incorrect. $2^4 = 16$.

What is the value of 7 // 2?

Correct! Floor division discards the fractional part, rounding 3.5 down to 3.

Incorrect. True division / returns 3.5; // floors it to 3.

Incorrect. Floor division rounds down toward negative infinity.

Incorrect. 1 is the remainder returned by 7 % 2.

According to Python operator precedence, what is the result of 2 + 3 * 4?

Correct! Multiplication takes precedence over addition: $3 times 4 = 12$, then $2 + 12 = 14$.

Incorrect. Python evaluates multiplication before addition, not left-to-right blindly.

Incorrect. Expression evaluates as $2 + (3 times 4)$.

Incorrect. Multiplication precedes addition.

What does 10 % 2 return?

Correct! 10 is an even number, so dividing by 2 leaves a remainder of 0.

Incorrect. 10 / 2 is 5, but % checks the remainder.

Incorrect. Even numbers have 0 remainder when divided by 2.

Incorrect. Remainder cannot equal or exceed the divisor 2.

What is the result of (2 + 3) * 4?

Correct! Parentheses override default precedence: $(2 + 3) = 5$, then $5 times 4 = 20$.

Incorrect. Parentheses force addition to evaluate before multiplication.

Incorrect. $5 times 4 = 20$.

Incorrect. Parentheses group 2 + 3 together first.

What will 19 // 5 evaluate to?

Correct! 19 divided by 5 is 3.8, which rounds down to 3.

Incorrect. Floor division rounds down, not up.

Incorrect. // discards decimal values for integer inputs.

Incorrect. Remainder is 4 (19 % 5), but // calculates integer quotient.

Which operator should you use to check if an integer is even or odd?

Correct! Checking if number % 2 == 0 determines whether a number is even.

Incorrect. Quotient does not directly indicate parity.

Incorrect. True division returns float results.

Incorrect. Exponentiation raises numbers to powers.

What is the result of 3 ** 3?

Correct! $3^3 = 3 times 3 times 3 = 27$.

Incorrect. 3 * 3 is 9, but $3^3 = 27$.

Incorrect. Exponentiation is repeated multiplication.

Incorrect. $3^4 = 81$, whereas $3^3 = 27$.

Question 1 of 0

9.2. Comparison Operators

Comparison operators evaluate expressions and return a Boolean value (True or False):

  • Equal to (==): Returns True if both operands are equal.

  • Not equal to (!=): Returns True if operands are not equal.

  • Greater than (>) and Less than (<): Standard inequality checks.

  • Greater than or equal to (>=) and Less than or equal to (<=): Inclusive boundary checks.

x = 10
y = 20

print(x == y)  # False
print(x != y)  # True
print(x < y)   # True
print(x >= 10) # True

9.2.1. Quiz: Comparison Operators

9.2.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
True
assignment
comparison
equal
not equal

1. To check if two values are Drop here in Python, use the == operator.
2. A single `=` sign is used for Drop here, while `==` is used for comparison.
3. The != operator checks whether two values are Drop here.
4. A Drop here operators always return a Boolean result (`True` or `False`).
5. The expression `10 >= 10` evaluates to Drop here.

9.2.1.2. Code Ordering Examples

Example 1: Check if a user’s age qualifies for a adult ticket (18 or older).

Drag and drop lines into the correct order and click to adjust indentation:
☰
age = 20
☰
print(is_adult)
☰
is_adult = age >= 18

Example 2: Compare two test scores to see if they are different.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(are_different)
☰
score2 = 90
☰
score1 = 85
☰
are_different = score1 != score2

Example 3: Check if a given number falls below a ceiling limit.

Drag and drop lines into the correct order and click to adjust indentation:
☰
limit = 100
☰
is_under = current < limit
☰
current = 85
☰
print(is_under)

9.2.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What is the difference between = and == in Python?

Correct! Single = sets values; double == compares values.

Incorrect. Roles are reversed.

Incorrect. = is assignment; == is comparison.

Incorrect. == compares any compatible data types.

What does 15 != 15 evaluate to?

Correct! 15 is equal to 15, so “not equal to” evaluates to False.

Incorrect. Expression checks if values are different.

Incorrect. Comparison operators output Booleans.

Incorrect. Valid syntax comparison.

Which expression evaluates to True?

Correct! 7 is equal to 7, satisfying less than or equal to.

Incorrect. 5 is smaller than 10.

Incorrect. 8 equals 8, so != is False.

Incorrect. 12 is greater than 10.

What is returned by "apple" == "Apple" in Python?

Correct! Python string comparison is case-sensitive (‘a’ != ‘A’).

Incorrect. Capitalization causes string mismatch.

Incorrect. String comparison is valid.

Incorrect. Both operands are string types.

What is the result of 100 >= 50?

Correct! 100 is greater than 50.

Incorrect. 100 exceeds 50.

Incorrect. Relational comparisons output Booleans.

Incorrect. Relational operations do not return numeric operands.

What is the evaluation of 5 < 5?

Correct! 5 is equal to 5, not strictly less than 5.

Incorrect. Strict less-than requires a smaller value.

Incorrect. Comparison yields Boolean False.

Incorrect. Valid comparison syntax.

Which operator checks if a value is less than or equal to another?

Correct! Less than or equal operator is written as <=.

Incorrect. Operator syntax requires < followed by =.

Incorrect. Comparison operators consist of maximum two characters.

Incorrect. != checks for inequality.

What will 3.0 == 3 return in Python?

Correct! Python converts numeric types during comparison; float 3.0 equals integer 3.

Incorrect. Numeric comparison checks equal mathematical value.

Incorrect. Python permits float and int numeric comparisons.

Incorrect. Valid comparison syntax.

Given a = 5 and b = 10, what does a > b evaluate to?

Correct! 5 is not greater than 10.

Incorrect. 5 is smaller than 10.

Incorrect. Relational checks return Booleans.

Incorrect. Operands are not returned.

What does "cat" != "dog" evaluate to?

Correct! The string “cat” is not equal to “dog”.

Incorrect. The strings are distinct.

Incorrect. Relational comparisons return Booleans.

Incorrect. Valid string comparison.

Question 1 of 0

9.3. Logical Operators

Logical operators combine or modify Boolean expressions:

  • and: Returns True only if both conditions evaluate to True.

  • or: Returns True if at least one condition evaluates to True.

  • not: Inverts a Boolean value (turns True to False and vice versa).

age = 15
has_permission = True

# Both conditions must be True
can_enter = (age >= 13) and has_permission  # True

# At least one condition must be True
is_weekend = False
is_holiday = True
no_school = is_weekend or is_holiday       # True

# Invert result
print(not is_weekend)                       # True

9.3.1. Quiz: Logical Operators

9.3.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
False
True
and
not
or

1. The Drop here operator returns `True` only if all connected conditions are true.
2. The Drop here operator returns `True` if at least one connected condition is true.
3. The Drop here operator reverses or inverts a Boolean truth value.
4. The expression `True and False` evaluates to Drop here.
5. The expression `not False` evaluates to Drop here.

9.3.1.2. Code Ordering Examples

Example 1: Check if a number is within a valid range between 10 and 20 inclusive.

Drag and drop lines into the correct order and click to adjust indentation:
☰
num = 15
☰
print(is_valid)
☰
is_valid = (num >= 10) and (num <= 20)

Example 2: Determine if a person gets free entry (child under 5 or senior over 65).

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(free_entry)
☰
age = 70
☰
free_entry = (age < 5) or (age > 65)

Example 3: Check if game over condition is NOT met.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(keep_playing)
☰
keep_playing = not game_over
☰
game_over = lives == 0
☰
lives = 3

9.3.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What does (5 > 2) and (10 < 5) evaluate to?

Correct! True and False evaluates to False because ‘and’ requires both conditions to be True.

Incorrect. Second condition (10 < 5) is False.

Incorrect. Logical operators evaluate to Booleans.

Incorrect. Valid logical check.

What is the result of (5 > 2) or (10 < 5)?

Correct! First condition (5 > 2) is True, so ‘or’ evaluates to True.

Incorrect. ‘or’ requires only one condition to be True.

Incorrect. Logical checks yield Booleans.

Incorrect. Valid syntax.

What does not (10 == 10) evaluate to?

Correct! 10 == 10 is True; ‘not’ inverts True to False.

Incorrect. ‘not’ negates the truth value of True.

Incorrect. ‘not’ returns a Boolean value.

Incorrect. Valid expression structure.

Which logical operator requires ONLY ONE condition to be true for the overall expression to be true?

Correct! ‘or’ returns True if any operand is True.

Incorrect. ‘and’ requires all operands to be True.

Incorrect. ‘not’ is a unary operator that inverts truth value.

Incorrect. == is a comparison operator, not a logical operator.

What is the output of not (5 > 10)?

Correct! 5 > 10 is False; ‘not False’ evaluates to True.

Incorrect. Inner expression is False, so ‘not’ turns it True.

Incorrect. Operator evaluates to Boolean True.

Incorrect. Valid structure.

What evaluates to True when combining conditions with and?

Correct! ‘and’ requires 100% true conditions.

Incorrect. That describes ‘or’ behavior.

Incorrect. False and False evaluates to False.

Incorrect. First condition being False forces ‘and’ to return False.

Given a = True and b = False, what is a and (not b)?

Correct! b is False, so ‘not b’ is True; True and True evaluates to True.

Incorrect. ‘not b’ turns False into True.

Incorrect. Evaluates to Boolean True.

Incorrect. Expression is syntactically valid.

What is short-circuit evaluation in Python logical operators?

Correct! Python skips evaluating remaining sub-expressions once outcome is fixed.

Incorrect. Short-circuiting affects execution order, not syntax parsing.

Incorrect. Execution remains sequential.

Incorrect. Type casting performs boolean conversion.

What is the result of False or False or True?

Correct! A single True condition causes an ‘or’ chain to evaluate to True.

Incorrect. One condition is True.

Incorrect. Evaluates to Boolean True.

Incorrect. Valid chained logical statement.

What does not (True and False) evaluate to?

Correct! Inside parens evaluates to False; ‘not False’ evaluates to True.

Incorrect. Inner expression yields False, negated to True.

Incorrect. Evaluates to Boolean True.

Incorrect. Valid logical expression.

Question 1 of 0

9.4. Assignment Operators

Assignment operators are used to assign or update variable values:

  • Basic Assignment (=): Assigns right-side value to left-side variable.

  • Add and Assign (+=): Adds value and reassigns result (x += 5 is x = x + 5).

  • Subtract and Assign (-=): Subtracts value and reassigns result (x -= 2 is x = x - 2).

  • Multiply and Assign (*=): Multiplies value and reassigns result (x *= 3 is x = x * 3).

  • Divide and Assign (/=): Divides value and reassigns result (x /= 2 is x = x / 2).

score = 100

score += 10  # score is now 110
score -= 25  # score is now 85
score *= 2   # score is now 170

9.4.1. Quiz: Assignment Operators

9.4.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
doubles
float
shorthand
subtracts
variable

1. The statement `x += 5` is a Drop here equivalent of `x = x + 5`.
2. The -= operator Drop here a value from a variable and reassigns the new value.
3. Running `score *= 2` Drop here the current value stored inside score.
4. Compound assignment operators update variables in-place without repeating the Drop here name twice.
5. Performing `x /= 2` updates `x` to a Drop here data type regardless of initial integer value.

9.4.1.2. Code Ordering Examples

Example 1: Increase a player’s score by 50 points using compound assignment.

Drag and drop lines into the correct order and click to adjust indentation:
☰
score += 50
☰
print(score)
☰
score = 100

Example 2: Apply a 10% discount to a price using the /= or *= operator.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(price)
☰
price *= 0.9
☰
price = 100

Example 3: Count down remaining lives in a video game by 1.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(lives)
☰
lives = 3
☰
lives -= 1

9.4.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

If count = 10, what is the value of count after count += 5?

Correct! count += 5 adds 5 to 10, updating count to 15.

Incorrect. Variable was updated by += operator.

Incorrect. += adds to existing value rather than replacing it with 5.

Incorrect. Addition occurred, not multiplication.

Which statement is equivalent to x = x * 3?

Correct! *= is the compound multiplication assignment operator.

Incorrect. Invalid operator syntax sequence.

Incorrect. **= is compound exponentiation assignment.

Incorrect. Invalid syntax.

Given val = 20, what is val after executing val /= 4?

Correct! Division /= always produces a float result (20 / 4 = 5.0).

Incorrect. /= operator outputs float types in Python 3.

Incorrect. Division was performed, not multiplication.

Incorrect. 20 / 4 evaluates to 5.0.

What is the final value of num after: num = 8; num -= 3; num *= 2?

Correct! $8 - 3 = 5$, then $5 times 2 = 10$.

Incorrect. Operations occur sequentially: subtraction then multiplication.

Incorrect. num -= 3 updates num to 5 first.

Incorrect. Operations involve integers without standard division.

Why do programmers use compound assignment operators (like +=, -=)?

Correct! Compound operators simplify variable update statements.

Incorrect. Variables store single values unless holding collections.

Incorrect. They explicitly update variable values.

Incorrect. Type casting functions perform type conversions.

If n = 4, what does n **= 2 set n to?

Correct! $4^2 = 16$.

Incorrect. **= is exponentiation ($4^2$), not multiplication ($4 times 2$).

Incorrect. Exponentiation multiplies 4 by itself.

Incorrect. Exponent is 2.

Given items = 12, what is the value of items after items %= 5?

Correct! $12 % 5 = 2$ (remainder of 12 divided by 5).

Incorrect. %= performs modulus (remainder), not division.

Incorrect. Remainder is 2.

Incorrect. 12 is not evenly divisible by 5.

What happens if you run x += 1 before defining x?

Correct! Variable x must be defined before its value can be updated.

Incorrect. Variables must exist prior to compound updates.

Incorrect. Python does not auto-initialize unassigned variables.

Incorrect. NameError occurs immediately.

Given text = "Hello", what is text after text += " World"?

Correct! The += operator concatenates strings when applied to string variables.

Incorrect. += appends string to existing string.

Incorrect. String concatenation with += is fully valid.

Incorrect. Valid string compound assignment.

What is the result of a = 10; a //= 3?

Correct! Floor division integer result ($10 // 3 = 3$) is assigned back to a.

Incorrect. //= performs floor division (rounds down to integer).

Incorrect. 1 is remainder (%=); //= computes integer quotient.

Incorrect. Floor division was executed.

Question 1 of 0