Chapter 6: Control Statements

Example 6.4, Page number: 6.3

In [1]:
import math


inputs=[5,25,4,8]
Sum,SumSq,SumSqrt=0,0,0

for x in inputs:

    Sum+=x
    SumSq+=x*x
    SumSqrt+=math.sqrt(x)


print " Sum = %d \n SumSq = %d \n SumSqrt = %f" %(Sum,SumSq,SumSqrt)
 Sum = 42 
 SumSq = 730 
 SumSqrt = 12.064495

Example 6.5, Page number: 6.4

In [1]:
def main(first,second):
    
    if first>second:
        print "first number is bigger"
    if second>first:
        print "second number is bigger"
    if first==second:
        print "both are equal"
    return

main(5,6)
main(6,5)
main(1,1)
second number is bigger
first number is bigger
both are equal

Example 6.7, Page naumber: 6.8

In [2]:
def main(time):

    if time>=0. and time<12.:
        print "Good Morning"
    elif time>=12. and time<18.:
        print "Good Afternoon"
    elif time>=18. and time<=24.:
        print "Good Evening"
    else:
        print "time is out of range"
    return

main(9)
main(15)
main(21)
main(36)
Good Morning
Good Afternoon
Good Evening
time is out of range

Example 6.8, Page number: 6.8

In [3]:
digit=0
while digit<=9:
    print digit
    digit=digit+1
0
1
2
3
4
5
6
7
8
9

Example 6.9, Page number: 6.9

In [4]:
letter="Fourscore and seven years ago aou fathers brought forth..."
letter=list(letter)
count=0
tag=len(letter)

while count<tag:
    letter[count]=letter[count].upper()
    count=count+1
letter=''.join(letter)
print letter
FOURSCORE AND SEVEN YEARS AGO AOU FATHERS BROUGHT FORTH...

Example 6.10, Page number: 6.11

In [3]:
Sum,count=0,0

numbers=[1,2,3,4,5,6]
n=6.0

while count<n:
     x=numbers[count]
     print "x = ",x
     Sum+=x
     count+=1

average=Sum/n

print 'Average = ',average
x =  1
x =  2
x =  3
x =  4
x =  5
x =  6
Average =  3.5
x =  1
x =  2
x =  3
x =  4
x =  5
x =  6
Average =  3.5

Example 6.11, Page number: 6.12

In [5]:
digit=0
while True:
    print digit
    digit=digit+1
    if digit>9:
        break
0
1
2
3
4
5
6
7
8
9

Example 6.12, Page number: 6.13

In [6]:
letter="Fourscore and seven years ago aou fathers brought forth..."
letter=list(letter)

count=0
tag=len(letter)

while True:
    letter[count]=letter[count].upper()
    count=count+1
    if count>=tag:
        break

letter=''.join(letter)
print letter
FOURSCORE AND SEVEN YEARS AGO AOU FATHERS BROUGHT FORTH...

Example 6.13, Page number: 6.14

In [4]:
Sum,count=0,0

numbers=[1,2,3,4,5,6]
n=6.0

while True:
     x=numbers[count]
     print "x = ",x
     Sum+=x
     count+=1
     if count>=n:
         break

average=Sum/n

print 'Average = ',average
x =  1
x =  2
x =  3
x =  4
x =  5
x =  6
Average =  3.5

Example 6.14, Page number: 6.16

In [7]:
for digit in range(0,10):
    print digit
0
1
2
3
4
5
6
7
8
9

Example 6.16, Page number: 6.17

In [8]:
letter="Fourscore and seven years ago aou fathers brought forth..."
letter=list(letter)
n=len(letter)

for count in range(0,n):
    
    letter[count]=letter[count].upper()

letter=''.join(letter)
print letter

        
FOURSCORE AND SEVEN YEARS AGO AOU FATHERS BROUGHT FORTH...

Example 6.17, Page number: 6.17

In [10]:
n=6
Sum=0.0

for count in range(1,n+1):
    Sum=Sum+count
    
average=Sum/n
print "the average is ",average
the average is  3.5

Example 6.18, Page number: 6.19

In [5]:
numbers=[[1.5,2.5,6.2,3.0],[4,-2,7],[5.4,8.0,2.2,1.7,-3.9]]
loopcount=3
loop=0

while loop<loopcount:

    Sum=0

    for x in numbers[loop]:

        print 'x = ',x
        Sum+=x

    print 'The average is ',Sum/len(numbers[loop])
    loop+=1
x =  1.5
x =  2.5
x =  6.2
x =  3.0
The average is  3.3
x =  4
x =  -2
x =  7
The average is  3
x =  5.4
x =  8.0
x =  2.2
x =  1.7
x =  -3.9
The average is  2.68

Example 6.19, Page number: 6.20

In [6]:
text=['Now is the time for all good men to come to aid..','Fourscore and seven years ago our fathers brought forth...','*']


loop=0

while True:
    letter=text[loop]
    if letter=='*':
        print "\nGood bye"
        break

    print '\n',letter
    letter=list(letter)
    n=len(letter)

    for count in range(0,n):
        letter[count]=letter[count].upper()

    letter=''.join(letter)
    print letter
    loop+=1
        
Now is the time for all good men to come to aid..
NOW IS THE TIME FOR ALL GOOD MEN TO COME TO AID..

Fourscore and seven years ago our fathers brought forth...
FOURSCORE AND SEVEN YEARS AGO OUR FATHERS BROUGHT FORTH...

Good bye

Example 6.20, Page number: 6.22

In [11]:
line="The White House. 1600 Pennsylvania Avenue. Washington. DC"
line=list(line)
line2=[]
for count in line:
    if (count>='0' and count<'9') or \
       (count>='a' and count<'z') or \
       (count>='A' and count<'Z'):

        line2.extend(chr(ord(count)+1))

    elif count=='9':
        line2.extend('0')
    elif count=='z':
        line2.extend('a')
    elif count=='Z':
        line2.extend('A')
    else:
        line2.extend('.')

line2=''.join(line2)
print line2
Uif.Xijuf.Ipvtf..2711.Qfootzmwbojb.Bwfovf..Xbtijohupo..ED

Example 6.21, Page number: 6.23

In [13]:
def main(p,r,n):
    

    if p<0 or r<0 or n<0:
        print "ERROR! Wrong input"
        return
    

    i=r/100.0
    f=p*((i+1)**n)

    print "The Final value (F) is %.2f" %f

    return
main(1000,6,20)
main(5000,-7.5,12)
The Final value (F) is 3207.14
ERROR! Wrong input

Example 6.22, Page number: 6.25

In [16]:
import math

def main(guess):
    count=0
    flag=True

    while flag:
        count=count+1
        if count==50:
            flag=False

        test=10.-3.*guess*guess
        if test>0:
            root=test**.2
            print "Iteration number : %2d   x= %7.5f" %(count,root)
            error=math.fabs(root-guess)
            if error>0.00001:
                guess=root
            else:
                flag=False
                print "\n\n root= %7.5f     number of iterations %2d" %(root,count)

        else:
            flag=False
            print "number out of range... try another initial guess"



    if count==50 and error>0.00001:
        print "convergence not obtained after 50 iterations"
    
    return

print "initial guess: 1"
main(1)
print "\ninitial guess: 10"
main(10)
initial guess: 1
Iteration number :  1   x= 1.47577
Iteration number :  2   x= 1.28225
Iteration number :  3   x= 1.38344
Iteration number :  4   x= 1.33613
Iteration number :  5   x= 1.35951
Iteration number :  6   x= 1.34826
Iteration number :  7   x= 1.35375
Iteration number :  8   x= 1.35109
Iteration number :  9   x= 1.35238
Iteration number : 10   x= 1.35175
Iteration number : 11   x= 1.35206
Iteration number : 12   x= 1.35191
Iteration number : 13   x= 1.35198
Iteration number : 14   x= 1.35195
Iteration number : 15   x= 1.35196
Iteration number : 16   x= 1.35195


 root= 1.35195     number of iterations 16

