Learning to code? As you dive into Python, you‘ll likely encounter strange symbols and punctuation marks strewn about the code called "operators". I remember feeling bewildered when I first learned programming – what do these obscure symbols like +
, <=
and ^
mean?!
Well, don‘t fret my friend! Operators are essentially little computing workhorses that are key building blocks in writing any program.
In this guide as your virtual coding companion, I‘ll demystify what operators are and overview the common operators we use in Python. My goal is to provide you intuitive explanations of operators with lots of examples so you can gain confidence using them in your own code!
What Are Operators? A Quick History
The formal computer science definition states:
Operators are symbols that perform logical or mathematical work in a program.
So operators let us execute useful operations ranging from math, comparisons, data manipulation and more!
The concept of operators dates all the way back to Boolean algebra in the mid-19th century. English mathematician George Boole defined logical operators like AND, OR and NOT operations. These later evolved into programming constructs implemented across all modern languages today.
Fun fact – Boolean logic operators allowed engineering the first programmable computers in the 1930s and 40s by pioneers like Alan Turing!
So in summary, operators have rich history enabling computation, without which we literally could not program at all!
Operators in Python
In Python, operators work on numeric literals, variables and more complex data structures. They allow you to:
- Perform arithmetic like addition and multiplication
- Assign values to variables
- Compare values for decision making
- Combine multiple true/false conditions
- Work on binary numeric data Represented in bits
…And more!
Python has a rich set of over 20 built-in operators spanning seven types:
Category | Operators | Use |
---|---|---|
Arithmetic | + , - , * , / etc |
Math operations |
Assignment | = , += , -= etc |
Assign variables |
Comparison | == , > , < etc |
Compare values |
Logical | and , or , not |
Combine conditions |
Identity | is , is not |
Test identical objects |
Membership | in , not in |
Check sequence membership |
Bitwise | & , \| , ~ etc |
Binary manipulations |
Let‘s explore each operator category in detail with examples to develop intuition!
Arithmetic Operators
Arithmetic operators are our good old friends from basic math. You likely already have an intuitive sense of how they work.
Python‘s built-in arithmetic operators:
Operator | Name | Operation | Example |
---|---|---|---|
+ | Addition | Sum two numbers | 5 + 2 = 7 |
– | Subtraction | Difference between numbers | 7 - 3 = 4 |
* | Multiplication | Product of two numbers | 4 * 5 = 20 |
/ | True division | Quotient from division | 20 / 5 = 4.0 |
% | Modulus | Remainder of division | 20 % 6 = 2 |
// | Floor division | Quotient rounded down | 20 // 6 = 3 |
** | Exponentiation | First operand raised to power of second | 5 ** 3 = 125 |
Let‘s see some usage examples:
# Addition
num1 = 10
num2 = 3
print(num1 + num2) # 13
# Subtraction
diff = num1 - num2 # 7
# Multiplication
prod = num1 * num2 # 30
# True division always returns float
result = num1 / num2 # 3.3333333333333335
# Floor division discards fractional part
floor_div = num1 // num2 # 3
# Modulus gives remainder after division
remainder = num1 % num2 # 1
# Exponentiation
squared = num2 ** 2 # 9
cubed = num1 ** 3 # 1000
Arithmetic operators enable easily expressing math formulas within code. Plus well optimized built-in operators run faster than calling custom math functions.
Let‘s next learn how assignment operators help store data.
Assignment Operators
The basic assignment operator we all know is the humble =
sign. It allows storing a value into a variable.
num = 10 # Assign num to 10
But assignment can do more than just directly set variables!
We have compound assignment operators that perform an operation and assignment together in one step.
For example:
num = 10
num += 5 # Shorthand for num = num + 5. Num becomes 15
num *= 2 # Num gets multiplied by 2 becoming 30
The full list of assignment operators:
Operator | Equivalent to |
---|---|
= |
x = 5 |
+= |
x = x + 5 |
-= |
x = x - 5 |
*= |
x = x * 5 |
/= |
x = x / 5 |
%= |
x = x % 5 |
//= |
x = x // 5 |
**= |
x = x ** 5 |
&= |
x = x & 5 |
|= |
x = x | 5 |
^= |
x = x ^ 5 |
>>= |
x = x >> 5 |
<<= |
x = x << 5 |
The last five are bitwise assignments that work at the binary level (we‘ll cover them later!).
These operators streamline writing code by reducing repetition. Plus the combined operation is more efficient than doing the steps individually.
Let‘s next overview comparison operators!
Comparison Operators
These compare two values resulting in a True / False or 1 / 0 outcome.
For example:
print(5 > 3) # True, 5 is greater than 3
print(4 == 4) # True, 4 equals 4
print(3 != 5) # True, 3 is not equal to 5
The comparison operators supported in Python:
Operator | Meaning | Example |
---|---|---|
== |
Equal to | 5 == 5 |
!= |
Not equal | 5 != 3 |
> |
Greater than | 5 > 3 |
< |
Less than | 3 < 5 |
>= |
Greater than or equal | 4 >= 4 |
<= |
Less than or equal | 5 <= 9 |
These expressions evaluate to either True or False.
For example:
age = 18
is_adult = age >= 18 # True
grade = ‘A‘
is_top_student = grade == ‘A‘ # True
We can use comparison operators to control program flow based on Boolean checks:
min_age = 13
user_age = 15
if user_age >= min_age:
print("You may sign up!")
else:
print("You are not old enough :(")
As you can see, comparison operators enable quite useful logic in code!
Up next: Logical operators…
Logical Operators
Logical operators let you combine multiple Boolean (True / False) conditions and evaluate them to a single Boolean output.
The three logical operators are:
Logical Operator | Meaning | Example |
---|---|---|
and |
True IF both operands are true | x > 0 and x < 10 |
or |
True IF either operand is true | x > 0 or x < 0 |
not |
Flips / negates a condition | not(x == 0) |
Here are some usage examples:
user_age = 7
required_age = 5
# User age > 5 AND age < 10?
can_register = user_age > required_age and user_age < 10
# True AND True = True
is_admin = False
is_moderator = True
# Is admin OR moderator?
has_privileges = is_admin or is_moderator
# False OR True = True
# NOT admin?
not_admin = not is_admin
# Converts True -> False
We can combine multiple logical operators:
age = 20
min_age = 16
max_age = 65
can_run = age > min_age and age < max_age
print(can_run) # True
Logical operators multiply what you can express in code by enabling complex Boolean logic chains!
Now let‘s contrast equality and identity checks…
Identity vs Equality
Python specifically differentiates between:
- Value equality: Do the values match? Uses
==
operator. - Identity: Do operands refer to the exact same object in memory? Uses the
is
operator.
For example:
a = [1,2,3] # Create list
b = [1,2,3] # Create second identical list
print(a == b) # True, SAME CONTENT
print(a is b) # False, unique objects!
Here both lists contain the same values so equality matches. But they reference two unique list objects in memory hence identity doesn‘t match.
Let‘s tweak the example:
a = [1,2,3]
b = a # Reference same list
print(a == b) # Values match
print(a is b) # Identical objects!
Now a
and b
point to the exact same list object so both equality AND identity match!
While equality checks (==
) are more common, is
/ is not
comparisons come in handy dealing with tricky mutable object scenarios in Python.
Up next: Membership operators!
Membership Operators
These check whether a value is present within a sequence data structure like strings, lists, dicts etc.
The two membership check operators are:
Operator | Checks if value… |
---|---|
in |
Is present within the sequence |
not in |
Is NOT present within the sequence |
For example:
colors = [‘blue‘, ‘green‘, ‘red‘]
print(‘blue‘ in colors) # True
print(‘purple‘ not in colors) # True, ‘purple‘ absent
Common use cases:
- Check user permissions / credentials
- Validate form data
- Signal handling for application events
- Access control lists
Code scenarios:
user_roles = [‘admin‘, ‘moderator‘, ‘user‘]
is_admin = ‘admin‘ in user_roles # True
requested_toppings = [‘cheese‘, ‘onion‘, ‘olives‘]
has_onion = ‘onion‘ in requested_toppings # True
letter_grades = [‘A‘, ‘B‘, ‘C‘]
is_top_grade = ‘A‘ in letter_grades # Check for grade
So in summary, membership operators enable set-like membership checks on Python sequences!
Finally, let‘s learn about bitwise operators that manipulate bits…
Bitwise Operators
These allow manipulating numbers at the binary level. Several programming domains rely on bit manipulation like data streams, flags protocols and machine learning.
Here is the set of Python bitwise operators:
Operator | Name | Operation | Binary example |
---|---|---|---|
& |
AND | Bits set to 1 where both bits are 1 | 1 & 1 = 1 , 1 & 0 = 0 |
| |
OR | Bits set to 1 if either bit is 1 | 1 | 1 = 1 , 1 | 0 = 1 |
^ |
XOR | Bits set to 1 where bits differ | 1 ^ 0 = 1 , 1 ^ 1 = 0 |
~ |
NOT | Flips bits: 0 -> 1, 1 -> 0 | ~1 = 0 , ~0 = 1 |
<< |
Left shift | Shift left filling empty bits with 0 | 0010 << 2 = 1000 |
>> |
Right shift | Shift right preserving sign bit | 1000 >> 1 = 0100 |
Here is how we can bitwise operations in Python:
print(0b110 & 0b010) # Bitwise AND
# Prints: 0b010
print(0b110 | 0b001) # Bitwise OR
# Prints: 0b111
a = 2 # Decimal 2
b = a << 1 # Bit shift left by 1 bit
print(b) # 4
x = ~0b111 # Invert bits
print(x) # -4
While bitwise operators seem niche, they find use from data serialization to hacking programming challenges!
Putting Operators to Work
We‘ve covered a whole lot of ground understanding Python operators. Here is a handy recap:
- Arithmetic – Mathematical operators
- Assignment – Store data
- Comparison – Enable decisions
- Logical – Combine conditions
- Identity vs Equality – Unique or identical
- Membership – Check inclusion
- Bitwise – Binary manipulation
Operators are small but enable BIG things in coding from math to complex logic!
I suggest playing with them live in code examples to gain true intuition. Try variations like:
- Arithmetic on integers vs floats
- Chaining logical operators
- Bit shifting and flipping numbers
Initially operators seem esoteric. But if you experiment actively with examples, they start feeling comfortable quickly!
So over to you my friend! Try using operators in fun coding projects and see what cool logic you can create 🙂
Let me know if any questions pop up!