Chapter 8: Structuring Your Programs

Program 8.1, page no. 323

In [1]:
count1 = 1

while(count1<=5):
    count1 += 1
    count2 = 0
    count2 += 1
    print "count1 = %d count2 = %d " %(count1, count2)
 
print "count1 = %d\n" %count1
count1 = 2 count2 = 1 
count1 = 3 count2 = 1 
count1 = 4 count2 = 1 
count1 = 5 count2 = 1 
count1 = 6 count2 = 1 
count1 = 6

Program 8.2, page no. 324

In [2]:
 

count = 0
while(count<=5):
    count += 1
    print "count = ", count
 
print "count = ", count
count =  1
count =  2
count =  3
count =  4
count =  5
count =  6
count =  6

Program 8.3, page no. 330

In [3]:
def Sum(x, n):
    sum = 0.0
    for i in range(n):
        sum += x[i]
    return sum
 
def Average(x, n):
    return Sum(x, n)/n

def GetData(data, t):
    print "How many values do you want to enter (Maximum 50)? "
    nValues = int(raw_input())
    if(nValues > 50):
        print "Maximum count exceeded. 50 items will be read."
        nValues = 50
    for i in range(nValues):
        data.append(float(raw_input()))
    return nValues
 
samples = []
sampleCount = GetData(samples, 50);
average = Average(samples, sampleCount);
print "The average of the values you entered is: ", average
How many values do you want to enter (Maximum 50)? 
5
1.0
2.0
3.0
4.0
5.0
The average of the values you entered is:  3.0

Program 8.4, page no. 339

In [4]:
def sort_string(text):
    dot_separated = text.split('.')
    text_sorted = sorted(dot_separated)
    return text_sorted


print "Enter strings to be sorted, separated by '.' Press Enter to end: "
text = raw_input()

sorted_text = sort_string(text)

for str in sorted_text:
    print str
Enter strings to be sorted, separated by '.' Press Enter to end: 
Sample strings. These are samples. Another Sample
 Another Sample
 These are samples
Sample strings

Program 8.5, page no. 344

In [5]:
def IncomePlus(pPay):
    pPay += 10000
    return pPay

your_pay = 30000
pold_pay = your_pay
pnew_pay = IncomePlus(pold_pay)
print "Old pay = $", pold_pay
print "New pay = $", pnew_pay
Old pay = $ 30000
New pay = $ 40000

Program 8.6, page no. 345

In [6]:
def IncomePlus(pPay):
    pPay += 10000
    return id(pPay)

your_pay = 30000
pold_pay = your_pay
pnew_pay = IncomePlus(pold_pay)
print "Old pay = $", pold_pay
print "New pay = $", pnew_pay
Old pay = $ 30000
New pay = $ 38417016