Chapter 3 , Integer Arithmetic Expressions

Program 3-1 , Page number: 33

In [1]:
# An introduction to arithmetic 

a = 2
b = 3
c = 4

answer = a + b
print "a + b = %d"%answer

answer = a - b
print "a - b = %d"%answer

answer = a * b
print "a * b = %d"%answer

answer = a / b
print "a / b = %d"%answer
a + b = 5
a - b = -1
a * b = 6
a / b = 0

Program 3-2 , Page number: 34

In [2]:
# Illustration of mathematical hierarchy

a = 2
b = 3
c = 4

answer = a + b * c

print "a = %d, b = %d, c= %d"%(a,b,c)
print "a + b * c = %d\n"%answer
a = 2, b = 3, c= 4
a + b * c = 14

Program 3-3 , Page number: 35

In [3]:
# A more advanced illustration of mathematical hierarchy

a = 5
b = 10
c = 15

answer = a + b / c
print "%d + %d / %d = %d"%(a,b,c,answer)

answer = b * c - a
print "%d * %d - %d = %d"%(a,b,c,answer)

answer = a * b / c
print "%d * %d / %d = %d"%(a,b,c,answer)

answer = (a + c) * b / a
print "(%d + %d) * %d / %d = %d"%(a,c,b,a,answer)
5 + 10 / 15 = 5
5 * 10 - 15 = 145
5 * 10 / 15 = 3
(5 + 15) * 10 / 5 = 40

Program 3-4 , Page number: 37

In [4]:
# Illustration of modulus operator

a = 4
b = 8
c = 13

print "%d mod %d = %d"%(b,a,b%a)
print "%d mod %d = %d"%(c,a,c%a)
print "%d mod %d = %d"%(c,b,c%b)

print "The modulus operator is: %"
8 mod 4 = 0
13 mod 4 = 1
13 mod 8 = 5
The modulus operator is: %

Program 3-5 , Page number: 38

In [5]:
# Illustration of the unary minus

a = -4
b = 5
c = -6

print "a = %d, b = %d, c = %d\n\n"%(a,b,c)
print "      and now\n\n"

a = -a
b = -b
c = -c

print "a = %d, b = %d, c = %d\n\n"%(a,b,c)
a = -4, b = 5, c = -6


      and now


a = 4, b = -5, c = 6