Python Tutorials

Python Operators

Operators are the “action words” of Python. If variables and values are the data you store, operators are the instructions that tell Python what to do with that data—add it, compare it, check membership, and more.

This chapter will walk you through the most commonly used operators in Python, with small examples you can try immediately. Each example is followed by a clear explanation of what the code does, why the result is what it is, and common follow-ups you may want to try.

Arithmetic Operators

Arithmetic operators perform math on numbers. You’ve already seen + for addition; Python also provides subtraction, multiplication, division, and a few operators that are especially useful in programming.

Addition and subtraction (+, -)

Addition and subtraction behave as you’d expect:

print(10 + 5)   # 15
print(10 - 5)   # 5

Explanation:

  • 10 + 5 evaluates the sum of the two integers and prints 15. Python adds numeric literals in the same way you would on paper.
  • 10 - 5 subtracts the second operand from the first and prints 5.

Why this matters: These simple operators are the foundation for all numeric calculations in code. Try replacing the literals with variables or expressions (e.g., a + b * c) to see operator precedence in action.


Multiplication (*)

The multiplication operator is an asterisk *.

print(6 * 7)    # 42

Explanation:

  • 6 * 7 multiplies the two numbers and prints 42. When one or both operands are floats (e.g., 6.0 * 7), the result will be a float.

Try this: Multiply variables, or use multiplication with floats to observe type changes.


Exponentiation (**)

Exponentiation raises a number to a power using **.

print(5 ** 2)   # 25
print(2 ** 5)   # 32

Explanation:

  • 5 ** 2 computes 5 to the power of 2 and prints 25.
  • 2 ** 5 computes 2 to the power of 5 and prints 32.

Context: Exponentiation is useful for calculations involving growth, bit shifts when powers of two are relevant, and mathematical formulas.


Division (/) returns a float

Division uses a forward slash /. In Python, regular division returns a floating-point number (a decimal), even when the result looks like a whole number.

print(20 / 5)   # 4.0
print(20 / 6)   # 3.3333333333333335

Explanation:

  • 20 / 5 mathematically equals 4, but Python prints 4.0 because / always yields a float.
  • 20 / 6 results in a non-terminating decimal which Python prints as a floating-point approximation 3.3333333333333335.

Why floats by default: Returning a float avoids accidentally losing fractional information. If you specifically need an integer quotient, use floor division //.


