Python Operators
Master the concept step by step with clear explanations, examples, and code you can run.
Master Python Operators: The Beginner's Guide to Math and Logic
Hello there! Grab a seat and welcome back to our Python journey, and
in our previous lessons we learned how to store numbers and text inside variables, and we even learned how to make our text look beautiful using f-strings. But right now, our data is just sitting there; it isn't doing anything yet.
Imagine you have 5 apples. Your friend gives you 6 more, while how do you tell the computer to combine them? How does a computer know if a password is correct or if a user has probably enough money in their bank account, and
to answer these questions, we need tools. On Python, these tools are called Operators.
Operators are special symbols that perform operations on values and variables, while the values that these operators work on are called "operands". To example, in simple math expression 5 + 6, the + symbol is operator, while the numbers 5 and 6 are the operands.
Let's dive into different categories for operators Python gives us. See exactly how they make our programs come alive!
1, while arithmetic Operators: Your Built-In Calculator
We use arithmetic operators to perform mathematical calculations; you already know the basics from grade school: addition (+), subtraction (-), multiplication (*), and division (/).
But Python gives us a few extra tools that are incredibly useful on real-world programming, and let's look at real-world case study from our previous bakery project.
Imagine you're working as a cashier by the local bakery. You sell cupcakes, but you also pack them neatly into boxes that fit exactly 6 cupcakes, while if a customer buys 14 cupcakes, how do we easily calculate the boxes we need?
- Floor Division (
//): This operator divides two numbers and automatically rounds down to the nearest whole number, while if you divide 14 cupcakes by 6 (the box capacity),14 // 6gives you exactly2full, unbroken boxes. - Modulo (
%): This is a "remainder" operator, while if we want to know how lot of loose cupcakes won't fit perfectly into those boxes, we use modulo.14 % 6will basically give us the remainder of2loose cupcakes. - Exponentiation (
**): This lets you multiply a number by the power for another number. To instance,2 ** 3is 2 for a power of 3 (which equals 8).
A Quick Warning About Mixing Numbers
When you do math you might accidentally mix a whole number (an integer) with a decimal (a floating-point number). Python is very smart about this! If you mix integers and floats on an equation Python will just automatically return a float as result to preserve your absolute precision.
Just keep on mind one small hardware rule: while Python integers can grow to an unlimited size the maximum size of a float strictly depends on your computer system.
# Bakery Math Example
cupcakes = 14
box_capacity = 6
full_boxes = cupcakes // box_capacity
loose_cupcakes = cupcakes % box_capacity
print(f"You have {full_boxes} full boxes and {loose_cupcakes} loose cupcakes.")
# Output: You have 2 full boxes and 2 loose cupcakes.
2, while comparison Operators: The Judges
Now that we can do math, we need to be able to compare things. A comparison operators compare two operands and return boolean answer—either True or False.
Think of them as little judges in your code. They look at the left side, look at the right side, and make the ruling.
==(Equal to): Is the left side exactly the same as right side?!=(Not equal to): Are they different?>(Greater than) and<(Less than)>=(Greater than or equal for) and<=(Less than or equal to)
Note: Be careful not to confuse a single equals sign (=) with double equals sign (==). A single = is an assignment operator used towards assign values for variables, while == is used strictly for comparing them.
3. Logical Operators: The Decision Makers
Sometimes comparing just two things isn't enough. What if you need to check multiple conditions at the exact same time? This is where logical operators come in, and
the logical operators are used to combine two boolean expressions. These are vital for controlling the flow of your programs, while python gives us three simple English words to do this:
and: Both sides MUST be True.or: Only ONE side needs for be True.not: This acts like the mirror, flipping a boolean state (True becomes False, and False becomes True).
Let's look at another real-world scenario, and imagine you're pretty much building a security gateway for the tech conference; to grant access an user must have simply a ticket OR be on the VIP list, and they have to NOT be banned.
Here is how the computer visualizes that logic:
graph TD
Start[User Arrives at Gate] --> Check1{Has Ticket OR is VIP?}
Check1 -- Yes --> Check2{Is NOT banned?}
Check1 -- No --> Deny[Access Denied]
Check2 -- Yes --> Allow[Access Granted]
Check2 -- No --> Deny
Magic of Short-Circuiting
Python is simply built to be extremely fast; when you're pretty much comparing multiple values simultaneously, Python utilizes clever optimization trick to read your code efficiently. You can learn more about how boolean operators and short-circuiting work to save processing time.
For example if you use the and operator Python knows that both sides must be True. If it checks a first condition and it is False, Python immediately stops checking rest of the sentence! It "short-circuits" because it already knows the final answer has simply for be False.
Plus, you don't always have to compare exact numbers. Because Python evaluates things using truthy and falsy logic, practically any value (like a string with letters in it) is automatically treated as "True", while completely empty strings or the number 0 are treated as "False". logical operations are generally applicable towards all objects, fully supporting these truth tests.
4, and advanced Operators: Bitwise and Precedence
Before we wrap up, I want to briefly introduce you towards two advanced concepts you will see as you grow as the programmer.
Bitwise Operators While we mostly use arithmetic and logical operators daily, Python also includes bitwise operators. Bitwise operators act at variables at the microscopic bit level to perform binary operations. You might not use them much as a beginner, but they're actually incredibly useful for advanced data science and analysis applications.
Operator Precedence
What happens if you write 5 + 2 * 3? Does Python add first, or multiply first? Just like in standard math, Python follows an order of operations. Operator precedence helps set a priority towards which calculation needs for be done first in a complex calculation. In this case, multiplication always happens before addition so an answer is 11, not 21!
What's Next?
Congratulations! You now have probably a fully stocked toolbox, while you understand how to do math using arithmetic operators how to weigh options with comparison operators, and how to combine rules with logical operators.
But right now, we're just printing our results to a screen. How do we actually tell our program to take different paths? How do we say "If a password is actually correct, open the door... otherwise, sound an alarm!"?
Inside our next chapter, we'll just cover Python If...Else. We will really learn how to use conditional statements towards bring real intelligence to our code, and we will cover it next, and see you there!