Chapter 6: Decision and control statements

Example 6.1, Page number: 114

In [1]:
# Variable declaration
old_number = 1
current_number = 1

print ('1')

# Calculation and result
while (current_number < 100) :
   print (current_number)
   next_number = current_number + old_number

   old_number = current_number
   current_number = next_number
1
1
2
3
5
8
13
21
34
55
89

Example 6.2, Page number: 115

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

# Calculation
while (i < 10) :
   item = 1

   if item == 0 :
      break

   total += item
   print ('Total: %d' % total)
   i = i + 1
        
# Result
print ('Final total: %d' % total)
Total: 1
Total: 2
Total: 3
Total: 4
Total: 5
Total: 6
Total: 7
Total: 8
Total: 9
Total: 10
Final total: 10

Example 6.3, Page number: 116

In [2]:
# Variable declaration
total = 0
minus_items = 0
i = 0

# Calculation
while (i < 10) :
   item = 1
   
   if item == 0 :
      break

   if item < 0 :
      minus_items += 1
      continue

   total += item
   print ('Total: %d' % total)
   i = i + 1
            
# Result
print ('Final total: %d' % total)
print ('with %d negative items omitted' % minus_items)
Total: 1
Total: 2
Total: 3
Total: 4
Total: 5
Total: 6
Total: 7
Total: 8
Total: 9
Total: 10
Final total: 10
with 0 negative items omitted

Example 6.4, Page number: 118

In [3]:
# Variable declaration
balance_owed = 100

# Calculation and result
if balance_owed == 0 :
   print ('You owe nothing.')
else :
   print ('You owe %d dollars.' % balance_owed)
You owe 100 dollars.