Python Basics
Python Operators
Operators are special symbols that perform operations on values and variables, and Python groups them into a few useful categories.
Arithmetic Operators
These perform basic math, such as addition, subtraction and multiplication, which you already saw in the numbers lesson.
print(10 + 3, 10 - 3, 10 * 3, 10 / 3, 10 // 3, 10 % 3, 10 ** 2)Comparison Operators
These compare two values and always return a boolean result, True or False.
print(5 == 5, 5 != 3, 5 > 3, 5 < 3, 5 >= 5, 5 <= 4)Logical Operators
and, or and not combine or invert boolean expressions, which is essential for writing more complex conditions later.
age = 22
has_id = True
print(age >= 18 and has_id) # True
print(age < 18 or has_id) # True
print(not has_id) # FalseAssignment Operators
Assignment operators store a value in a variable, and shorthand versions like += update a variable based on its current value.
score = 10
score += 5 # same as score = score + 5
print(score) # 15Membership and Identity Operators
in and not in check whether a value exists inside a collection like a list or string, while is and is not check whether two variables point to the exact same object in memory.
fruits = ["apple", "mango"]
print("apple" in fruits) # True
print("banana" not in fruits) # True
x = None
print(x is None) # TrueQuick Reference Table
| Category | Operators |
|---|---|
| Arithmetic | + - * / // % ** |
| Comparison | == != > < >= <= |
| Logical | and or not |
| Assignment | = += -= *= /= |
| Membership | in not in |
| Identity | is is not |
Use == to compare values and is only when you specifically need to check object identity, such as comparing against None.
