5  Python Operators

We have seen examples of arithmetic operators, and the double equals sign, but let’s cover a wide range of operators in Python.

The Python Operators page from W3 Schools provides an excellent overview. Contents copied below for reference.

5.1 Arithmetic Operators

Arithmetic Operators. Source: W3 Schools

Examples (with numbers):

print(2 + 10)
print(2 - 10)
print(2 * 10)
print(2 / 10)
12
-8
20
0.2

5.2 Comparison Operators

Comparison Operators. Source: W3 Schools
print(2 == 10)
print(2 != 10)

print(2 < 10)
print(2 <= 10)

print(2 > 10)
print(2 >= 10)
False
True
True
True
False
False

5.3 Assignment Operators

Assignment Operators. Source: W3 Schools

Examples:

x = 5
print(x)

x = x + 1
print(x)

x += 1
print(x)
5
6
7

5.4 Membership Operators

Membership Operators. Source: W3 Schools

Examples (with strings):

print("H" in "Hello World")
print("H" not in "Hello World")
True
False

Examples (with lists):

print(5 in [1,2,5])
print(5 not in [1,2,5])
True
False

5.5 Logical Operators

Logical Operators. Source: W3 Schools

Examples (for compound expressions):

x = 5

print(x > 0 and x > 20)
print(x > 0 or x > 20)
False
True

The and operator will return True if BOTH sides are true.

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

The or operator will return True if EITHER side is true.

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

5.5.1 Truthiness

Another way of using the or operator is within the concept of “truthiness”.

In this context, the or operator will return the first “truthy” value.

Values that are considered “truthy” are True, or any other object that is present or non-empty, or non-blank.

Values that are considered “falsy” are False, None, empty string (""), empty list ([]), etc.

0 or "" or [] or False or None or 4 or "Hello World" or True
4

In this case, we see 4 returned because it is the first truthy value.

In practice, we usually use “truthiness” to set a value if it is not null:

original = "My Old Value"
new = original or "My New Value"
print(new)
My Old Value
original = None
new = original or "My New Value"
print(new)
My New Value