Operators in Python
Hello Friends, today in this article we are going to discuss about operators in Python
What are operators in Python?
Operators are special symbols in Python that carry out arithmetic or logical computation.
The value that the operator operates on is called the operand.
>>> 5+5 10
Here, + is the operator which we use for addition
There are different types of operators which are used in Python
- Arithmetic operators
- Assignment operators
- Relational operators
- Logical operators
- Operators Precedence
Different Arithmetic operators like-
- Addition (+) for adding two numbers
- Subtraction (-) for subtracting second number from first
- Multiplication (*) for multiplying two numbers
- Division (/) for dividing numerator by denominator
- Modulus operator (%) for determining remainder of after an integer division
Assignment operator (=)
a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.
Different relational operators supported in Python are:
- Equals (==)
- Not equals (!=)
- Greater than (>)
- Less than (<)
- Greater or equal to (>=)
- Less than or equal to (<=)
Logical operators are the
|and||True if both the operands are true||x and y|
|or||True if either of the operands is true||x or y|
|not||True if operand is false (complements the operand)||not x|
The combination of values, variables, operators and functions calls is termed as an expression. The Python interpreter can evaluate a valid expression.
>>> 5 - 7 -2
5 - 7 is an expression. There can be more than one operator in an expression.
To evaluate these types of expressions there is a rule of precedence in Python. It guides the order in which these operations are carried out.
For example, multiplication has higher precedence than subtraction.
>>> 10 - 4 * 2 2
But we can change this order using parentheses
() as it has higher precedence than multiplication.
>>> (10 - 4) * 2 12
The operator precedence in Python is listed in the following table. It is in descending order (upper group has higher precedence than the lower ones).
|/ * // %||Division, Multiplication,|
Integer division, Modulus
|+-||Addition and subtraction|
|>,>=,<, <=, ==, !=||Relational operators|
|=, +=, -=, **=, /=, //-, %=||Assignment operators|
|not or and||Logical and Boolean operators|
Operators which have higher precedence appears on the top of the table.
Thank you for reading this article
Have a nice day