Chapter 5: Operators & Expressions

example 5.1, page no. 62

In [1]:
a = 20.5
b = 6.4

print "a = ", a
print "b = ", b
print "a+b = ", (a+b)
print "a-b = ", (a-b)
print "a*b = ", (a*b)
print "a/b = ", (a/b)
print "a%b = ", (a%b)
a =  20.5
b =  6.4
a+b =  26.9
a-b =  14.1
a*b =  131.2
a/b =  3.203125
a%b =  1.3

example 5.2, page no. 64

In [2]:
a = 15.0
b = 20.75
c = 15.0
print "a = ", a
print "b = ", b
print "c = ", c
print "a<b is ", (a<b)
print "a>b is ", (a>b)
print "a==c is ", (a==c)
print "a<=c is ", (a<=c)
print "a>=b is ", (a>=b)
print "b!=c is ", (b!=c)
print "b==(a+c) is ", (b==(a+c))
a =  15.0
b =  20.75
c =  15.0
a<b is  True
a>b is  False
a==c is  True
a<=c is  True
a>=b is  False
b!=c is  True
b==(a+c) is  False

example 5.3, page no. 67

In [18]:
#there is no inrement operator in Python, we will use += instead

m = 10
n = 20
print "m = ", m
print "n = ", n
m+=1
print "++m = ", m 
print "n++ = ", n
n+=1
print "m = ", m
print "n = ", n
m =  10
n =  20
++m =  11
n++ =  20
m =  11
n =  21

example 5.4, page no. 73

In [21]:
my_sum = 0
for i in range(1, 11):
    my_sum = my_sum + (1/float(i))
    print "i = ", i,
    print "sum = ", my_sum
i =  1 sum =  1.0
i =  2 sum =  1.5
i =  3 sum =  1.83333333333
i =  4 sum =  2.08333333333
i =  5 sum =  2.28333333333
i =  6 sum =  2.45
i =  7 sum =  2.59285714286
i =  8 sum =  2.71785714286
i =  9 sum =  2.82896825397
i =  10 sum =  2.92896825397

example 5.5, page no. 74

In [23]:
my_list = []
my_list.append(1)
my_list.append(2)
l = len(my_list)-1
total = 0
while l >= 0:
    total = total + my_list[l]
    l -= 1
print "The total amount is ", total
The total amount is  3

example 5.6, page no. 77

In [2]:
a = 10
b = 5
c = 8
d = 2
x = 6.4
y = 3.0

answer1 = a * b + c / d
answer2 = a * (b+c) / d

answer3 = a/c
answer4 = float(a)/c
answer5 = a / y

answer6 = a % c
answer7 = float(x%y)

bool1 = a > b and c > d
bool2 = a < b and c > d
bool3 = a < b or c > d
bool4 = not(a - b == c)

print "Order of Evaluation"
print "a * b + c / d = ", answer1
print "a * (b+c) / d = ", answer2

print "Type Conversion"
print "a / c = ", answer3
print "float(a)/c = ", answer4
print "a / y = ", answer5

print "Modulo Operations"
print "a % c = ", answer6
print "x % y = ", answer6

print "Logical Operations"
print "a > b and c > d = ", bool1
print "a < b and c > d = ", bool2
print "a < b or c > d = ", bool3
print "not(a - b == c) ", bool4
Order of Evaluation
a * b + c / d =  54
a * (b+c) / d =  65
Type Conversion
a / c =  1
float(a)/c =  1.25
a / y =  3.33333333333
Modulo Operations
a % c =  2
x % y =  2
Logical Operations
a > b and c > d =  True
a < b and c > d =  False
a < b or c > d =  True
not(a - b == c)  True
In [ ]: