What are Operators and Expressions in Python
Operators and Expressions in Python
Mathematics is the foundation for computers. Computers make mathematics accessible and programmable for complex systems such as Rocket Science. What do you think we do when we try to solve complex problems? Mathematics is all about equations and formulas to do something with the numbers. These numbers are called operands, and the activity that happens on them is operations. These operations consist of addition, subtraction, multiplication, division, exponentiation, modulus and many more scientific complex calculations. The symbols representing these operations are called operators, and the equations and formulas are called expressions in programming terminology. All operands can be considered as data or information on which we perform operations through the operators. In this blog, I will discuss these operators and expressions in detail to unfold the underlying programming concepts.
Overview of Operators
Operators and expressions are fundamental concepts in programming that allow us to perform various operations on data. All programming languages have this basic concept. We are discussing this from the perspective of Python Programming. It has several operators, and each one serves a specific purpose. I assume you know that in mathematics, expressions are evaluated in a particular order of operators when there is more than one operator in the expression—The Operator Precedence. Therefore, understanding operators and their precedence is crucial for writing error-free code. Before that, let's explore the different types of operators. Later, we will quickly go through their precedence and how to evaluate expressions effectively.
First things first, Python supports various types of operators. Below are the main categories:
- Arithmetic Operators
- Assignment Operators
- Comparison/Relational Operators
- Boolean Operators
- Bitwise Operators
- Bitwise Assignment Operators
- Conditional Operator
- Identity Operator
- Membership Operator
- Deletion Operator
- Callables Operators
- String and Sequence Operators
- Sequence Assignment Operators
- Grouping/Misc Operators
Let's see them one at a time, starting with Arithmetic Operators so that you can understand them better and more in-depth.
Arithmetic Operators
Python Arithmetic operations are given below with their respective Python operator symbol.
Operation Name | Operator | Description | Syntax |
---|---|---|---|
Addition | + | Addition: adds two numbers/digits/operands | x + y |
Subtraction | – | Subtraction: subtracts two numbers/digits/operands | x – y |
Multiplication | * | Multiplication: multiplies two numbers/digits/operands | x * y |
Division | / | Division (float): divides the first by the second number | x / y |
Floor Division | // | Division (floor): divides the first by the second number | x // y |
Modulus | % | Modulus: returns the remainder when the first number is divided by the second | x % y |
Power/Exponentiation | ** | Power: Returns the first number after raising the power of the second number | x ** y |
The names are self-explanatory. We don't need to discuss them in detail. Let's quickly see their precedence rules. The highest will be the first, and the lowest will be the last.
Precedence of Arithmetic Operators
- Exponentiation
**
- Unary plus
+
and unary minus-
- Multiplication
*
, division/
, and modulus%
- Addition
+
and subtraction-
Assignment Operators
Assignment operators are those where we assign some value directly or by evaluating expressions on the right-hand side to the left-hand side, usually a variable. The Python assignment operators with respective symbols and examples are below. Please go through them and try to use them in your programs. Assignment operators have the lowest precedence as it is the final step after expression evaluation is completed.
Operator Name |
Sign |
Description |
Syntax |
---|---|---|---|
Simple Assignment Operator |
= |
Assign the value of the right-hand side of the expression to the left-hand side operand | a = a + b |
Addition Assignment Operator |
+= |
Add the right-hand side operand with the left-hand side operand and then assign the result to the left operand | a += b |
Subtraction Assignment Operator |
-= |
Subtract the right-hand side operand from the left-hand side operand and then assign the result to the left operand | a -= b |
Multiplication Assignment Operator |
*= |
Multiply the right operand with the left operand and then assign the result to the left operand | a *= b |
Division Assignment Operator |
/= |
Divide the left operand with the right operand and then assign the result to the left operand | a /= b |
Modulus Assignment Operator |
%= |
Divide the left operand with the right operand and then assign the remainder to the left operand | a %= b |
Floor Division Assignment Operator |
//= |
Divide the left operand with the right operand and then assign the value(floor) to the left operand | a //= b |
Exponentiation Assignment Operator |
**= |
Calculate the exponent(raise power) value using operands and then assign the result to the left operand | a **= b |
Bitwise AND Assignment Operator |
&= |
Performs Bitwise AND on operands and assigns the result to the left operand | a &= b |
Bitwise OR Assignment Operator |
|= |
Performs Bitwise OR on operands and assigns the value to the left operand | a |= b |
Bitwise XOR Assignment Operator |
^= |
Performs Bitwise XOR on operands and assigns the value to the left operand | a ^= b |
Bitwise Right Shift Assignment Operator |
>>= |
Performs Bitwise right shift on operands and assigns the result to left operand | a >>= b |
|
<<= |
Performs Bitwise left shift on operands and assigns the result to the left operand | a <<= b |
Walrus Operator |
:= |
Assign a value to a variable within an expression. First introduced in Python 3.8. |
a := exp |
Relational Operators
Comparison operators are used to compare two values/operands. These values can be numbers, strings, booleans, and more. Generally, the LHS side is compared to the RHS with any of the operators below.
Operator Name | Operator | Description | Syntax |
Equal To | == | It's an equality check operator. It evaluates to True if LHS and RHS are equal. | red == red |
Not Equal | != | It's also an equality check operator. It evaluates to True if LHS and RHS are not equal. | red != bread |
Greater Than | > | It's a size check operator. It evaluates to True if LHS is greater than RHS. | 10 > 5 |
Less Than | < | It's also a size check operator. It evaluates to True if LHS is less than RHS. | 5 < 10 |
Greater Than or Equal To | >= | Greater than or equal to: It evaluates to True if LHS is greater than or equal to the RHS. |
10 >= 10 11 >- 10 |
Less Than or Equal To | <= | Less than or equal to: It evaluates to True if LHS is less than or equal to the RHS. |
10 <= 11 11 <= 11 |
Python is amazing. You can also chain the comparison operators to depict exactly what is denoted in mathematics below. In mathematics, we see the below constraints many times.
0 < i < 100
-100 < n < 100
We can do the same check easily in Python like below:
if 0 < i < 100:
print("i - Within Constraints")
if -100 < i < 100:
print("i - Within Constraints")
You can test the above on your machine and let me know in the comments if this works or if I am wrong.
Boolean Operators
Many times, we have options in life to choose from. Imagine a situation in which you want to purchase a dress for yourself. Before buying the dress from the shop, you first decide what dress you want. Am I right? This time, you think of colours, styles, etc. So you choose from red OR blue. So, this OR
is a logical operator. Similarly, you also use AND
and NOT
, do you? Below are Python's logical operators.
Operator Name | Operator | Description | Syntax |
---|---|---|---|
Logical AND | and | Returns True if both the operands are true. | red and blue |
Logical OR | or | Returns True if either of the operands is true | red or blue |
Logical NOT | not | Returns True if the operand is false | not red |
Bitwise Operators
These operators are called bitwise operators because they operate on bits. I assume that you know what bits are in machine code. Below are Python's bitwise operators.
Operator Name | Operator | Description | Syntax |
---|---|---|---|
Bitwise AND | & | Returns the result of bitwise AND of two INTEGERS | x & y |
Bitwise OR | | | Returns the result of bitwise OR of two INTEGERS | x | y |
Bitwise NOT | ~ | Sets the 1 bits to 0 and 1 to 0 and then adds 1 | ~ x |
Bitwise X-OR | ^ | Returns the result of bitwise XOR of two INTEGERS | x^y |
Left Shift | << | Shifts the bits of the first operand left by the specified number of bits | x<<y |
Right Shift | >> | Shifts the bits of the first operand right by the specified number of bits | x>>y |
Bitwise Assignment Operators
Operator Name | Operator | Description | Syntax |
---|---|---|---|
Bitwise AND assignment | &= | Performs bitwise AND and assigns value to the left operand. | x &= y |
Bitwise OR assignment | |= | Performs bitwise OR and assigns value to the left operand. | x |= y |
Bitwise X-OR assignment | ^= | Returns the result of bitwise XOR of two INTEGERS | x ^= y |
Left Shift assignment | <<= | Shifts the bits of the first operand left by the specified number of bits | x <<= y |
Right Shift assignment | >>= | Shifts the bits of the first operand right by the specified number of bits | x >>= y |
Conditional Operator - if else
if else
is handy when you want to write condition-based assignments. See the below example.
is_email_valid = True if check_email(email) else False
print('Email is valid' if is_email_valid else "Email is invalid")
Identity Operator - is
It's a saviour when you quickly want to identify whether an object is identical to another. It returns True
if the objects are the same. See the example below.
a = "This is test string 1"
b = "This is test string 1"
c = a
if a is b:
print("a is b")
else:
print("a is not b")
# Output
# a is not b
if c is a:
print("c is a")
else:
print("c is not a")
# Output
# c is b
Here, you can observe that it is entirely different from the comparison or relational operators. Behind the scenes, this operator looks for the variable's memory location instead of the value itself. Therefore, the First comparison between a
and b
is False and displayed - "a is not b
". On line number 3, we created the Third variable c
and assigned a to it. It did not copy the value of a but stored the memory location of a
. Hence, the condition c is a
gave True.
Clearly, the identity operator compares the memory location, whereas relational/comparison operators compare actual values.
Membership Operator - in
The membership operator checks whether the LHS operand exists in the collection or an iterable, such as a list or dictionary and returns a boolean. See the below example.
my_list = ["value1", 4, "v", 10.5]
item1 = "v"
item2 = 10.5
item3 = "10.5"
if item1 in my_list:
print(item1, "exists")
else:
print(item1, "does not exist")
#Output - v exists
if item2 in my_list:
print(item2, "exists")
else:
print(item2, "does not exist")
#Output - 10.5 exists
if item3 in my_list:
print(item3, "exists")
else:
print(item3, "does not exist")
#Output - 10.5 does not exist
You can test this code and let me know in the comments why the third condition was evaluated to "False
" and printed "10.5 does not exist
"
Deletion Operator - del
This operator deletes the object when you call it, like in the example below. You can delete a variable, dictionary item, list item, etc.
b = "This is test string 1"
print("b=", b)
del b
print("b=", b)
# Output
#Traceback (most recent call last):
# File "", line 1, in
#NameError: name 'b' is not defined
What if we use the previous example and try to delete c
variable? Let's check it out.
a = "This is test string 1"
c = a
print("c=", c)
del c
print("a=", a)
print("c=", c)
# Output
#Traceback (most recent call last):
# File "", line 1, in
#NameError: name 'c' is not defined
Callables Operators
This is fascinating and useful when you want to pack/unpack the collections. Python modules and libraries use these extensively. Below is the list. Let's dig into it.
Operator Name | Operator | Description |
---|---|---|
Tuple Packing/Unpacking | * |
Packing happens when we call a function with positional arguments separately. Unpacking happens when we call a function with a list of parameters in tuple form with this operator. |
Dictionary Packing/Unpacking | ** | Packing happens when we call a function with positional arguments separately.
Unpacking happens when we call a function with a list of parameters in tuple form with this operator. |
Decorator | @ | Used when we decorate the function with additional functionality |
lambda | lambda | It returns an anonymous or oneliner function |
Call operator | () | It calls a callable object with specified parameters. |
If you want to see examples, please visit the functions in Python blog, where I have explained this with examples.
String and Sequence Operators
Operator Name | Operator | Description | Example |
---|---|---|---|
Concatenation Operator | + |
It concatenates the two sequences and returns a single sequence. |
"ABC" + "XYZ" |
Multiple concatenation | * | Returns a sequence of self-concatenated sequences for a specified amount of time. | "ABC" * 5 |
Formatting Operator | % | Formats a string according to the specified format |
"%d" % 123 "%s" % "test" |
This is intriguing because you can present the output to the console precisely as you wish so the user can follow it better and understand it quickly. Do you want to see the dictionary example? Look at this.
my_dict = {
"language": "Python",
"number": 2
}
print("%(language)s has %(number)03d quote types." % my_dict)
# Output - Python has 002 quote types.
Sequence Assignment Operators
Operator Name | Operator | Description | Example |
---|---|---|---|
Concatenation Assignment Operator | += |
Concatenates the left-hand side string/sequence with the right-hand side and assigns the result to that left-hand side |
"ABC" + "XYZ" |
Multiple concatenation assignment | *= | Multiplies the left-hand side string/sequence with the right-hand side string/sequence and assign the result to the left-hand side | "ABC" * 5 |
That's it for all operators Python supports. This is a huge list, isn't it? Now that you have seen all the operators, you can proceed with the precedence of operators. Wait a minute. Before you know the precedence of operators, you must understand the grouping operators. See the below:
Grouping/Misc Operators
Operator Name | Operator | Description | Example |
---|---|---|---|
Open Group | ( | It means the group is started. |
((a + (b*c) / e)/d) |
Close Group | ) | It means the group is closed. | ((a + (b*c) /e)/d) |
The expression ((a + (b*c) / e)/d)
has several groups, including inner groups. By thumb rule, the innermost group has to be evaluated first and so on. Let's understand this by an example.
a = 15
b = 14.7
c = -13
d = 12
e = 11
# Expression to evaluate with groups
ans = ((a + (b*c) / e)/d)
# Breakdown of the expressions based on groups
# 1. g1 = (b*c)
# 2. g2 = (a + g1 / e)
# 3. ans = (g3 / d)
print(ans)
I hope this has helped you understand the groups in expressions. You also must have understood that group operators have the highest precedence in expressions. You must use the parenthesis ()
to group expressions whenever you wish to enforce a specific order of expression evaluation. It's time for precedence rules.
Precedence and Associativity of Operators
Every operator has a different precedence. Therefore, it's essential to understand the order of evaluation to avoid ambiguity and obtain correct results. Below is the precedence order:
- Parentheses
()
- Exponentiation or power
**
- Multiplication
*
, division/
, and modulus%
- Addition
+
and subtraction-
- Assignment operators
=
,+=
,-=
, and so on
Understanding operator precedence and associativity is crucial to avoid unexpected results in complex expressions.
Conclusion
Operators and expressions are the foundation of Python programs. They enable us to perform mathematical calculations, compare values, and make logical decisions. Understanding the precedence and associativity of operators is vital for writing accurate and efficient code. By mastering these concepts, you will gain more control over your Python programs and be better equipped to solve a wide range of problems in the world of programming. Happy coding!
Reader Comments
Add a Comment
Recent Posts
- A Journey into Python Programming | Power of Python Programming
- How To Use Variables and Data Types in Python Programming
- How To Use Basic Input and Output in Python
- How To Use Conditional Statements in Python?
- How To Use Loops in Python?
- How To Use Lists in Python?
- How To Use Tuples in Python?
- How To Use Python Dictionaries?
- How To Define Functions In Python?
- How To Use Modules and Packages in Python?
- How To Do File Handling In Python?
- How To Handle Exceptions In Python?
- How To Manipulate String in Python?