Python Tutorial - Basic Operators

Python language supports the following types of operators.

Arithmetic Operators


print 2 + 3 # 5 - Addition
print 3 - 2 # 1 - Subtraction

print 2 * 3 # 6 - Multiplication
print 2 ** 3 # 8 - Exponent

print 18 / 4 # 4 - Division 
print 18 // 4 # 4 - Floor Division
print 10 % 3 # 1 - Modulus
note that in python division the result show only the integer number, for example if divide 10 on 3 the result will be only 3 not 3.3333 as we expect, solve this problem see python float division.

Comparison Operators


print 5==5 # True - Equal

print 5 != 7 # True - Not equal
print 5 <> 7 # True - Not equal

print 5 > 2 # True - greater than
print 5 < 2 # False- less than

print 5 >= 2 # True - greater than or equal
print 5 <= 5 # True - less than or equal

Assignment Operators


a = 5 # a=5
a += 2 # a=5+2 = 7
a -= 3  # a=7-3 = 4

a *= 3  # a=4*3 = 12
a /= 2  # a=12/2 = 6

a %= 4  # a=6%4 = 2

a **= 4  # a=2**4 = 16
a //= 7  # a=16//7 = 2

Logical Operators


print (True)and(False) # False
print (4=4) and (7=5) # False

print (True)or(False) # True
print (4=4) or (7=5) # Ture

print Not (True) # False
print Not (3=3)  # False

Logical Operators


print (True)and(False) # False
print (4=4) and (7=5) # False

print (True)or(False) # True
print (4=4) or (7=5) # Ture

print Not (True) # False
print Not (3=3)  # False

Membership Operators



list = [1, 2, 3, 4, 5 ];

if ( 3 in list ):
    print 'yes 3 is in the list'
else :
    print '3 is not in the list'










If this post was good and helpful for you, Please give it Like.
.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment