Hour 10: Controlling Programming flow

Exmaple 10.1, Page No.157

In [7]:
print "Integers that can be divided by both 2 and 3"
print "(within the range of 0 to 100):"
for i in range(0,100):
    if i%2==0 and i%3==0:
        print "  ",i
Integers that can be divided by both 2 and 3
(within the range of 0 to 100):
   0
   6
   12
   18
   24
   30
   36
   42
   48
   54
   60
   66
   72
   78
   84
   90
   96

Exmaple 10.2, Page No.159

In [10]:
print "Even Number   Odd Number"
for i in range(0,10):
    if(i%2==0):
        print i,
    else:
        print "{:14d}".format(i)
Even Number   Odd Number
0              1
2              3
4              5
6              7
8              9

Exmaple 10.3, Page No.160

In [1]:
for i in range(-5,6):
    if i>0:
        if i%2==0:
            print "{:d} is an even number.".format(i)
        else:
            print "{:d} is an odd number.".format(i)
    elif i==0:
        print "The number is zero."
    else:
        print "Negative number:",i
Negative number: -5
Negative number: -4
Negative number: -3
Negative number: -2
Negative number: -1
The number is zero.
1 is an odd number.
2 is an even number.
3 is an odd number.
4 is an even number.
5 is an odd number.

Example 10.4, Page No.162

In [17]:
day=raw_input("Please enter a sigle digit for a day\n(within the range of 1 to 3:)")
if day=='1':
    print "Day 1"
elif day=='2':
    print "Day 2"
elif day=='3':
    print "Day 3"
Please enter a sigle digit for a day
(within the range of 1 to 3:)3
Day 3

Example 10.5, Page No.164

In [22]:
#This program is specially used to understand the "break" statement in switch..case. 
#But in python we can't use break statement outside of the loop so break is not written with each if block.
day=raw_input("Please enter a sigle digit for a day\n(within the range of 1 to 7:)")
if day=='1':
    print "Day 1 is Sunday"
    
elif day=='2':
    print "Day 2 is Monday"
    
elif day=='3':
    print "Day 3 is Tuesday"
    
elif day=='4':
    print "Day 4 is Wednesday"
    
elif day=='5':
    print "Day 5 is Thursday"
    
elif day=='6':
    print "Day 6 is Friday"
    
elif day=='7':
    print "Day 7 is Saturday"
    
else:
    print "The digit is not within the range of 1 to 7"
    
Please enter a sigle digit for a day
(within the range of 1 to 7:)1
Day 1 is Sunday

Example 10.6, Page No.166

In [24]:
print "Enter a character:\n (enter X to exit)\n"
while 1:
    c=raw_input()
    if c=='x':
        break
print "Break the infinite loop. Bye!"
Enter a character:
 (enter X to exit)

H
I
x
Break the infinite loop. Bye!

Example 10.7, Page No.167

In [26]:
sum=0
for i in range(1,8):
    if i==3 or i==5:
        continue
    sum=sum+i
print "The sum of 1,2,4,6, and 7 is:",sum
The sum of 1,2,4,6, and 7 is: 20