Chapter 3: Loops and Decisions

Example 3.1, Page Number: 76

In [1]:
numb = input("Enter a number: ")                #get the number

print 'numb<10  is',int(numb < 10)
print 'numb>10  is',int(numb > 10)
print 'numb==10 is',int(numb == 10),'\n'
Enter a number: 20
numb<10  is 0
numb>10  is 1
numb==10 is 0 

Example 3.2, Page Number: 78

In [2]:
for j in range(15):           #for loop from 0 to 14
    print j*j,'',             #displaying the square of j
0  1  4  9  16  25  36  49  64  81  100  121  144  169  196 

Example 3.3, Page Number: 81

In [3]:
numb = 1        #define noop variable


for numb in range(1,11):           #loop from 1 to 10
    
    print '%4d' %(numb),           #display first column
    cube = numb*numb*numb          #calculate cube
    print '%6d' %(cube)            #display 2nd column
   1      1
   2      8
   3     27
   4     64
   5    125
   6    216
   7    343
   8    512
   9    729
  10   1000

Example 3.4, Page Number: 84

In [4]:
fact = 1

numb = input("Enter a number: ")        #get number

for j in range(numb,1,-1):             #loop from numb to 1 (numb , numb-1 , .... , 2 , 1)
    fact *= j                          #multiply by j

print 'Factorial is',fact,'\n'         #display the factorial of the number
Enter a number: 10
Factorial is 3628800 

Example 3.5, Page Number: 86

In [5]:
n = 99      

while(n!=0):            #loop untill n is 0
    n = input()         #read a number into n

print       #for end line
1
27
33
144
9
0

Example 3.6, Page Number: 88

In [6]:
pow = 1                #power variable initially 1
numb = 1               #numb goes from 1 to ???
 
    
while(pow<10000):                #loop untill power <= 4 digits
    print '%2d' %(numb),         #display number
    print '%5d' %(pow)           #display 4th power
    numb += 1                    #get for next power
    pow = numb*numb*numb*numb    #calculate forth power
 1     1
 2    16
 3    81
 4   256
 5   625
 6  1296
 7  2401
 8  4096
 9  6561

Example 3.7, Page Number: 89

In [7]:
limit = 4294967295      #largest unsigned long  
next = 0                #next-to-last term
last = 1                #last term


while(next<limit/2):       #don't let results get too big
    print last,'',         #display last term
    sum = next + last      #add last two terms
    next = last            #variables move forword in the series
    last = sum             
     
print '\n'
1  1  2  3  5  8  13  21  34  55  89  144  233  377  610  987  1597  2584  4181  6765  10946  17711  28657  46368  75025  121393  196418  317811  514229  832040  1346269  2178309  3524578  5702887  9227465  14930352  24157817  39088169  63245986  102334155  165580141  267914296  433494437  701408733  1134903170  1836311903  2971215073  

Example 3.8, Page Number: 91

In [8]:
while True:                                   #start while loop
                                              #find out the quotient and remainder
    dividend = input("Enter dividend: ")
    divisor = input("Enter divisor: ")
    
    print 'Quotient is',dividend / divisor,
    print ', Remainder is',dividend % divisor
    
    ch = raw_input("Do another? (y/n): ")      #do it again
    
    if(ch == 'n'):              #loop condition
        break;
Enter dividend: 11
Enter divisor: 3
Quotient is 3 , Remainder is 2
Do another? (y/n): y
Enter dividend: 222
Enter divisor: 17
Quotient is 13 , Remainder is 1
Do another? (y/n): n

Example 3.9, Page Number: 94

In [9]:
x = input("Enter a number: ")              #get input

if(x > 100):                       #check whether a number is greater than 100 or not
    print 'That number is greater than 100 \n'
Enter a number: 2000
That number is greater than 100 

Example 3.10, Page Number: 96

In [10]:
x = input("Enter a number: ")          #get input

if(x > 100):                           #check whether a number is greater than 100 or not
    print 'That number',x,             #print the number
    print 'is greater than 100 \n'
Enter a number: 12345
That number 12345 is greater than 100 

Example 3.11, Page Number: 96

In [11]:
n = input("Enter a number: ")            #get input to test
b=0

