Learn Python
Python Introduction |
Python Installation |
Python Hello World |
Python Tokens |
Python Program Structure |
Python Variables and Assignments |
Python Input Output |
Python Data Types |
Python Mutable Immutable |
Python Opeartors |
Python Expression |
Python if statement |
Python range method |
Python Loop |
Python break continue |
Python Loop else |
Python Nested Loop |
Python Operators
Operators are tokens that perform some operation / calculation / computation, in an expression.
Operators
Operators are tokens that perform some operation / calculation / computation, in an expression.
Variables and objects to which the computation or operation is applied, are called operands.
Operator require some operands to work upon.
Python supports following operators –
A. Unary Operators
Unary operators, require only one operand to work upon.
+ Unary plus
- Unary minus
~ Bitwise complement
not logical negation
B. Binary Operators
Binary Operators, require two operands to work upon.
i. Arithmetic Operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus or Remainder
** Exponent (raise to power)
// Floor division, also called integer division. In floor division only whole part i.e. integer of the result is given in the output and the fractional part is truncated.
Note: 1//2 is 0, (-1)//2 is -1,
1//(-2) is -1, and (-1)//(-2) is 0.
The result is always rounded towards minus infinity.
Note:
* Replication Operator, When * is used with string, it works as replication or duplication operator.
+ Concatenation Operator, When + is used with string, tuples, and lists.
ii. Relational Operators
It is also called comparison operators. Determines the relation among different operands by doing comparison. Its results into the Boolean value True or False. Python supports six types of comparison or relational operators -
< Less than
< Less thanthan
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Note : Relational operators work on following principles:-
4.0 is equal to 4. Because for Numeric types, the values are compared after removing trailing zeros after decimal point from a floating point number.
Strings are compared on the basis of lexicographical ordering, i.e. based on ordinal values. ‘A’ is less than ‘a’, because ordinal values (ASCII) value of ‘A’ is 65 while ‘a’. To check ordinal code of a character, use ord(character).
Two lists and two tuples are equal, if they have same elements in the same order.
Truth Value Testing
Value with truth value as false : None, False, 0, 0.0, 0j, “”, (), [], {}, (empty string, empty tuple, empty list, empty dictionary)
Values with truth value as true : All other values are considered true
Boolean True is equivalent to 1 and Boolean False to 0, for comparison purpose.
iii. Logical Operators : Python provides three logical operators-
and Logical and
or Logical or
not Logical not
The or Operator : The or operator combines two expressions or operands, and works in following ways, depend upon the operand
Relational expressions as operands
The or operator evaluates to True if either of its operands evaluates to True; False if both operands evaluate to False.
Numbers / strings/ lists as operands
In an expression x or y, if first operand has falsetval, then return second operand y as result, otherwise return x.
The and Operator: Like or, and operator also combines two expressions or operands, and works in following ways, depend upon the operand’s category-
Relational expressions as operands
The and operator evaluates to True if both of its operands evaluates to True; False if either or both operands evaluate to False.
Numbers or strings or lists as operands
In an expression x and y, if first operand has falsetval, then return first operand x as result, otherwise return y.
The Logical not Operator:
Logical not operator works on single operand, it negates or reverse the truth value of the expression. i.e. not True = False , not False = True.
Unlike ‘and’ and ‘or’, not operator returns always a Boolean value True or False.
Summary (Logical Operator)
Case - I
Operation : x or y
Result : if x is false, then y, else x
Notes : This is a short-circuit operator, so it only evaluates the second argument if the first one is false.
Case - II
Operation : x and y
Result : if x is false, then x, else y
Notes : This is a short-circuit operator, so it only evaluates the second argument if the first one is true.
Case - III
Operation : not x
Result : if x is false, then True, else False
Notes : not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.
iv. Assignment Operator
= Assignment, assign a value to variable.
v. Augmented Assignment operator
it combine the impact of arithmetic operator and assignment operator. E.g. x = 10
+= Assign Addition e.g. x += 20 # x = x + 20
-= Assign difference e.g. x -= 15 # x = x - 15
*= Assign product e.g. x *= 2 # x = x * 2
/= Assign quotient e.g. x /= 4 # x = x / 4
%= Assign remainder e.g. x %= 3 # x = x % 3
**= Assign Exponent e.g. x **= 3 # x = x ** 3
//= Assign floor division e.g. x//=2 # x //= 4
vi. Identity Operators are used to check if both the operands reference the same object memory i.e. compare the memory location of two objects and return True or False accordingly
is is the identity same? => returns True if both operands are pointing to same objects i.e. same memory location, otherwise return False.
is not is the identity not same? => returns Trueif both operands are pointing to different objects i.e. to different memory location, otherwise return False..
Note: id(object_variable name) : method is returns the memory location of the object. id() is the built-in function of Python.
vii. Membership Operators
in whether variable in sequence, returns True if given value is present in the specified list, tuple and sequence; otherwise returns False,
not in whether variable not in sequence, returns True if given value is not present in the specified list, tuple and sequence; otherwise return False.
viii. Bitwise Operators
& Bitwise AND Compares two bits and generates a result of 1 if both bits are 1; otherwise, it returns 0.
^ Bitwise exclusive OR (XOR) Compares two bits and returns 1 if either of the bits are 1 and it gives 0 if both bits are 0 or 1.
| Bitwise OR (Including OR) Compares two bits and generates a result of 0 if both bits are 0; otherwise, it returns 1
~ Bitwise Not / Bitwise Inverte Invert all bits. i.e. 0 to 1 and 1 to 0. It’s a Unary operator.
<< shift left To shift all bits specified number, towards left side and adding specified 0 to right side. For example : x << n x shifted left by n bits. A left shift by n bits is equivalent to multiplication by pow(2, n) without overflow check. Negative shift counts are illegal and cause a ValueError to be raised
>> shift right To shift all bits specified number, towards right side and adding specified 0(zero) to left side. For example - x >> n x shifted right by n bits. A right shift by n bits is equivalent to division by pow(2, n) without overflow check. Negative shift counts are illegal and cause a ValueError to be raised.
Note:
bin(integer), returns the binary equivalent number of given integer literals or integer variable. bin( ) is a built-in method of Python.
Operator Precedence
Precedence means priority. When an expression or statement contains multiple operators, Python overcome the order of execution through Operator Precedence. Get a look of operator precedence
Operator Precedence (Highest to lowest)
Operator => Description
( ) => Parentheses , grouping
** => Exponentiation
~y => Bitwise nor ~
+y, - y => Unary +, Unary –
*, /, //, % => Multiplication, Division, floor division, remainder
+, - => Addition, Subtraction
& => Bitwise AND &
^ => Bitwise XOR ^
| => Bitwise OR |
<, <=, >, >=, ==, !=, is, is not => Relational Operators, Identity Operator
not y => Boolean not / Logical not
and => Boolean and / Logical and
or => Boolean or / Logical or
Operator Associativity
Associativity is the order in which an expression having multiple operators of same precedence, is evaluated.
All operators are left associative except exponentiation (**) is right associative.