Operators in Python

 Operators are internally functions in python

_ _add_ _(a,b)

Various operators in python

  • Addition  a + b
  • Concatenation  a + b
  • Containment test - a in Obj
  • Division(True Division) - a/b
  • Division(Floor Division) - a//b
  • Bitwise AND - a & b
  • Bitwise OR - a | b
  • Bitwise Exclusiv OR - a ^ b
  • Bitwise NOT - ~ a 
  • Exponentiation - a ** a 
  • Identity - a is b
  •  Identity - a is not b
  • Indexed Assignment - Obj[i] = a
  • Indexed Deletion - del Obj[i]
  • Indexing - Obj[i]
  • Left Shift - <<
  • Logical AND - a and b
  • Logical OR - a or b
  • Modulo - a%b
  • Multiplication or Repetition - a * b
  • Negation - -a 
  • Negation(logical) - not a
  • Positive - +a 
  • Right shift - a>>b 
  • Slice Assignment - S[i:j] = values
  • Slice Deletion - del S[i:j] 
  • Slicing - S[i:j]
  • String formatting - S%s
  • Subtraction - a - b
  • Ordering (less than) - a <b
  • Ordering (greater than) a > b
  • Ordering (less than equal to) - a <=b 
  • Ordering(greater than equal to) - a >= b
  • Equality - a == b
  • not equal - a!=b 

Operator Categorization:

Arithmetic Operators - No increment (++) , No decrement(--) operators in python
                                    **, /,//,*,%,+,-
Relational Operators - < , > , <= , >= , ==, !=
Logical Operators - not, and , or
Bitwise Operators - &, |,|, ^, <<, >>
Assignment Operators - ==,  +=  , -= , /= ,  *= ,//= ,%= ,**= , *= , &=, |=, ^=, >>=,<<=
Identity Operators - is , is not
Membership Operator - in, not in 

Arithmetic Operators

** - Exponential operator 

2 ** 3 = 2 * 2 * 2 = 8
-2 ** 2 = - (2) ** 2 = -4
(-2) ** 2 = 4 - note if we want to do square of -negative number use parenthesis.
2**(-2) == 1/ (2*2) = 1/4 = 0.25

/ - Operator

Divide result such as 5/2 = 2.5 as in Mathemetics - float value

// - Same as / operator in C

Divide result such as 5//2 = 2 - Floor division

% operator 

Exception in python - % can also be used for floating number, that was illegal in C. 

Example - 5.5 % 3 = 2.5,  
                 5.5 % 1.5 = 1.0

* , - ( Have dual nature) 

For str type value it will concatenate , for integer it works normal ways. 

"ab" + "ba" == > "abba"

"ab" * 3 = ababab  --> only integer value is allowed not floating one 


Some pointers to remember 

+ is addition operator for numbers ( int,bool,float) while works as concatnation for str type
+ is invalid when applied between string and number - 3 + '3 ' - this is invalid, but works with both string type numbers '3' + '3' - will be 33
 
* Works as multiplication (when numbers are numbers), if one of them is number than it works as repetition operator - cannot work with float though

Relational operators

  • Relational operators always give result True or False
  • When truth value is converted to int it becomes 1 and for false 0
  • Relational operator can also be used to compare two strings - Example "ABC" > "CDE" give False as CDE order comes after ABC.
  • Inquality operators are <, > <= and >= and doesn't work with complex number - (4+5j) < (3+2j) - this will give error. Equality operators such as == , != will give result True or False depending upon calculation
Logical Operators
Some cases

not "Eduction" 
returns False.
As any non-empty string is True in Python. 

In python operators are written as not, and, or instead of !, &&, || like in C,C++,Java.

In case of non bool characters, we need to conclude result based on the operator used

Example 

>>> 3 and 4
4

Here and operator result depend upon 4 (next variable) so answer is 4. 

Similar 

>>> 3 or 4
3

Here in case of or result depend upon first variable, if first variable is true answer is first variable. No need to check another statement. 

>>> 0 or 4
4
>>>

Take away - Every non-zero value is true and non-empty string is True. 

>>> 0 or 4
4
>>>

Bitwise Not operator : ~

~0 = 1 
~1 = 0

Bitwise not operator works as follows

Say a number is 5, so binary of it would be 101. 

Let's rewrite the same thing in 8 bits - 00000101

so ~5 would be as follows 11111010. This is correct in terms of binary. But if we need to find decimal equivalent then can be solved with 2's complement method.

Original - 00000101

i) Inverse the number position for 0 with 1 

11111010

ii) Since the beginning value is 1, its negative number. Let's say number is -K
iii) Take 2's complement would give the answer

2's complement means - 1's complement + 1 

1's complement would be initial number 00000101 + 1 = 00000110 = 6

Answer was - K so it would be -6. 

Let's take another example - 

a = ~15

Here binary is 00001111

So negative would be as follows. 

i) Take 1st complement - 11110000 - this is negative number lets say -K

ii) So, the answer would be 2's complement 

Take 1s complement or number and add 1 

 it would be 00001111 + 1 -> 000010000 -> 16 

so, answer would be -16.  

Assignment Operator 

Some variation 

In python we cannot assign multiple values like we do with below syntax in c

x = 10 , y = 20 --> This would result error. 

SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

correct way to do this in python

x, y = 10, 20 ==> this assigns 10 in x and 20 in y. 

If we do this , 

x, y,z  = 10, 20 

This would result in error too. The number of arguments must match with the variables.

ValueError: not enough values to unpack (expected 3, got 2)

Identity Operator

Identity operators are used to check the reference of objects. If both the references are same it returns True.

Example - a = 5 and b = 5 

>>> a = 5
>>> id(a)
140729746682792
>>> b = 5
>>> id(b)
140729746682792


Here both the id's are name. We can check the same thing using is operator. 

a is b 

>>> a is b
True

But in some cases, the id's are allocated different for same value as in case of floats.

Example a = 3. 5 and b = 3.5 

>>> c = 3.5
>>> d = 3.5
>>> id(c)
2308035296848
>>> id(d)
2308035296976

if we check as using identity operator. It returns false.

>>> c is d
False

Membership operator

in 
not in

a in b. 
  • a and b should be iterable (container variable)
  • Result will be True or False
  • Container is a type which can hold multiple values and it is iterable. 
int, float, complex, bool are not iterable

str, range, list, tupple, set, dict are iterable. 

Example with str -

>>> 'h' in "hari"
True
>>> x = "Hari Sapkota Sharma"
>>> "Sap" in x
True
>>> "lota" in x
False
>>>

Comments