Chapter 7: Programming process

Example 7.1, Page number: 126

In [1]:
# Variable declaration
result = 0
i = 0

# Calculation and result
while (i < 3) :
   print ('Result: %d' % result)
   operator = '+'
   value = 10

   if operator == '+' :
      result += value
   else :
      print ('Unknown operator %c' % operator)
   i = i + 1         
Result: 0
Result: 10
Result: 20

Example 7.2, Page number: 133

In [4]:
# Variable declaration
result = 0
i = 0

# Calculation and result
while (i < 3) :
   print ('Result: %d' % result)
   operator = '+'
   value = 5

   if operator == 'q' or operator == 'Q' :
      break

   if operator == '+' :
      result += value

   if operator == '-' :
      result -= value

   if operator == '*' :
      result *= value

   if operator == '/' :
      if value == 0 :
         print ('Error: Divide by zero')
         print ('operation ignored') 
      else :
         result /= value

   i = i + 1
Result: 0
Result: 5
Result: 10

Example 7.3, Page number: 140

In [ ]:
import sys
import random
while (1) :

   # random number to be guessed
   number_to_guess = random.randrange (1, 101, 1)

   # current lower limit of player's range
   low_limit = 0

   # current upper limit of player's range
   high_limit = 100
   
   # number of times player guessed
   guess_count = 0

   while (1) :
      
      # tell user what the bounds are and get his guess
      print ('Bounds %d - %d\n' % (low_limit, high_limit))
      print ('Value[%d]?' % guess_count)
      
      guess_count += 1

      # number gotten from the player
      player_number = 50

      # did he guess right?
      if (player_number == number_to_guess) :
         break

      # adjust bounds for next guess
      if (player_number < number_to_guess) :
         low_limit = player_number
    
      else :
         high_limit = player_number

   print ('Bingo\n')