Operators in Python: Arithmetic, Comparison, and Logical Operations
If you want your program to perform calculations, compare values, or make decisions, you’ll need to understand operators. These are special symbols or keywords that tell Python what to do with the data.
In this article, we’ll cover the three most important types of operators in Python:
Let’s break it all down step by step ??
?? 1. Arithmetic Operators
Arithmetic operators are used for basic math operations. They work with numeric types like int and float.
a = 10
b = 3
print(a + b) # addition → 13
print(a - b) # subtraction → 7
print(a * b) # multiplication → 30
print(a / b) # division → 3.333...
?? Division using / always returns a float, even if the result is a whole number.
Python also offers more advanced math operators:
print(a // b) # floor division → 3
print(a % b) # modulus (remainder) → 1
print(a ** b) # exponentiation → 1000
When to use these?
?? 2. Comparison Operators
Comparison (or relational) operators are used to compare two values. The result is always either True or False.
x = 10
y = 5
print(x == y) # is x equal to y? → False
print(x != y) # is x not equal to y? → True
print(x > y) # is x greater than y? → True
print(x < y) # is x less than y? → False
print(x >= y) # is x greater or equal to y? → True
print(x <= y) # is x less or equal to y? → False
Real-world use:You’ll often use comparison operators when making decisions in your code. For example:
age = 20
print(age >= 18) # True → the user is an adult
?? Don’t confuse == (equality check) with = (assignment operator).
领英推荐
?? 3. Logical Operators
Logical operators are used to combine multiple expressions or conditions. The result is again either True or False.
a = 5
b = 10
print(a > 0 and b > 0) # True → both are positive
print(a > 0 or b < 0) # True → the first is true, second is false
print(not a > 0) # False → because a > 0 is True, and `not` flips it
Why use logical operators?
They allow you to create more complex logic like:
“Is the user over 18 and has a valid ticket?” or
“Is it the weekend or does the user have a vacation day?”
?? Key Takeaways
? Use +, -, *, /, //, %, ** for math operations
? Use ==, !=, >, <, >=, <= to compare values
? Use and, or, not to combine or invert conditions
? The result of comparisons and logic is always True or False
? Operators are the foundation for control flow, conditions, and functions