You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Operators are symbols that perform operations on values. An expression combines values and operators to produce a result.
a = 10
b = 3
print(a + b) # 13 — addition
print(a - b) # 7 — subtraction
print(a * b) # 30 — multiplication
print(a / b) # 3.3333... — division (always float)
print(a // b) # 3 — floor division (integer result)
print(a % b) # 1 — modulo (remainder)
print(a ** b) # 1000 — exponentiation
Note that regular division (/) always returns a float in Python 3, even if both operands are integers.
Comparisons produce boolean (True or False) results:
x = 5
print(x == 5) # True — equal to
print(x != 3) # True — not equal to
print(x > 3) # True — greater than
print(x < 3) # False — less than
print(x >= 5) # True — greater than or equal
print(x <= 4) # False — less than or equal
Combine boolean expressions with and, or, and not:
age = 25
is_member = True
print(age >= 18 and is_member) # True
print(age < 18 or is_member) # True
print(not is_member) # False
Python uses short-circuit evaluation: with and, if the first operand is false the second is not evaluated; with or, if the first is true the second is skipped.
first = "Hello"
second = "World"
combined = first + ", " + second + "!" # concatenation
print(combined) # Hello, World!
repeated = "ha" * 3
print(repeated) # hahaha
Python provides shorthand compound assignment operators:
count = 10
count += 5 # count = count + 5 -> 15
count -= 3 # count = count - 3 -> 12
count *= 2 # count = count * 2 -> 24
count //= 4 # count = count // 4 -> 6
count **= 2 # count = count ** 2 -> 36
Python evaluates operators in a specific order (highest to lowest precedence):
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.