Friday, 17 March 2017

Python Operators: Assignment and Special Operators

Assignment operators:


  • Assignment operators are used in Python to assign values to variables. 
  • a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left. 
  • There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5.


Note:
  • Python not support the post increment and decrement,pre increment and decrement. but this mechanism achieve indirectly by using assignment operators.


Special operators:

Python language offers some special type of operators,they are
  • Identity operators
  • Membership operators
These operators are not supported other languages

Identity operators:

  • Identity operators  are used to compare the address of the objects which are pointed by the operands.

Example1:

x=10
y=4
print(id(x))
print(id(y))
print(x is y)
print(x is not y)

Output:

1812472816
1812472624

False
True

Example2:

a=100
b=100
print(id(a))
print(id(b))
print(a is b)
print(a is not b)

Output:

1812475696
1812475696

True
False

Note:
above two examples are immutable objects.

Example3:

p=[10,20,30,40]
q=[10,20,30,40]
print(id(p))
print(id(q))
print(p is q)
print(p is not q)

Output:

55103816
55172232

False
True

Note:
p and q are mutable objects.mutable objects contains same content but having different address.

Membership operators


  • Membership operators are used to search for the given element in the given object.
  • Objects like list,tuple,set,dict.
  • These membership operators feature takes from SQL .


Example1:

x=[10,20,30,40,50]
print(10 in x)
print(60 in x)
print(20 not in x)
print(100 not in x)

Output:

True
False

False
True

Example2:

name="sivakrishna"
print('i' in name)
print('a' in name)
print('y' not in name)
print('k' not in name)

Output:

True
True

True
False

Operator presidency:



Example:

a=20
b=10
c=15
d=5
e=0
e=(a+b)*c/d
print("value of (a+b)*c/d is: ",e)

e=((a+b)*c)/d
print("value of ((a+b)*c)/d is: ",e)

e=(a+b)*(c/d)
print("value of (a+b)*(c/d) is: ",e)

e=a+(b*c)/d
print("value of (a+b)*c/d is: ",e)

Output:

value of (a+b)*c/d is:  90.0
value of ((a+b)*c)/d is:  90.0
value of (a+b)*(c/d) is:  90.0
value of (a+b)*c/d is:  50.0

No comments:

Post a Comment