Hey there! If you‘re new to Python, some of the syntax and constructs can seem confusing at first glance. Operators are one such example – special symbols and keywords that perform a wide variety of operations in code.
Mastering operators may feel daunting as a beginner, but don‘t worry! In this comprehensive guide, we‘ll explore the ins and outs of all seven operator categories step-by-step:
- Arithmetic
- Assignment
- Comparison
- Logical
- Identity
- Membership
- Bitwise
Equipped with an understanding of what each operator does and when to apply them, you’ll be able to write Python code more efficiently and debug issues faster. Let‘s get started!
Arithmetic Operators: Performing Core Calculations
Arithmetic operators are our trusty tools for doing basic math within Python code. You likely recognize them from grade school arithmetic:
# Addition
1 + 1 = 2
# Subtraction
5 - 3 = 2
# Multiplication
2 * 4 = 8
# Division
8 / 2 = 4.0
Here are all the arithmetic operators we have at our disposal in Python:
Operator | Function | Example |
---|---|---|
+ | Addition | X + Y |
– | Subtraction | X – Y |
* | Multiplication | X * Y |
/ | Division | X / Y |
% | Modulus | X % Y |
// | Floor division | X // Y |
** | Exponent | X ** Y |
Let‘s see a few of them applied in code:
# Addition
def sum(x, y):
return x + y
print(sum(10, 5))
# 15
# Modulus example
def is_even(x):
return x % 2 == 0
print(is_even(10)) # True - 10 is even
print(is_even(7)) # False - 7 is odd
# Exponentiation
def square(x):
return x**2
print(square(5))
# 25
As you can see, Python allows us to leverage core math operators flexibly within our code logic.
Up next, let‘s look at how we assign values to variables using assignment operators.
Assignment Operators: Storing Code Values Efficiently
In programming, we need a way to store data values for later manipulation and retrieval. This is where variables come into play.
Assignment operators give us a handy shortcut for declaring variables and setting their values in one line:
my_num = 5
friend_age = 21
The humble = sign take on an important role in Python here by assigning 5 to my_num
and 21 to friend_age
so we can reference them later.
We also have access to compound assignment operators like += and -= that apply an operation while assigning:
my_points = 0
# Long way
my_points = my_points + 100
# Compound assignment
my_points += 100
Here‘s the full lineup of assignment operator options:
Operator | Equivalent To |
---|---|
= | my_var = 5 |
+= | my_var += 5 (my_var = my_var + 5) |
-= | my_var -= 5 (my_var = my_var – 5) |
*= | my_var = 5 (my_var = my_var 5) |
/= | my_var /= 5 (my_var = my_var / 5) |
%= | my_var %= 5 (my_var = my_var % 5) |
//= | my_var //= 5 (my_var = my_var // 5) |
**= | my_var **= 5 (my_var = my_var**5) |
While = on its own works fine, leveraging operators like += and -= can save you time and simplify your code.
Now let‘s examine comparison operators that evaluate two values against one another.
Compare Values with Equality and Relational Operators
When coding programs with logic flow based on conditions, we need a way to evaluate and compare data values.
In math class, you used relational operators like > (greater than) and < (less than) to compare numbers. Python gives us similar comparison operators to accomplish the same goals:
Operator | checks if | True example |
---|---|---|
== | Equal to | 5 == 5 |
!= | Not equal | 5 != 7 |
> | Greater than | 7 > 5 |
< | Less than | 5 < 7 |
>= | Greater or equal | 5 >= 5 |
<= | Less than or equal | 5 <= 7 |
Let‘s see some usage examples:
# Simple equality check
if user_age == 25:
print("Quarter life crisis impending")
# Not equal
if choice != "Y":
print("Please enter Y for Yes")
# Greater than
if steps > 10000:
print("You hit your daily goal!")
# Less than or equal
if points <= 0:
print("Game over :(")
As you can see, comparison operators allow us to check conditions then execute different behavior based on the Boolean (True/False) result.
Hmmm…but what if we want to combine multiple comparison checks, so that both conditions must pass? That‘s where logical operators come in…
Logical Operators: Combining Condition Checks
Logical operators give us more complex conditional processing capabilities by chaining multiple comparison statements together.
The three logical operators available in Python are:
Operator | What it does |
---|---|
and | Checks if both comparisons are True |
or | Checks if either comparison is True |
not | Flips/inverts the Boolean result |
For example, say we‘re building a security access system that requires a valid ID badge AND a correct PIN code to unlock doors. We could model this using and
:
access_granted = False
if badge_scan == True and pin_valid == True:
print("Welcome! Doors unlocked.")
access_granted = True
else:
print("ERROR: Access denied.")
Both checks must pass to set access_granted = True
. If either comparison fails, access is denied.
The or
operator works similarly but only requires one passing check:
if age >= 65 or military_service == True:
print("You get a discount!")
And not
inverts a Boolean like so:
is_logged_in = True
if not is_logged_in:
print("Please sign in first")
Logical operators give us more intricate code logic capabilities combining expressions.
Up next: special operators for checking identity and membership…
Identity vs Membership: What‘s In a Name?
In addition to checking if values are equal, Python gives us a special is
operator to check if two variables reference the exact same object in memory:
a = [1, 2, 3] # a references object 123
b = a # b references the same object 123
print(a == b) # True, values are equal
print(a is b) # True, both reference same object
Conversely, the is not
operator checks if two variables point to different objects:
a = [1, 2, 3] # Object 123
b = [1, 2, 3] # Distinct object 456, but equal value
print(a == b) # Values are equal
print(a is not b) # References different objects
This distinction is subtle but can make debugging tricky issues easier!
Meanwhile, Python‘s in
and not in
operators check if a value exists within a sequence like a string or list container. This is known as membership:
current_users = ["andy", "bob123", "catleader"]
if "bob123" in current_users:
print("Login successful")
if "hacker1" not in current_users:
print("Invalid username")
We just checked username membership to handle validation and access.
Now, for the final operator type – bitwise operators for math at the binary level…
Bitwise Operators: The Binary Level
Most arithmetic and logic in Python takes place using base 10 decimal numbers, just like we‘re used to.
However, bitwise operators allow us to manipulate binary numbers in code for tasks like managing hardware interactions and encrypting data.
Reminder: Binary systems have only two possible values per digit – 1 or 0. This base-2 foundation is what makes computer logic possible!
Here‘s a summary of available bitwise operators:
Operator | What it does |
---|---|
& | Bits set to 1 where BOTH corresponding bits are 1 |
| | Bits set to 1 if EITHER corresponding bit is 1 |
^ | Bits set to 1 where ONLY one corresponding bit is 1 (xor) |
~ | Flips all bits (1 becomes 0, and 0 becomes 1) |
<< | Shift all bits left by specified amount, adding 0‘s as empty spots on right side |
>> | Shift all bits right by specified amount, losing outermost bits and preserving sign +/- |
While novice Python coders likely won‘t employ bitwise operations initially, recognizing their capabilities helps demystify these operators. Mastering binary-level manipulations expands your value as a well-rounded developer!
We‘ve covered a lot of ground exploring Python‘s operators – from basic math and variable assignment to logic/identity checks and binary-level bit tweaking!
Here are the key operator categories to become very familiar with as a Pythonista:
- Arithmetic: Performing calculations
- Assignment: Storing variable values
- Comparison: Evaluating conditions
- Logical: Combining expressions
- Identity/Membership: Checking objects and sequences
Practice using the core operators above over and over. Cement your knowledge by applying them within sample Python programs and scripts. Start simple!
As you level up your coding skills, bitwise and niche operators will come more naturally in time. For now, get excellent at leveraging the essentials.
You‘ve got this! Allow your curiosity to guide you, one operator at a time…
What will you build next with your updated operator knowledge? Let me know if you have any other Python questions!