for j in range(2,n/2+1,1):            #divide by every integer from 2
    
    if(n%j == 0):                     #if remainder is 0
        print 'It\'s not prime; divisible by',j             #it's divisible by j
        b=1
        break
        
if b==0:
    print 'It\'s prime'
Enter a number: 22231
It's not prime; divisible by 11

Example 3.12, Page Number: 98

In [12]:
x = input("Enter a number: ")              #get input

if x>100:                                #if input is greater than 100
    print 'That number is greater than 100\n'
    
else:                                    #if input less than or equal to 100
    print 'That number is not greater than 100\n'
Enter a number: 3
That number is not greater than 100

Example 3.13, Page Number: 100

In [13]:
chcount = 0             #counts non-space characters
wdcount = 1             #counts spaces between words
ch = 'a'

ch = raw_input("Enter a phrase: ")        #geting the line

for j in range(len(ch)):      #for loop till line ends
    if ch[j] == ' ':          #if it's a space
        wdcount += 1          #count a word
    else:                     #otherwise
        chcount += 1          #count a character

print 'Words =',wdcount,'\nLetters =',(chcount),'\n'        #display result
Enter a phrase: For while and do
Words = 4 
Letters = 13 

Example 3.14, Page Number: 101

In [14]:
chcount = 0             #counts non-space characters
wdcount = 1             #counts spaces between words
ch = 'a'

ch = raw_input("Enter a phrase: ")        #geting the line

for j in range(len(ch)):      #for loop till line ends
    if ch[j] == ' ':          #if it's a space
        wdcount += 1          #count a word
    else:                     #otherwise
        chcount += 1          #count a character

print 'Words =',wdcount,'\nLetters =',(chcount),'\n'        #display result
Enter a phrase: For while and do
Words = 4 
Letters = 13 

Example 3.15, Page Number: 102

In [15]:
dir = 'a'
x = 10
y = 10

print 'Type Enter to quit'

while(dir != '\n'):                 #untill Enter is typed
    
    print 'Your location is',x,',',y
    dir = raw_input('\nPress direction key (n, s, e, w): ')           #get direction
    
    if dir == 'n':       #go north
        y += 1
    else:
        if dir == 's':      #go south
            y -= 1
        else:
            if dir == 'e':      #go east
                x += 1
            else:
                if dir == 'w':     #go west
                    x-=1
                else:
                    break
Type Enter to quit
Your location is 10 , 10

Press direction key (n, s, e, w): s
Your location is 10 , 9

Press direction key (n, s, e, w): e
Your location is 11 , 9

Press direction key (n, s, e, w): 

Example 3.16, Page Number: 104

In [16]:
#get three numbers
print 'Enter three number, a, b, c:'
a = input()
b = input()
c = input()

if a==b:                        #if a=b
    
    if b==c:                    #if b=c i.e. all three numbers are same 
        print 'a, b, and c are the same\n'
        
    else:
        print 'b and c are different\n'
        
else:                       #if a != b
    print 'a and b are different\n'
Enter three number, a, b, c:
2
3
3
a and b are different

Example 3.17, Page Number: 106

In [17]:
dir = 'a'
x = 10
y = 10

print 'Type Enter to quit'

while(dir != '\n'):                 #untill Enter is typed
    
    print 'Your location is',x,',',y
    dir = raw_input('\nPress direction key (n, s, e, w): ')           #get charcter
    
    if dir == 'n':       #go north
        y += 1
    elif dir == 's':     #go south
        y -= 1
    elif dir == 'e':     #go east
        x += 1
    elif dir == 'w':     #go west
        x -= 1
    else:
        break
Type Enter to quit
Your location is 10 , 10

Press direction key (n, s, e, w): s
Your location is 10 , 9

Press direction key (n, s, e, w): e
Your location is 11 , 9

Press direction key (n, s, e, w): 

Example 3.18, Page Number: 107

In [18]:
speed = input("Enter 33, 45, or 78: ")             #get value of speed from user

#selection based on speed

if speed == 33:            #if user entered 33              
    print 'LP album\n'
    
elif speed == 45:          #if user entered 45
    print 'Single selection\n'
    
elif speed == 78:          #if user entered 78
    print 'Obsolete formate\n'
Enter 33, 45, or 78: 45
Single selection

Example 3.19, Page Number: 110

In [19]:
dir = 'a'
x = 10
y = 10

print 'Type Enter to quit'

while(dir != '\n'):                 #untill Enter is typed
    
    print 'Your location is',x,',',y
    dir = raw_input('\nPress direction key (n, s, e, w): ')           #get charcter
    
    if dir == 'n':       #go north
        y += 1
    elif dir == 's':      #go south
        y -= 1
    elif dir == 'e':      #go east
        x += 1
    elif dir == 'w':     #go west
        x -= 1
        
    elif not dir:
        print 'Exiting'
        break
        
    else:
        print 'Try again'
        
Type Enter to quit
Your location is 10 , 10

Press direction key (n, s, e, w): s
Your location is 10 , 9

Press direction key (n, s, e, w): e
Your location is 11 , 9

Press direction key (n, s, e, w): a
Try again
Your location is 11 , 9

Press direction key (n, s, e, w): 
Exiting

Example 3.20, Page Number: 113

In [20]:
for j in range(80):           #for every column
    ch = '' if j%8 else 'X'    #ch is 'x' if column is multiple of 8 and ' ' (space) otherwise
    print ch,
X        X        X        X        X        X        X        X        X        X       

Example 3.21, Page Number: 115

In [21]:
dir = 'a'
x = 10
y = 10

print 'Type Enter to quit'

while(dir != '\n'):                 #untill Enter is typed
    
    print 'Your location is',x,',',y
    dir = raw_input('\nPress direction key (n, s, e, w): ')           #get charcter
    
                          #Update coordinates
    if dir == 'n':        #go north
        y -= 1
    elif dir == 's':      #go south
        y += 1
    elif dir == 'e':      #go east
        x += 1
    elif dir == 'w':      #go west
        x -= 1
    else:
        break
    if x == 7 and y == 11:        #if x is 7 and y is 11
        print 'You found the treasure'
        break;                    #exit from program
Type Enter to quit
Your location is 10 , 10

Press direction key (n, s, e, w): w
Your location is 9 , 10

Press direction key (n, s, e, w): w
Your location is 8 , 10

Press direction key (n, s, e, w): w
Your location is 7 , 10

Press direction key (n, s, e, w): s
You found the treasure

Example 3.22, Page Number: 116

In [22]:
dir = 'a'
x = 10
y = 10

print 'Type Enter to quit'

while(dir != '\n'):                 #untill Enter is typed
    
    print 'Your location is',x,',',y
    
    if x < 5 or x > 15:        #if x west of 5 and x east 15
        print 'Beware: dragons lurk here'
    
    dir = raw_input('\nPress direction key (n, s, e, w): ')           #get charcter
    
                          #Update coordinates
    if dir == 'n':        #go north
        y -= 1
    elif dir == 's':      #go south
        y += 1
    elif dir == 'e':      #go east
        x += 1
    elif dir == 'w':     #go west
        x -= 1
    else:
        break
    
Type Enter to quit
Your location is 10 , 10

Press direction key (n, s, e, w): n
Your location is 10 , 9

Press direction key (n, s, e, w): e
Your location is 11 , 9

Press direction key (n, s, e, w): e
Your location is 12 , 9

Press direction key (n, s, e, w): e
Your location is 13 , 9

Press direction key (n, s, e, w): e
Your location is 14 , 9

Press direction key (n, s, e, w): e
Your location is 15 , 9

Press direction key (n, s, e, w): e
Your location is 16 , 9
Beware: dragons lurk here

Press direction key (n, s, e, w): 

Example 3.23, Page Number: 121

In [23]:
while True:
    
    dividend = input("\nEnter dividend: ")
    divisor = input("Enetre divisor")
    
    if divisor==0:                     #if attempt to divide by 0
        
        print 'Illegal divisor'        #display message
        continue                       #go to top of loop
        
    print 'Quotient is',dividend/divisor 
    print 'remainder is',dividend%divisor
    
    ch = raw_input('Do another? (y/n): ')
    
    if(ch=='n'):
        break
Enter dividend: 10
Enetre divisor0
Illegal divisor

Enter dividend: 5
Enetre divisor2
Quotient is 2
remainder is 1
Do another? (y/n): n
In [ ]: