Home

›

Articles

›

Understanding Operators In Python, With Examples

# Understanding Operators In Python, With Examples

## Key Points

• Python programming language has seven different types of operators: arithmetic, assignment, comparison, logical, identity, membership, and bitwise.
• Arithmetic operators in Python include addition, subtraction, exponentiation, multiplication, division, modulus, and floor division.
• Assignment operators are used to assign values to variables in Python.
• Comparison operators are used to compare two values in Python.
• Logical operators are used to combine conditional statements in Python.

What comes to mind when you hear the term operator? It’s likely your brain automatically thought of mathematical operators, like addition, subtraction, multiplication, etc.

However, when it comes to coding, there are many more operators that can be quite useful. In fact, the Python programming language itself has seven different types of operators:

As you get more familiar with coding in Python, using these operators will come more naturally to you. You’ll find they can be incredibly useful—and, oftentimes, absolutely necessary.

However, without seeing how they interact with code and logic, some of these operators might be challenging to understand. If you’re looking to deepen your knowledge of Python operators, you’ve come to the right place.

We’ll break down what each of these operators are and show you how to use them in your code. By the end of this article, you should feel confident enough to use them on your own.

We’ll start with the easiest operators and build on that knowledge as we move through the coding examples. But first, let’s look at an overview of the different operators you’ll encounter in Python:

## Arithmetic Operators

Before we dive into each of these arithmetic operators, here is the code we’ll be using to talk through how this all works:

The following arithmetic operators are available to use in Python:

When you use addition in a mathematical operation, you are simply adding two numbers together. This is one of the simplest tasks to accomplish in Python.

As you can see in the code above, we can write effortless code in our “add” function to return the sum of x and y. Parameters of x and y get sent to the function, which represents 10 and 5, and Python gives us the following response:

10 + 5 = 15

### Subtraction

Similar to addition, this Python operator is extremely straightforward. When x and y get sent to the “subtract” function, we get the following response:

10 – 5 = 10

### Exponentiation

Another useful arithmetic operator is the exponentiation operator. In our “squared_num” function, it takes one number, then squares it.

Here is the output we receive:

10 squared = 100

### Multiplication

Next, we send those same numbers to the “multiply” function and get this response:

10 * 5 = 50

### Division

Though division is simple at its core, the response is a little bit different than we might expect. When we send x and y to Python, this is what we get:

10 / 5 = 2.0

The division operator hasn’t always worked this way, but in version 3.x of Python, even if you’re working with two integers that divide evenly, you’ll always get a float back as a response when dividing.

For this reason, you should only use division if you’re looking for more precision in your result. If you’re looking to get an integer returned, floor division would be more useful. (We’ll talk about that in a bit.)

### Modulus

If you’re new to programming, it’s possible you might not know what modulus means. To put it simply, modulus will divide two numbers, then return the remainder. If there is no remainder, it will return 0.

One of the most useful ways to use this in programming is to determine whether a number is even or not. In the code above, we used the modulus operator to divide a number by 2.

Then, our if statement printed a message to the console to indicate the number was even if the result of the operation was 0. Any other result means we have an odd number.

So, we get this output from Python:

10 is an even number.

5 is an odd number.

### Floor Division

When we use floor division, we lose the benefit of precision when we’re only looking to get an integer returned. However, if that works for your use case, then that loss of precision won’t make a difference.

Our code for floor division gives us this result:

5 divided by 2 (using floor division) = 2

Really, you know that 5 divided by 2 is 2.5. However, floor division rounds the result down to the lowest possible integer, essentially removing the decimal portion of the result.

## Assignment Operators

The assignment operators are pretty straightforward because they are simply using various methods to assign values to a variable. Check out the table below for all the assignment operators, along with examples:

The last five assignment operators in the list are bitwise operators; we’ll go over those at the end of this article. For right now, it’s enough to know that it applies this assignment logic using bitwise calculations.

## Comparison Operators

The comparison operators are simple to understand because it’s likely you’ve used some of them in basic math already. Check out the table below:

These operators are extremely useful when using if statements in your Python code. Check out the code examples below to see these in action:

## Logical Operators

To expand on our learning of conditionals, we can also use logical operators to make comparisons. There are only a few of these, and they are quite easy to understand:

### And

To see the “and” operator in action, let’s focus on the “withdraw” function. When the program calls this function, it needs to check for two things:

1. An amount over \$0.00
2. An amount that doesn’t exceed the current balance

If we only checked for the amount to be greater than zero, then the account would have gone negative. Likewise, if we tried to subtract a negative amount, the program would add money to the customer’s balance rather than subtract it.

Since the last line of code tried to take more money out than the balance, we receive an error message of “Invalid withdraw amount” when the program runs.

### Or

The “or” operator is similar to “and,” except for one major difference: only one of the conditions needs to be true. Check out the code below to see it in action:

This short program checks the user’s age to see if they get a discount. The “check_discount” function needs one of two things to be true to set this boolean to True:

1. The age must be greater than or equal to 65 (or)
2. The age must be less than or equal to 12

In our program, since the age doesn’t meet either of these requirements, the “else” statement gets executed. So, the customer must pay the full price of the item.

### Not

One way that using the “not” operator can be valuable is in making your code more readable to other programmers who come after you. Here is a code snippet that illustrates how this can be useful:

By naming the variable “tall_enough,” we automatically say that we’re checking to see whether somebody is physically tall enough to do something.

In this code example, we set it to False. So, as you’re reading the if statement, you understand exactly what we’re trying to do: we’re checking to see if someone is not tall enough. If that evaluates as True, then we get this result:

You are not tall enough to ride.

## Identity Operators

Python has two identity operators:

1. is not evaluates as True if two objects are not the same
2. is evaluates as True if two objects are the same

One way you’ll use these identity operators quite a bit is in determining whether something is or is not None. Python uses this keyword to indicate that a variable or object is empty or null. Here are some real-world examples you might have occasion to use:

• Checking to see if a user is or is not logged in (ex: if user is not None)
• Checking data in an object to validate whether the user accurately filled out a form (for passwords, email addresses, usernames, etc.)
• Checking to see if an API or server responded (ex: if response is not None)

Checking for None is also extremely helpful when debugging your code if you’re not getting the results you expect.

Throwing in a simple “print” statement on a variable can tell you whether or not it has any data. If your variable is consistently printing out “None” as its contents, then you can begin to isolate where the problem lies.

## Membership Operators

Python has two membership operators you can use: “in” and “not in.” Put simply, these operators check to see if a sequence is in or not in a data object. Here’s a simple example:

Out in the real world, this algorithm would be much more complex. But, for the sake of a short article, it works to show us how valuable these membership operators can be. In this code, Python will accept a user ID as input from the keyboard, then store that in a variable.

Next, it’s going to check to see if the user input is inside its list of user IDs. If it is, they will get logged in and see the welcome message. If not, they will be denied access because their credentials are invalid.

Membership operators can also be helpful in checking password strength. For instance, let’s say an organization wants their employee passwords to have the following criteria:

1. The length must be at least seven characters
2. It should have both upper and lowercase letters.
3. It should have at least three special characters.

The membership operator would then come in to check to see if these conditions are two—at least for #2 and #3. If it evaluates as False, the employee would need to pick another password, then try again. This cycle will repeat until all conditions are adequately met.

## Bitwise Operators

Last on our list of operators is the bitwise operators. All these operators work with binary numbers. However, you don’t need to know how to turn 10,234 into a binary number. You just need to understand a little bit about how binary works.

In the binary number system, 1 represents on, and 0 represents off.

Since your computer uses the binary number system, it’s helpful to have these bitwise operators that can easily work with binaries. It tends to make your code faster, and it allows for more precision in your calculations.

Here are the bitwise operators you can use in Python:

### &

Let’s take two binary numbers: 1100100 (100) and 0001111 (15). If we used the & operator on these two numbers, we would go down the line to find out where both numbers have a 1 in the value place. With these two numbers, the only common digit they have is in the 4s place. So, the value would be 4.

### |

Now, we’re looking for spots where there’s a 1 in either number. This would give us the following binary number:

1101111 (111)

### ^

This is called the XOR operator. It sounds almost exactly like the previous operator (OR), but there is a slight distinction—there can only be a 1 in one of the numbers. With our example, that would give us the following number:

1101011 (107)

### ~

This is called the NOT operator. Put simply, it flips the digits and returns the complement of a number’s binary representation.

So, if we did this with 100 (1100100), we would get -101 when using a 32-bit binary number, where the leftmost place represents a positive or negative value.

### << / >>

The zero fill left shift operator does exactly that—it shifts the binary number to the left and fills with zeros on the right.  Then the signed right shift moves the digits to the right.

## Wrapping up: Operators in Python

If you’re just beginning your journey into learning Python, you may not have a reason to use most of the operators. However, knowing they are there and how they can help you improve your code will serve you well in your future as a software developer.

With this foundational knowledge, you can start having fun by playing around with each of these operators to see how they work in the code you’ve created.

If you’re feeling overwhelmed by the more complex operators in this article, don’t worry. We’ve all been there. Start with what you know and grow from there. Before you know it, you’ll be coding with Python operators in your sleep!

What are Python operators?

Python operators are special symbols that carry out arithmetic or logical computation. The value that the operator operates on is called the operand. You need operators to do just about anything in this language, from simple projects to the most complex applications.

What is the difference between == and is operator in Python?

The == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands refer to the same object or not.

What does the // operator do in Python?

The // operator in Python is the floor division operator. It returns the largest possible integer from the division operation. For example, 5 // 2 will return 2.

What does the % operator do in Python?

The % operator is the modulus operator in Python. This operator returns the remainder of the division of the number to the left by the number on its right. 10 % 3 will return 1. You get 1 when you perform this calculation since 3 goes into 10 3 times, but there is 1 left over.

#### Tyler Von Harz, Author for History-Computer

Tyler Von Harz is a writer at History-Computer, focusing primarily on computers, cloud computing, programming, and electronics. He brings 15 years of tech industry experience to the table and holds a degree in Software Development earned between 2019 and 2023. For the past ten years, he has owned a computer store where he specializes in PC assembly and repair. Tyler calls Philadelphia home and enjoys exploring electronics in his free time. In addition to writing for several publications, he often updates his YouTube channel with insightful tutorials.

Read articles by Tyler Von Harz

This site uses Akismet to reduce spam. Learn how your comment data is processed.