print(2 + 10)
print(2 - 10)
print(2 * 10)
print(2 / 10)
12
-8
20
0.2
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.
Examples (with numbers):
print(2 + 10)
print(2 - 10)
print(2 * 10)
print(2 / 10)
12
-8
20
0.2
print(2 == 10)
print(2 != 10)
print(2 < 10)
print(2 <= 10)
print(2 > 10)
print(2 >= 10)
False
True
True
True
False
False
Examples:
= 5
x print(x)
= x + 1
x print(x)
+= 1
x print(x)
5
6
7
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
Examples (for compound expressions):
= 5
x
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
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:
= "My Old Value"
original = original or "My New Value"
new print(new)
My Old Value
= None
original = original or "My New Value"
new print(new)
My New Value