Python Operators: Arithmetic Operators: Arithmetic Operators Are Used To Perform Mathematical
Python Operators: Arithmetic Operators: Arithmetic Operators Are Used To Perform Mathematical
Output:
13
5
36
2.25
2
1
6561
Please refer Differences between / and // for some interesting facts about these
two operators.
2. Relational Operators: Relational operators compares the values. It either
returns True or False according to the condition.
OPERAT
OR DESCRIPTION SYNTAX
> Greater than: True if left operand is greater than the right x>y
< Less than: True if left operand is less than the right x<y
Greater than or equal to: True if left operand is greater than or equal to
>= the right x >= y
Less than or equal to: True if left operand is less than or equal to the
<= right x <= y
and Logical AND: True if both the operands are true x and y
| Bitwise OR x|y
~ Bitwise NOT ~x
Output:
0
14
-11
14
2
40
5. Assignment operators: Assignment operators are used to assign values to
the variables.
Add AND: Add right side operand with left side operand
+= and then assign to left operand a+=b a=a+b
a <<= b a= a
Performs Bitwise left shift on operands and assign value to
<<= left operand << b
. Identity operators-
is and is not are the identity operators both are used to check if two
values are located on the same part of the memory. Two variables that are equal
does not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
print(a3 is b3)
Output:
False
True
False
Membership operators-
expr = 10 + 20 * 30
print(expr)
# Precedence of 'or' & 'and'
name = "Alex"
age = 0
if name == "Alex" or name == "John" and age >= 2 :
print("Hello! Welcome.")
else :
print("Good Bye!!")
Output:
610
Hello! Welcome.
Operator Associativity: If an expression contains two or more operators with the
same precedence then Operator Associativity is used to determine. It can either be
Left to Right or from Right to Left.
print(100 / 10 * 10)
# Left-right associativity
# 5 - 2 + 3 is calculated as
# (5 - 2) + 3 and not
# as 5 - (2 + 3)
print(5 - 2 + 3)
# left-right associativity
print(5 - (2 + 3))
# right-left associativity
# 2 ** 3 ** 2 is calculated as
# 2 ** (3 ** 2) and not
# as (2 ** 3) ** 2
print(2 ** 3 ** 2)
Output:
100.0
6
0
512
OPERATOR DESCRIPTION ASSOCIATIVITY
() Parentheses left-to-right
** Exponent right-to-left
+ - Addition/subtraction left-to-right