Operators in Python are symbols or words that are used to perform different kinds of operations in Python. They are used for performing arithmetic, relational, and logical operations.
Operators are important components in expressions in Python. Almost every expression or statement you will ever write in Python requires the use of an operator.
In this article, you will learn:
- The meaning of operators
- Types of operators
- Write different kinds of expressions with operators
Meaning of an operator
An operator is a symbol or word(s) that denotes the kind of operation to be performed on values. Take a look at the following line of code.
1 + 2
The symbol + in between the two numbers 1 and 2 represents addition. This symbol indicates addition. In order words, it is a way of telling the translator that the operation to be performed on the numbers is addition.
In expressions, operators determine the kind of operations to be performed on the values.
Operators in Python expressions
An expression is a combination of values and operators. When you combine an operator with values, you get an expression. This expression is then evaluated into a single value.
For example, 2 + 3 is an expression with an operator + and values (2 and 3). In this case, the operator + denotes addition, and the outcome is 5.
In a situation where there is more than one expression, python keeps evaluating the individual expressions making up the multiple expression until it becomes a single value.
For instance:
In the expression, 2 + 3 + 4, the value 2 is added to 3, which evaluates to 5, and then 4 is added to 5, which gives 9.
A lot of times, you might want to assign a name or variable to an expression. This way, you can always refer to the expression by a name.
For example:
sum = 2 +3
Hence, anytime you want to refer to the expression, you can use the name sum.
Types of operators
There are basically six types of operators in Python and they include:
- Arithmetic
- Relational
- Logical
- Bitwise
- Identity
- Membership
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations or calculations. The following are the commonly used arithmetic operators and what they are used for.
+ | Addition |
– | Subtraction |
* | Multiplication |
/ | Division |
// | Integer division |
** | Exponentiation |
% | Modulus |
The addition operator (+) is used for adding numbers, while the subtraction operator (–) is used in performing subtractions. The multiplication operator (*) is used for multiplications in numbers.
For divisions, the single forward slash (/) is for division. If values are divided using this operator, the outcome is always a float number. This type of division is called true division.
The double forward slash (//) is also used for a kind of division called the integer division. The outcome of this division is an integer value. When numbers are divided using the integer division operator, the decimal points are removed retaining only the integer number.
For instance:
3/2 = 1.5 but 3//2 = 1
The double asterisk (**) is used as an operator for exponentiation, and the percentage sign (%) is used as an operator for modulus.
Modulus is the same thing as the remainder. For instance, 5 divided by 2 will give 2 and a remainder of 1.
2 is the quotient while 1 is the remainder or modulus.
The following program illustrates how arithmetic operators are used in calculations.
#arithmetic operators - ex1.py num1 = 20 num2 = 5 #addition operator result = num1 + num2 print(result) #subtraction operator result = num1 - num2 print(result) #multiplication result = num1 * num2 print(result) #division result = num1 / num2 print(result) #integer division result = num1 // num2 print(result) #modulus operator result = num1 % num2 print(result) #exponentiation operator result = num1 ** num2 print(result)
output
25 15 100 4.0 4 0 3200000
Binary and unary operators
Most arithmetic operators are binary operators, meaning that they work on two values or operands.
An expression like 2 * 3 has the multiplication operator * and two operands 2 and 3. 2 is the left operand, while 3 is the right operand.
Some arithmetic operators are unary operators and work on a single operator. For instance, negative and positive signs like + and – are unary operators representing mathematical signs.
+ | Unary plus |
– | Unary minus |
For example:
- -5
- +10
Representing mathematical expressions in Python
With arithmetic operators, you can represent mathematical expressions into Python expressions. Let’s express some mathematical expressions as Python expressions.
The equation, y = 2x – 1 can be represented in Python as:
y = 2*x - 1
Also, the equation z = x3 + y2 + 5 can be represented in python as:
z = x**3 + y**2 + 5
Grouping expressions with parenthesis
Parenthesis is used for grouping expressions. To ensure that your expressions evaluate correctly, parenthesis is often to break down a complex expression into smaller chunks.
Take a look at the example below:
#grouping with parenthesis - ex2.py num1 = 2 num2 = 3 result = num1 + 7 / 5 * num2 print(result) result = num1 + (7/5) * num2 print(result) result = (num1 + 7) / (5 * num2) print(result)
output
6.199999999999999 6.199999999999999 0.6
When using parenthesis, ensure that you group the right expressions together. If not, you may get the wrong result.
Rules of Operator Precedence
Expressions are executed based on the order of precedence of the operator. They are neither evaluated from left to right nor from right to left.
Python evaluates expressions based on the precedence of the operators using a set of rules. These rules are similar to the rules for algebraic expressions and are abbreviated as PEDMMAS.
Operators are evaluated in the following order.
- Parenthesis
- Exponentiation
- Division
- Multiplication
- Modulus
- Addition
- Subtraction
Operators that are contained in a pair of parenthesis are evaluated before those that are outside of the parenthesis. This is followed by exponentiation, division, multiplication, modulus, addition and then subtraction.
Now, let’s see how it works through the example below:
#arithmetic operator precedence - ex3.py result = 2 + 2 - 2 print(result) result = 2 + (2 - 2) print(result) result = 2 * 2 - 2 print(result) #evaluates by precedence result = 2 + 2 - 2 * 2 / 2 ** 2 % 2 print(result) #using parenthesis to confirm precedence result = 2 + 2 - ((2 * (2 / (2 ** 2))) % 2) print(result) #using parenthesis to evaluate from right result = (2 + (2 - (2 * (2 / (2 ** (2 % 2)))))) print(result) #using parenthesis to evaluate from left result = ((((((2 + 2) - 2) * 2) / 2) ** 2) % 2) print(result)
output
2 2 2 3.0 3.0 0.0 0.0
From the example above, you can see the expressions are evaluated according to the precedence of operators and not from the right or from the left.
Relational operators
Relational operators also known as comparison operators are used to compare for equality among values. Particularly, they are used to establish if two values are equal, less or greater than each other. The following are relational operators and their meanings.
- Greater than >
- Less than <
- Greater or equal to >=
- Less or equal to <=
- Equality ==
- Not Equality !=
The greater than (>) returns True if the operand on the left is larger than the operator on the right.
The less than (<) returns True if the operand on the left is smaller than the operator on the right.
Greater or equal to (>=) returns True if the operand on the left is equivalent or larger than the operator on the right.
Less or equal to (<=) returns True if the operand on the left is equivalent or smaller than the operator on the right.
The equality operator (==) returns True if the left and right operators are equivalent, while the not equality operator (!=) returns True if the operands are not equivalent.
Keep in mind that the equality operator (==) is not the same as equal to (=). The equality operator is a relational operator used in comparing values, while the equal sign is an assignment operator used in assigning values to a variable.
Truthy and falsey values
Also, relational operators are used in determining whether an expression is truthy or falsey. The following are examples of relational operators and their meanings.
A truthy value or expression evaluates to True, while a falsey value or expression evaluates to False. For instance, any number greater than 0 or a non-empty list or string evaluates to True and is considered truth. The number 0 or empty string or list evaluates to False and is considered falsey.
In the example below, relational operators are used in comparing values.
#relational operators - ex4.py num1 = 2 num2 = 3 #greater than result = num1 > num2 print(result) #less than result = num1 < num2 print(result) #greater or equal to result = num1 >= num2 print(result) #less or equal to result = num1 <= num2 print(result) #equality result = num1 == num2 print(result) #not equality result = num1 != num2 print(result)
output
False True False True False True
Relational operators are often used in decision-making in control statements such as the if statements and while statements. For example:
#relational operator in control flow - ex4a.py num = 2 if num > 1: print('hello')
Logical operators
Logical operators are used in combining two or more boolean expressions. Boolean expressions are expressions with two possible outcomes – True or False.
Logical operators include the following:
The and operator is used to combine two or more expressions into a single complex expression. The outcome of this expression is either True or False.
If the and operator is used to combine expressions, the individual expressions must evaluate to True in order to get an overall outcome of True. If any of the expressions evaluates to False, the entire expression evaluates to False.
The or operator is also used to combine two or more expressions. Unlike the and operator, the combined expression evaluates to True, if ANY of the individual expressions evaluate to True. It evaluates to False if all the expressions evaluate to False. This is shown in the example below:
#logical operators - ex5.py #and operator result = 3 > 2 and 2 < 1 print(result) result = 3 < 2 and 2 < 1 print(result) #or operator result = 3 > 2 or 2 < 1 print(result) result = 3 < 2 or 2 < 1 print(result) result = 3 > 2 or 2 > 1 print(result) #not operator print(not True)
output
False False True False True False
The not operator is a unary operator that negates a boolean value. It changes a truthy value to falsey and a falsey value to truthy, as shown below:
#not operator in truthy or falsey expressions - ex5.py print(not (2 < 3)) print(not (2 > 3))
output
False True
Identity operators
The identity operator is used to determine whether two values are exactly the same. Two values may be equal to each other but not the same thing. For instance, these two values – 5 and ‘5’ are not the same thing. One is an integer while the other one is a string.
- Is
- Is not
The is operator returns True if the operands are exactly the same and false if otherwise. The opposite of the is operator is the is not.
The following example provides more clarity.
#identity operator - ex6.py print(2 is 2 ) print(2 is 2*1) print(2 is '2') print(2 is 2.0)
output
True True False False
Membership operators
These operators are used to determine whether a given value is present in a sequence. It is particularly useful if you want to determine whether a given value is present in a list, tuple or dictionary. There are two membership operators in Python and they include:
- In
- Not in
In the example below, membership operators are used to determine whether a given value is present in a list.
#membership opeators - ex7.py num = 3 #in operator result = num in [1,2,3,4,5] print(result) result = 'p' in 'apple' print(result) result = 'o' in 'apple' print(result) #not in operator result = num not in [1,2,3,4,5] print(result) result = 'p' not in 'apple' print(result) result = 'o' not in 'apple' print(result)
output
True True False False False True
Bitwise operators
Bitwise operators are used for operations at the bit or binary level. These are operations involving the individual bit of a number of characters. The bit is the same thing as a binary digit. You can learn more about binary number systems here.
The table below shows the different bitwise operators and their meanings.
Operator | Meaning |
& | Bitwise AND |
| | Bitwise OR |
~ | Bitwise NOT |
^ | XOR |
<< | Bitwise left shift |
>> | Bitwise right shift |
In the following examples, bitwise operators are used to perform operations.
#bitwise operators - ex8.py #bitwise and num1 = 0b10001 num2 = 0b11111 result = bin(num1 & num2) print(result) #bitwise or result = bin(num1 | num2) print(result) #bitwise xor result = bin(num1 ^ num2) print(result) #bitwise not result = bin(~num1) print(result) result = bin(~num2) print(result) #bitwise left shift result = bin(num1 << 1) print(result) result = bin(num1 << 2) print(result) result = bin(num1 << 3) print(result) #bitwise right shift result = bin(num1 >> 1) print(result) result = bin(num1 >> 2) print(result) result = bin(num1 >> 3) print(result)
output
0b10001 0b11111 0b1110 -0b10010 -0b100000 0b100010 0b1000100 0b10001000 0b1000 0b100 0b10
Since bitwise operations happen at the bit level, the built-in function bin() is used to convert numbers to binary equivalents. This way, you can easily how the bits are manipulated by these operators.
Conclusion
Without operators, you cannot make an expression in Python. There are basically 6 types or categories of operators and they include – arithmetic, relational, logical, membership, identity and bitwise operators.
Learning how to create and work with expressions is an essential aspect of Python programming. With what you’ve learned, you’re a step closer to mastering the Python programming language. You can check out the source codes for this article in this repository.