Operators

Operators are special symbols (or, in some cases, words) that perform operations on values and variables. Python groups them into a few families: arithmetic, comparison, logical, assignment, identity, and membership operators.

Arithmetic Operators

These perform basic mathematical calculations.

OperatorMeaningExampleResult
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/True division (always returns a float)5 / 22.5
//Floor division (rounds down to the nearest whole number)5 // 22
%Modulus (remainder)5 % 21
**Exponent (power)5 ** 225

The difference between / and // trips up a lot of newcomers: / always gives you a precise float result, while // throws away anything after the decimal point and gives you back a whole number.

print(7 / 2)   # 3.5
print(7 // 2)  # 3

Comparison Operators

Comparison operators compare two values and always produce a bool result (True or False).

a = 10
b = 20

print(a == b)  # False, equal to
print(a != b)  # True, not equal to
print(a > b)   # False, greater than
print(a < b)   # True, less than
print(a >= b)  # False, greater than or equal to
print(a <= b)  # True, less than or equal to

Logical Operators

Unlike C-family languages that use &&, || and !, Python spells its logical operators out as the words and, or, and not.

age = 25
has_id = True

print(age > 18 and has_id)   # True, both conditions are true
print(age < 18 or has_id)    # True, at least one condition is true
print(not has_id)             # False, reverses the value

Assignment Operators

Beyond the plain =, Python offers shorthand operators that update a variable based on its current value.

x = 10
x += 5   # same as x = x + 5, now x is 15
x -= 3   # same as x = x - 3, now x is 12
x *= 2   # same as x = x * 2, now x is 24
x /= 4   # same as x = x / 4, now x is 6.0
print(x)

Identity vs Equality: is vs ==

This is one of Python's most important gotchas. == checks whether two values are equal, while is checks whether two names refer to the exact same object in memory. Two variables can hold equal values without being the same object.

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

print(a == b)  # True, same contents
print(a is b)   # False, two different list objects in memory
print(a is c)   # True, c points to the exact same object as a

Note: Use == when you want to compare values (the usual case). Reserve is for checking identity, such as the common idiom if x is None:.

Membership Operators

in and not in test whether a value exists inside a sequence such as a string, list, or tuple.

fruits = ["apple", "banana", "cherry"]

print("banana" in fruits)      # True
print("mango" not in fruits)  # True
Next steps: Head to Strings to work with text data in detail.