Floor division (//) for “whole number” division

Sometimes you want the quotient without the decimal part. That’s what floor division // does.

print(20 // 6)  # 3
print(21 // 6)  # 3

Explanation:

  • 20 // 6 divides 20 by 6 and drops the fractional part, giving 3.
  • 21 // 6 similarly gives 3 because 21/6 is 3.5 and floor division truncates toward negative infinity (so it gives 3).

Important nuance with negatives: For negative results, // behaves differently than simple truncation: -7 // 3 yields -3, not -2. Test negative cases to understand this fully.


Modulus (%) for the remainder

The modulus operator % gives the remainder after division.

print(20 % 6)   # 2

Explanation:

  • 20 % 6 computes the remainder when 20 is divided by 6. Since 6 * 3 = 18 and 20 - 18 = 2, the modulus is 2.

Common uses:

  • Determining even/odd numbers: number % 2 == 0 checks for evenness.
  • Scheduling or cycling through indices: i % n gives a repeating sequence 0..n-1.
number = 14
print(number % 2 == 0)  # True

for i in range(1, 11):
    if i % 3 == 0:
        print(i, "is divisible by 3")

Explanation of the loop:

  • range(1, 11) produces numbers 1 through 10. i % 3 == 0 checks whether i leaves no remainder when divided by 3; the print executes only for those values.

[ Output showing modulus-based checks]


Operators with Strings

Operators aren’t limited to numbers. Python also supports a couple of useful operations on strings.

String concatenation with +

Using + with strings joins them together.

first = "Hello"
second = "World"
print(first + " " + second)  # Hello World

Explanation:

  • first + " " + second concatenates three strings: the first variable, a single space, and the second variable, producing the combined string Hello World.

Type rule reminder: + for strings requires both operands to be strings. Combining a string and a number directly raises a TypeError.

# print("Age: " + 25)  # TypeError
print("Age: " + str(25))  # Age: 25

Why str() or f-strings: Converting non-string types with str() or using f-strings (f"Age: {age}") is preferable because it’s readable and avoids type errors.


String repetition with *

Multiplying a string by a number repeats it.

print("Hi! " * 4)  # Hi! Hi! Hi! Hi!

Explanation:

  • The * operator for strings duplicates the string the specified number of times and concatenates the results. Here, "Hi! " * 4 creates a single string with Hi! repeated 4 times.

Use cases: Building simple separators, creating test data, or drawing ASCII art lines.


Comparison Operators

Comparison operators evaluate two values and return a Boolean: True or False.

Equality and inequality (==, !=)

== checks whether two values are equal.

print(True == True)     # True
print(10 == 10)         # True
print(10 == 11)         # False

!= checks whether two values are not equal.

print(10 != 11)         # True

Explanation:

  • == returns True when the values compared are equivalent in value. For built-in types this behavior is predictable, but for custom objects the class may define its own equality logic.
  • != is simply the logical inverse of == and is often used when you want to exclude a certain value.

Less-than and greater-than (<, <=, >, >=)

These operators compare numeric values (and also work with strings in alphabetic order, though you’ll use them most often with numbers).

print(4 < 5)            # True
print(5 <= 5)           # True
print(5 > 2)            # True
print(5 >= 2)           # True

Explanation:

  • These comparisons evaluate relationships between values. For strings, Python compares lexicographically (based on character codes), which can be surprising if you mix uppercase and lowercase letters.

Practical tip: When comparing floating point numbers for equality, small rounding errors can occur. For sensitive comparisons, check whether values are within a small tolerance (e.g., abs(a-b) < 1e-9).

A common beginner mistake is confusing assignment (=) with comparison (==). Use = to store a value in a variable, and == to compare values.

[Example showing = vs == in code]


Logical Operators (and, or, not)

Logical operators combine or flip Boolean values. They read like plain English, which makes them easier to remember.

and

With and, both sides must be True for the whole expression to be True.

print(True and True)    # True
print(True and False)   # False

Explanation:

  • True and True returns True because both operands evaluate to True.
  • True and False returns False because one operand is False.

or

With or, at least one side must be True.

print(True or False)    # True
print(False or False)   # False

Explanation:

  • True or False is True because one of the operands is True.
  • False or False is False because neither operand is True.

not

not flips a Boolean value.

print(not True)         # False
print(not False)        # True

Practical note — short-circuit evaluation:

  • Python evaluates and and or with short-circuiting. For and, if the left operand is falsey, Python skips evaluating the right side because the expression cannot be True. For or, if the left operand is truthy, Python skips the right side. Use this to write concise defaults, but avoid placing expensive operations on the skipped side if you rely on them.

Example in conditions:

age = 20
has_id = True

if age >= 18 and has_id:
    print("Allowed")
else:
    print("Not allowed")

Explanation:

  • The if statement runs the print("Allowed") only if both age >= 18 and has_id are True. This pattern appears frequently in access checks and validations.

Membership Operators (in, not in)

Membership operators check whether a value exists inside a sequence (like a list, tuple, set, or string). They also return True or False.

Checking membership in lists

numbers = [1, 2, 3, 4, 5]
print(1 in numbers)         # True
print(10 in numbers)        # False
print(10 not in numbers)    # True

Explanation:

  • 1 in numbers scans the list and returns True because 1 is an element.
  • 10 in numbers is False because 10 does not appear.
  • 10 not in numbers is the inverse check and returns True.

Checking membership in strings

You can also search inside strings.

text = "my pet cat"
print("cat" in text)       # True
print("dog" in text)       # False

Explanation:

  • "cat" in text is True because the sequence of characters c-a-t appears in the string.
  • Be careful: substring matching is character-based, not word-based. For example, "cat" in "catatonic" returns True, which may be undesirable if you intended to check for whole words.

[ Membership checks with list and string]


Identity Operators (is, is not)

Identity operators check whether two variables refer to the same object in memory, not whether they merely have the same value.

This is different from ==.

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)   # True  (values are the same)
print(a is b)   # False (different objects)

Explanation:

  • a == b returns True because both lists have the same contents.
  • a is b returns False because a and b point to different list objects in memory.

Common idiom: Use is when checking for None:

value = None

if value is None:
    print("No value yet")

This is the recommended way to check for the absence of a value.


Operator Precedence

When you combine operators, Python follows a precedence order (similar to math). Multiplication happens before addition, and parentheses can force an order.

print(2 + 3 * 4)     # 14
print((2 + 3) * 4)   # 20

Explanation:

  • In 2 + 3 * 4, multiplication runs first (3 * 4 = 12) and then addition makes 14.
  • With parentheses, (2 + 3) is evaluated first, producing 5, and then 5 * 4 = 20.

Advice: Use parentheses liberally to document your intended evaluation order. It improves readability and reduces bugs.


Practice

Type these into your Python environment and predict the result before running them:

print(17 % 5)
print(9 // 2)
print("na" * 4 + " Batman!")
print(10 / 2)
print(5 <= 5)
print(True and not False)
print("py" in "python")

x = None
print(x is None)

What to observe:

  • For 17 % 5, identify the remainder.
  • For 9 // 2, notice how floor division discards fractional parts.
  • For the string operations, see how repetition and concatenation interact.
  • x is None demonstrates a canonical identity check.

Summary

Operators are how you tell Python to work with your data. Arithmetic operators handle math (including helpful tools like % for remainders), strings can be joined and repeated using + and *, and comparison/logical/membership operators help you make decisions by producing True or False. Identity operators, especially is None, are a clean way to check for “no value.”

In the next chapters, you’ll use these operators constantly inside conditions, loops, and real programs—so it’s worth practicing until the results feel natural.

Leave a Comment