initial guess: 10
number out of range... try another initial guess

Example 6.23, Page number: 6.30

In [18]:
def main(ch):

    if ch=='r' or ch=='R':
        print "RED"

    elif ch=='w' or ch=='W':
        print "WHITE"

    elif ch=='b' or ch=='B':
        print "BLUE"
        
    return

main('r')
main('W')
main('b')
RED
WHITE
BLUE

Example 6.24, Page number: 6.31

In [19]:
def main(ch):
    ch=ch.upper()

    if ch=='R':
        print "RED"

    elif ch=='W':
        print "WHITE"

    elif ch=='B':
        print "BLUE"

    else:
        print "ERROR"
        
    return

main('r')
main('W')
main('b')
main('y')
RED
WHITE
BLUE
ERROR

Example 6.25, Page number: 6.31

In [22]:
import math

def main(x,flag):

    if flag==-1:
        y=math.fabs(x)
    elif flag==0:
        y=x**0.5
    elif flag==1:
        y=x
    elif flag==2 or flag==3:
        y=2*(x-1)
    else:
        y=0
    print "y= ",y
    
    return

main(36,-1)
main(36,0)
main(36,1)
main(36,2)
main(36,3)
main(36,5)
main(0,6)
y=  36.0
y=  6.0
y=  36
y=  70
y=  70
y=  0
y=  0

Example 6.26, Page number: 6.32

In [23]:
choice=0

def main(choice,val,n):
    
    if choice==1:

        print "Straight Line Method\n\n"
        val=float(val)
        deprec=val/n
        for year in range(1,n+1):
            val=val-deprec
            print "End of year %2d  Depreciation: %7.2f     Current value: %8.2f"\
                  %(year,deprec,val)


    elif choice==2:
        print "Double Declining Balance Method\n\n"
        val=float(val)
        for year in range(1,n+1):
            deprec=2*val/n
            val=val-deprec
            print "End of year %2d  Depreciation: %7.2f     Current value: %8.2f"\
                  %(year,deprec,val)

    elif choice==3:
        print "Sum of the years' -Digit Method\n\n"
        val=float(val)
        tag=val

        for year in range(1,n+1):
            deprec=(n-year+1)*tag/(n*(n+1)/2)
            val=val-deprec
            print "End of year %2d  Depreciation: %7.2f     Current value: %8.2f"\
                  %(year,deprec,val)

    else:
        print "incorrect data entry..."

    return

print "\n Method: (1-SSL 2-DDB 3-SYD)  "
print "choice: 1  \nval: 8000 \nNumber of years: 10"
main(1,8000,10)
print "\n Method: (1-SSL 2-DDB 3-SYD)  "
print "choice: 2  \nval: 8000 \nNumber of years: 10"
main(2,8000,10)
print "\n Method: (1-SSL 2-DDB 3-SYD)  "
print "choice: 3  \nval: 8000 \nNumber of years: 10"
main(3,8000,10)
print "\n Method: (1-SSL 2-DDB 3-SYD)  "
print "choice: 5 \nval: 8000 \nNumber of years: 10"
main(5,8000,10)
 Method: (1-SSL 2-DDB 3-SYD)  
choice: 1  
val: 8000 
Number of years: 10
Straight Line Method


End of year  1  Depreciation:  800.00     Current value:  7200.00
End of year  2  Depreciation:  800.00     Current value:  6400.00
End of year  3  Depreciation:  800.00     Current value:  5600.00
End of year  4  Depreciation:  800.00     Current value:  4800.00
End of year  5  Depreciation:  800.00     Current value:  4000.00
End of year  6  Depreciation:  800.00     Current value:  3200.00
End of year  7  Depreciation:  800.00     Current value:  2400.00
End of year  8  Depreciation:  800.00     Current value:  1600.00
End of year  9  Depreciation:  800.00     Current value:   800.00
End of year 10  Depreciation:  800.00     Current value:     0.00

 Method: (1-SSL 2-DDB 3-SYD)  
choice: 2  
val: 8000 
Number of years: 10
Double Declining Balance Method


End of year  1  Depreciation: 1600.00     Current value:  6400.00
End of year  2  Depreciation: 1280.00     Current value:  5120.00
End of year  3  Depreciation: 1024.00     Current value:  4096.00
End of year  4  Depreciation:  819.20     Current value:  3276.80
End of year  5  Depreciation:  655.36     Current value:  2621.44
End of year  6  Depreciation:  524.29     Current value:  2097.15
End of year  7  Depreciation:  419.43     Current value:  1677.72
End of year  8  Depreciation:  335.54     Current value:  1342.18
End of year  9  Depreciation:  268.44     Current value:  1073.74
End of year 10  Depreciation:  214.75     Current value:   858.99

 Method: (1-SSL 2-DDB 3-SYD)  
choice: 3  
val: 8000 
Number of years: 10
Sum of the years' -Digit Method


End of year  1  Depreciation: 1454.55     Current value:  6545.45
End of year  2  Depreciation: 1309.09     Current value:  5236.36
End of year  3  Depreciation: 1163.64     Current value:  4072.73
End of year  4  Depreciation: 1018.18     Current value:  3054.55
End of year  5  Depreciation:  872.73     Current value:  2181.82
End of year  6  Depreciation:  727.27     Current value:  1454.55
End of year  7  Depreciation:  581.82     Current value:   872.73
End of year  8  Depreciation:  436.36     Current value:   436.36
End of year  9  Depreciation:  290.91     Current value:   145.45
End of year 10  Depreciation:  145.45     Current value:     0.00

 Method: (1-SSL 2-DDB 3-SYD)  
choice: 5 
val: 8000 
Number of years: 10
incorrect data entry...

Example 6.31, Page number: 6.41

In [24]:
navg=0
Sum=0.0
n=6

for count in range(-6,n+1):
    x=count
    if(x<0):
        continue
    Sum=Sum+x
    navg=navg+1


average=Sum/navg
print "The average is ",average
The average is  3.0

Example 6.32, Page number: 6.42

In [25]:
def main(letter):
    flag=True

    letter=list(letter)

    tag=len(letter)-1
    countback=tag

    for count in range(0,(tag/2)+1):
        if letter[count]!=letter[countback]:
            flag=False
            break
        countback=countback-1

    letter=''.join(letter)
    if flag:
        print "\n %s IS a palindrome" %letter
    else:
        print "\n %s is NOT a palindrome" %letter
    
    return

main('TOOT')
main('FALSE')
main('PULLUP')
main('ABLE WAS I ERE I SAW ELBA')
 TOOT IS a palindrome

 FALSE is NOT a palindrome

 PULLUP IS a palindrome

 ABLE WAS I ERE I SAW ELBA IS a palindrome

Example 6.34, Page number: 6.47

In [7]:
text=['Now is the time for all good men to come to aid..','Fourscore and seven years ago our fathers brought forth.$$..','*']


loop,flag=0,False

while True:
    letter=text[loop]
    if letter=='*' or flag:
        print "\nGood bye"
        break

    print '\n',letter
    letter=list(letter)
    n=len(letter)

    for count in range(0,n):
        letter[count]=letter[count].upper()

    letter2=''.join(letter)
    print letter2

    for count in range(0,n-1):
        if letter[count]=='$' and letter[count+1]=='$':
            print 'BREAK CONDITION DETECTED - TERMINATE EXECUTION'
            flag=True
            break
    
    loop+=1
        
Now is the time for all good men to come to aid..
NOW IS THE TIME FOR ALL GOOD MEN TO COME TO AID..

Fourscore and seven years ago our fathers brought forth.$$..
FOURSCORE AND SEVEN YEARS AGO OUR FATHERS BROUGHT FORTH.$$..
BREAK CONDITION DETECTED - TERMINATE EXECUTION

Good bye
In [ ]: