An operator is used to perform some sort of operation on variables and values.
a = 4 b = 7 c = a + b print(c)
Python has the following type of operators
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical Operators
- Membership Operators
- Identity Operators
- Bitwise Operators
Arithmetic operators –
Arithmetic operators are used to performing basic arithmetic or mathematical operations. They include –
+, -, *, /, %, **, //
+ operator is used to perform addition, ‘-‘ is used to perform subtraction on two numbers, * is used for multiplication.
a = 6 b = 4 print(a + b) print(a - b) print(a * b)
/ and % operators are used to perform division. The only difference between them is ‘/ ‘ returns the quotient whereas ‘%’ returns the remainder.
a = 8 b = 2 print(a / b) print(a % b)
** operator is used for calculating the exponential of a number.
a = 10 b = 2 print(a ** b)
// operator is used to calculate floor division. That is it rounds off the result to its nearest whole number.
a = 5 b = 2 print(a // b)
These operators are used to assign values to variables.
‘=’ is used to assign a value to a variable.
a = 12 print(a)
+= is the increment assignment operator. It adds a value to the existing value of a variable.
a = 4 a += 2 print(a)
In the above example
a += 2
is equivalent to
a = a + 2
In the exact same way, we have ‘-=’, ‘*=’, ‘/=’, ‘%=’ and ‘**=’.
|Expression||Is equivalent to|
|a -= 2||a = a – 2|
|a *= 2||a = a * 2|
|a /= 2||a = a / 2|
|a %= 2||a = a % 2|
|a **= 2||a = a ** 2|
Comparison operators are used to compare two values. Any expression having a comparison operator returns a boolean value – true or false. There are several comparison operators in python which are ==, !=, >, <, >=, and <=.
a = 4 b = 4 print(a == b)
In the same way-
|!=||is not equal||a != b|
|>||is greater than||a > b|
|<||is lesser than||a < b|
|>=||is greater than or equal to||a >= b|
|<=||is lesser than or equal to||a <= b|
The logical operators combine multiple conditional statements
and – It returns True if all the conditions are true. If any one of the conditions is False, the overall statement returns False.
x = 1 y = 2 print(x < 4 and y < 4)
or- It returns True if any one of the conditions is true. If all the conditions are False, the overall statement returns False.
x = 1 y = 6 print(x < 4 or y < 4)
not- It reverses the result of any conditional statement.
x = 10 print(not(x < 20))
There are some other type of operators as well, but they can only be understood if we know the concepts of conditional statements, collections types etc.
So as of now this should be enough, after some later tutorials, the remaining operators would be discussed.