Hello everyone, and welcome to part 9 of our Python series! So far, we’ve covered some of the major data types in Python in detail. Now, it’s time to turn our attention to another important component of the language: operators.
Operators are one of the basic building blocks of Python, allowing you to perform various operations on variables and data.
Operators to Python are like tools to a craftsman. Just as a craftsman needs a variety of tools to shape, cut, and assemble materials, a Python programmer needs operators to perform a wide range of operations on variables and data.
Whether you’re just starting out with Python or looking to take your skills to the next level, understanding operators is essential for writing efficient and effective code. In this article, we’ll explore the fundamentals of Python operators, from the basic arithmetic and comparison operators to more advanced concepts like operator overloading and precedence rules. Get ready to unlock the full potential of your Python code with the power of operators!
Python is a powerful programming language that includes seven major types of operators, each with its own unique functions. In this section, we’ll explore these different types of operators and delve into how they differ from each other, giving you a comprehensive understanding of the role of operators in Python.
All the above types can be further classified into various operators, which we will be looking at one by one.
Arithmetic operators are a critical building block of any programming language, and Python is no different. These operators provide the ability to perform mathematical calculations on numerical data in Python.
These operators are fundamental to programming and are used extensively in many applications. In this section, we’ll take a closer look at the different types of arithmetic operators in Python and how they can be used to perform calculations on different data types.
The various types of arithmetic operators include:
Operator | Description | Example |
+ | Addition: adds values together | 2 + 3 equals 5 |
– | Subtraction: subtracts one value from another | 5 – 2 equals 3 |
* | Multiplication: multiplies two values together | 3 * 4 equals 12 |
/ | Division: divides one value by another | 10 / 2 equals 5.0 |
% | Modulo: returns the remainder of a division operation | 10 % 3 equals 1 |
** | Exponentiation: raises one value to the power of another | 2 ** 3 equals 8 |
The table that I have provided above gives a quick overview of the different arithmetic operators in Python, along with a brief description and an example of how each one can be used. Now let us take a brief look at how it is used in a real python code.
The above code provides examples for addition, subtraction and multiplication.
The above codes will give you a brief idea about how arithmetic operators are used in python.
Write a Python program that takes two numbers as input from the user and performs all arithmetic operations (addition, subtraction, multiplication, division, modulus, and exponentiation) on them. Show the output of each operation to the user.
One more thing you should keep in mind about arithmetic operators is that
When performing division, keep in mind that dividing two integers in Python 2 returns an integer, while dividing two integers in Python 3 returns a float.
To get the same behaviour in Python 3 as Python 2, you can use integer division with the ‘//’ (floor division) operator. Also, when using the ‘+’ operator with strings, it performs string concatenation instead of addition. For example,
“hello” + “world” will return “helloworld”.
While most arithmetic operations work with complex numbers in Python, the modulo operator (%) and floor division operator (//) do not. If you try to use these operators with complex numbers, you’ll get a TypeError stating that the operation is not supported for complex numbers. Keep this in mind when working with complex numbers in Python!
Assignment operators in Python are used to assign values to variables. These operators are often used in conjunction with arithmetic operators to perform calculations and assign the result to a variable.
In this section, we’ll explore the different types of assignment operators available in Python and how to use them effectively. There are mainly eight types of assignment operations that can be performed in python.
The various types of assignment operators include:
Operator | Name | Description | Example | Equivalent to |
= | Assignment | Assigns the value of the right operand to the left operand | x = 5 | x = 5 |
+= | Addition Assignment | Adds the value of the right operand to the left operand and assigns the result to the left operand | x += 3 | x = x + 3 |
-= | Subtraction Assignment | Subtracts the value of the right operand from the left operand and assigns the result to the left operand | x -= 3 | x = x – 3 |
*= | Multiplication Assignment | Multiplies the left operand with the right operand and assigns the result to the left operand | x *= 3 | x = x * 3 |
/= | Division Assignment | Divides the left operand by the right operand and assigns the result to the left operand | x /= 3 | x = x / 3 |
%= | Modulus Assignment | Performs modulus operation on the left operand with the right operand and assigns the result to the left operand | x %= 3 | x = x % 3 |
//= | Floor Division Assignment | Performs floor division operation on the left operand with the right operand and assigns the result to the left operand | x //= 3 | x = x // 3 |
**= | Exponentiation Assignment | Performs exponentiation operation on the left operand with the right operand and assigns the result to the left operand | x **= 3 | x = x ** 3 |
For those of you who are wondering floor division is a division operation where the quotient is rounded down to the nearest integer that is smaller than the result of normal division.
Now let us look at how these operators are used in a python code.
Here’s a fun fact about assignment operators in Python: In Python, you can use multiple assignment to assign values to multiple variables in a single line of code. For example:
x, y, z = 1, 2, 3
This assigns the value 1 to x, 2 to y, and 3 to z in a single line of code, which can be a handy shortcut in some situations.
The next type of operators that we will be looking into is the comparison operators. Comparison operators like the name suggests, compares two values in python and checks weather they are equal or not.
In Python, comparison operators always return a boolean value (True or False) depending on the outcome of the comparison.
Here are the comparison operators in Python:
Operator | Name | Description | Example |
== | Equal to | Returns True if two operands are equal | 5 == 5 returns True |
!= | Not equal to | Returns True if two operands are not equal | 5 != 3 returns True |
< | Less than | Returns True if the left operand is less than the right operand | 3 < 5 returns True |
> | Greater than | Returns True if the left operand is greater than the right operand | 5 > 3 returns True |
<= | Less than or equal to | Returns True if the left operand is less than or equal to the right operand | 3 <= 5 returns True |
>= | Greater than or equal to | Returns True if the left operand is greater than or equal to the right operand | 5 >= 5 returns True |
Note that the comparison operators return boolean values (True or False) depending on whether the comparison is true or false.
Here are some python examples on comparison operators.
The above examples shows the comparison between two numeric values but we can also compare other data types as well.
When comparing other datatypes, the comparison is based on their contents rather than their memory location.
In Python, comparison between different data types is generally not possible. However, there are some exceptions where comparison between certain data types is allowed.
For example, comparison between integers and floats is possible in Python. But, comparison between other data types, such as strings and numbers, is not allowed. It’s also important to note that comparison between complex numbers is not possible, except for the equality and inequality operators.
Write a program that generates a random number between 1 and 10, and then asks the user to guess the number. If the user’s guess is correct, the program should print “Congratulations! You guessed the number!” and exit. Otherwise, the program should print “Sorry, that’s not the number. Please try again.” and ask the user to guess again. The user should be allowed to keep guessing until they get the number right.
Hint: You can use the random module in Python to generate a random number. You can import it using import random, and then use random.randint(1, 10) to generate a random integer between 1 and 10.
Logical operators in Python are used to evaluate multiple conditions in a single expression. They allow programmers to check if two or more conditions are true or false and perform specific actions based on the result.
By using logical operators, programmers can create more complex and powerful programs.
In this section, we will look at the different types of logical operators available in Python and how to use them effectively in your code.
The three main types of logical operators are:
Let us first take a look at the truth tables of each of these operators:
Operand 1 | Operand 2 | Result |
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Operand 1 | Operand 2 | Result |
True | True | True |
True | False | True |
False | True | False |
False | False | False |
Operand 1 | Result |
True | False |
False | True |
In Python, these operators are utilized to perform logical operations by taking the operands mentioned earlier as different conditions. To better understand this concept, refer to the table and examples provided below.
Operator | Description |
and | Returns True if both statements are true |
or | Returns True if one of the statements is true |
not | Reverse the result, returns False if the result is true |
Now, let’s take a look at some real Python code to better understand how these logical operators are used.
In this example, we are using the and operator to combine two conditions:
x < y and y < z.
The if statement checks if both conditions are True, and if they are, it prints the message:
“y is between x and z”
If either of the conditions is False, the else block will execute and print the message
“y is not between x and z”
In this example, the or operator is used to combine two conditions. The code checks whether x is equal to 5 or y is equal to 15, and if at least one of these conditions is true, it prints
“At least one condition is true.”
If both conditions are false, it prints
“Both conditions are false.”
Since x is equal to 5, the first condition is true and the code executes the if block, printing “At least one condition is true.”
In this example, the not operator is used to negate the result of the comparison x > y. Since x is greater than y, the result of x > y is True, but the not operator negates this to False. Therefore, the output of this code would be: “x is greater than y”.
Now that we’ve learned about the logical operators in Python, I hope you have a clear understanding of how they work. But wait, there’s more! Let me enlighten you with some interesting facts that you should be aware of while using these operators.
not -> and -> or
This means that not is evaluated first, followed by and, and then or. However, it is recommended to use parentheses to make the order of evaluation clear.
Write a Python program that takes in two boolean values as input from the user and applies logical operators to them. The program should print out the result of each operation, along with a message describing the logic behind it.
Alright, now let’s take a look at another type of operator in Python – the Identity Operators. These operators are used to compare the memory locations of two objects in Python.
Identity operators are used to compare the memory locations of two objects in Python. These operators are “is” and “is not”. The “is” operator checks if two objects are the same object and have the same memory location, while the “is not” operator checks if two objects are not the same object and do not have the same memory location. In this blog post, we will explore the identity operators in Python and their usage with some examples.
Operator | Description |
is | Returns True if both variables are the same object |
is not | Returns True if both variables are not the same object |
Here’s an example of the is operator:
In this example, x and y are two different lists that happen to have the same contents. However, they are not the same object in memory. On the other hand, x and z are both pointing to the same object in memory, so the is operator returns True in this case.
Alright now let’s take a look at an example of is not operator in python:
In this example, we have two lists a and b with the same values, but they are different objects in memory. The ‘is not’ operator checks if they are not the same object. Therefore, a is not b returns True.
We also have another variable c which is assigned to the same object as a. So, a is not c returns False.
Another interesting aspect of the identity operator is that it can also demonstrate object reusability in Python.
For example, when we create multiple variables with the same value (such as integers), Python may reuse the same object in memory to save resources.
In such cases, using the is operator to compare these variables may return True, indicating that they refer to the same object in memory. However, this behaviour is implementation-dependent and may vary in different versions of Python or with different objects.
Membership Operators are used to test if a sequence (such as a string, list, or tuple) contains a specific value. These operators return a Boolean value (True or False) based on whether the value is found or not. There are two membership operators in Python: in and not in.
Operator | Description |
in | Evaluates to True if a value is found in the sequence. |
not in | Evaluates to True if a value is not found in the sequence. |
Example of ‘in’ operator in python:
In this example, we define a list my_list containing the integers from 1 to 5. We then use the in operator to check if the integer 3 is in the list. Since 3 is indeed in the list, the program prints the message “3 is in the list!” to the console.
Example of ‘not in’ operator in python:
One important thing to note about the membership operators is that they are generally used to test whether a value or variable exists within a sequence or collection of items.
This includes lists, tuples, sets, and dictionaries. However, it is important to keep in mind that using the “in” operator to search through large data structures can be slow and inefficient. In such cases, it is often better to use alternative data structures such as hash tables or binary search trees to optimize search performance.
In Python, bitwise operators are used to perform operations on individual bits of binary numbers. These operators are often used in low-level programming, such as in device drivers and embedded systems, where the manipulation of bits is essential.
Bitwise operators can also be used to optimize code and perform certain calculations quickly. There are four bitwise operators in Python:
Operator | Name | Description |
& | Bitwise and | returns a 1 in each bit position if both operands have a 1 in that position |
| | Bitwise or | returns a 1 in each bit position if either operand has a 1 in that position |
^ | Bitwise xor | returns a 1 in each bit position if only one operand has a 1 in that position |
~ | Bitwise not | inverts all the bits of the operand |
<< | Bitwise left shift | shifts the bits of the left operand to the left by a number of positions specified by the right operand |
>> | Bitwise right shift | shifts the bits of the left operand to the right by a number of positions specified by the right operand |
The operands of bitwise operators are always converted to binary representation before any operation is performed.
Now let us take a look at some python implementations of bitwise operators.
Bitwise OR (|):
Bitwise Negation (~):
Bitwise Left Shift (<<):
Bitwise Right Shift (>>):
Alright, folks! Let’s take a look at a new topic – the ternary operator in Python. This operator is a condensed way of writing an if-else statement, making it perfect for short, simple conditions. The ternary operator consists of three parts: a condition, a value to return if the condition is true, and a value to return if the condition is false.
The syntax for ternary operator is as follows:
value_if_true if condition else value_if_false
Let me show you an example of how to use the ternary operator. Imagine we have a variable called x, and we want to check if x is greater than 5. If it is, we want to return “Greater than 5“, otherwise we want to return “Less than or equal to 5“. We can use the ternary operator to accomplish this in a single line of code:
The output of this code will be “Greater than 5”, since x is greater than 5. As you can see, the ternary operator allows us to write this condition in a concise and readable way.
So, when should you use the ternary operator? It’s perfect for simple conditions where you want to avoid writing a lengthy if-else statement. However, for more complex conditions, it’s better to stick with the traditional if-else statement to maintain readability and avoid confusion.
Now that you know how to use the ternary operator, go ahead and give it a try in your next project!
As the name suggests, chained comparisons are nothing but comparisons that are chained together to create a more complex boolean expression.
In simpler terms, with chained comparisons, you can compare multiple variables or values in a single line of code. It not only makes your code more readable and concise but also reduces the chances of errors and bugs.
Let’s look at an example to understand this better:
In this example, we have chained the comparison operators < to create a complex boolean expression that checks if a is less than b and b is less than c. If this condition is true, then it will print the message “a is less than b and b is less than c”.
Pretty neat, right? And this is just the tip of the iceberg. Chained comparisons can be used in various real-world programming scenarios to make your code more efficient and easier to read.
Alright, let’s talk about operator precedence rules in Python. When multiple operators are used in an expression, Python follows a set of precedence rules to determine the order of operations. This is important because it can affect the outcome of your code.
For example, in the expression 2 + 3 * 4, Python will first perform the multiplication (3 * 4), and then add the result to 2. This will result in an output of 14, not 20, because multiplication has a higher precedence than addition.
To avoid confusion and ensure that your code behaves as expected, it’s important to understand the operator precedence rules in Python.
Here is a table of the operator precedence rules in Python, listed from highest to lowest:
Operator | Description |
** | Exponential |
(+x), (-x) | Positive, negative |
*, /, //, % | Multiplication, division, floor division, modulus |
+, – | Addition, subtraction |
<<, >> | Bitwise shifts |
& | Bitwise and |
^ | Bitwise XOR |
| | Bitwise OR |
<, <=, >, >= | Comparisons |
!=, == | Equality operators |
is, is not | Identity operators |
in, not in | Membership operators |
not | Boolean NOT |
and | Boolean AND |
or | Boolean OR |
It’s important to note that you can use parentheses to override the operator precedence rules and ensure that your code behaves as intended.
Here is an example code snippet that demonstrates the use of operator precedence rules in Python:
In this code, we have used the +, *, /, //, %, and ** operators, as well as parentheses, to manipulate the values of x, y, and z and produce different results.
By understanding operator precedence rules, you can write cleaner and more efficient code, and avoid bugs caused by unexpected order of operations.
In conclusion, Python offers a wide range of powerful operators that can help us write efficient and concise code. From basic arithmetic operations to more advanced features like ternary operators, chained comparisons, and operator precedence rules, understanding and mastering these concepts can take your programming skills to the next level.
Whether you’re a beginner or an experienced programmer, taking the time to learn these topics and applying them in real-world scenarios can help you write cleaner, more efficient, and more elegant code. So, keep practicing, exploring, and experimenting with these operators, and who knows, you may just create the next big thing in the world of Python programming, if you enjoyed the blog follow 1stepgrow.
We provide online certification in Data Science and AI, Digital Marketing, Data Analytics with a job guarantee program. For more information, contact us today!
Courses
1stepGrow
Anaconda | Jupyter Notebook | Git & GitHub (Version Control Systems) | Python Programming Language | R Programming Langauage | Linear Algebra & Statistics | ANOVA | Hypothesis Testing | Machine Learning | Data Cleaning | Data Wrangling | Feature Engineering | Exploratory Data Analytics (EDA) | ML Algorithms | Linear Regression | Logistic Regression | Decision Tree | Random Forest | Bagging & Boosting | PCA | SVM | Time Series Analysis | Natural Language Processing (NLP) | NLTK | Deep Learning | Neural Networks | Computer Vision | Reinforcement Learning | ANN | CNN | RNN | LSTM | Facebook Prophet | SQL | MongoDB | Advance Excel for Data Science | BI Tools | Tableau | Power BI | Big Data | Hadoop | Apache Spark | Azure Datalake | Cloud Deployment | AWS | GCP | AGILE & SCRUM | Data Science Capstone Projects | ML Capstone Projects | AI Capstone Projects | Domain Training | Business Analytics
WordPress | Elementor | On-Page SEO | Off-Page SEO | Technical SEO | Content SEO | SEM | PPC | Social Media Marketing | Email Marketing | Inbound Marketing | Web Analytics | Facebook Marketing | Mobile App Marketing | Content Marketing | YouTube Marketing | Google My Business (GMB) | CRM | Affiliate Marketing | Influencer Marketing | WordPress Website Development | AI in Digital Marketing | Portfolio Creation for Digital Marketing profile | Digital Marketing Capstone Projects
Jupyter Notebook | Git & GitHub | Python | Linear Algebra & Statistics | ANOVA | Hypothesis Testing | Machine Learning | Data Cleaning | Data Wrangling | Feature Engineering | Exploratory Data Analytics (EDA) | ML Algorithms | Linear Regression | Logistic Regression | Decision Tree | Random Forest | Bagging & Boosting | PCA | SVM | Time Series Analysis | Natural Language Processing (NLP) | NLTK | SQL | MongoDB | Advance Excel for Data Science | Alteryx | BI Tools | Tableau | Power BI | Big Data | Hadoop | Apache Spark | Azure Datalake | Cloud Deployment | AWS | GCP | AGILE & SCRUM | Data Analytics Capstone Projects
Anjanapura | Arekere | Basavanagudi | Basaveshwara Nagar | Begur | Bellandur | Bommanahalli | Bommasandra | BTM Layout | CV Raman Nagar | Electronic City | Girinagar | Gottigere | Hebbal | Hoodi | HSR Layout | Hulimavu | Indira Nagar | Jalahalli | Jayanagar | J. P. Nagar | Kamakshipalya | Kalyan Nagar | Kammanahalli | Kengeri | Koramangala | Kothnur | Krishnarajapuram | Kumaraswamy Layout | Lingarajapuram | Mahadevapura | Mahalakshmi Layout | Malleshwaram | Marathahalli | Mathikere | Nagarbhavi | Nandini Layout | Nayandahalli | Padmanabhanagar | Peenya | Pete Area | Rajaji Nagar | Rajarajeshwari Nagar | Ramamurthy Nagar | R. T. Nagar | Sadashivanagar | Seshadripuram | Shivajinagar | Ulsoor | Uttarahalli | Varthur | Vasanth Nagar | Vidyaranyapura | Vijayanagar | White Field | Yelahanka | Yeshwanthpur
Mumbai | Pune | Nagpur | Delhi | Gurugram | Chennai | Hyderabad | Coimbatore | Bhubaneswar | Kolkata | Indore | Jaipur and More