Chapter 4: Variables, data types, and arithmetic expressions

Program 4.1, Page number: 26

In [1]:
integerVar=100
floatingVar=331.79
doubleVar=8.44e+11
charVar='w'
boolVar=bool(0)

print("integerVar={0}".format(integerVar))
print("floatingVar={0}".format(floatingVar))
print("doubleVar={0}".format(doubleVar))
print("charVar={0}".format(charVar))
print("boolVar={0}".format(boolVar))
integerVar=100
floatingVar=331.79
doubleVar=8.44e+11
charVar=w
boolVar=False

Program 4.2, Page number: 30

In [2]:
a=100
b=2
c=25
d=4

result=a-b                              #subtraction
print("a-b={0}".format(result))         #result

result=b*c                              #multiplication
print("b*c={0}".format(result))         #result

result=a/c                              #division
print("a/c={0}".format(result))         #result

result=a+b*c                            #precedence
print("a+b*c={0}".format(result))       #result 

print("a*b+c*d={0}".format(a*b+c*d))    #direct calculation
a-b=98
b*c=50
a/c=4
a+b*c=150
a*b+c*d=300

Program 4.3, Page number: 33

In [3]:
a=25
b=2
c=25.0
d=2.0

print("6 + a / 5 * b = {0}".format(6+a/5*b))
print("a / b * b = {0}".format(a/b*b))
print("c / d * d = {0}".format(c/d*d))
print("-a={0}".format(-a))
6 + a / 5 * b = 16
a / b * b = 24
c / d * d = 25.0
-a=-25

Program 4.4, Page number: 35

In [4]:
a=25
b=5
c=10
d=7

print("a % b = {0}".format(a%b))
print("a % c = {0}".format(a%c))
print("a % d = {0}".format(a%d))
print("a / d * d + a % d = {0}".format(a/d*d+a%d))
a % b = 0
a % c = 5
a % d = 4
a / d * d + a % d = 25

Program 4.5, Page number: 36

In [5]:
f1=123.125
f2=1.0
i1=1
i2=-150
c='a'


i1=f1                                                              #floating to integer conversion
print("{0} assigned to an int produces {1:.0f}".format(f1,i1))

f1=i2                                                              #integer to floating conversion
print("{0} assigned to a float produces {1}".format(i2,f1))

f1=i2/100                                                          #integer divided by integer
print("{0} divided by 100 produces {1}".format(i2,f1))

f2=i2/100.0                                                        #integer divided by a float
print("{0} divided by 100.0 produces {1}".format(i2,f2))

f2=float(i2/100)                                                   #type cast operator
print("{0} divided by 100 produces {1}".format(i2,f2))
123.125 assigned to an int produces 123
-150 assigned to a float produces -150
-150 divided by 100 produces -2
-150 divided by 100.0 produces -1.5
-150 divided by 100 produces -2.0