Chapter 5.1: Decision Statements

Example 5.1, Page number: 64

In [1]:
#Check whether the entered number is less than 10? if yes, display the same

#Variable initialization
v = raw_input("Enter the number : ")

#In python, raw_input() is used to read values

v = int(v)

#Result
if v < 10 :
    print '\nNumber entered is less than 10'
Enter the number : 9

Number entered is less than 10

Example 5.2, Page number: 65

In [2]:
#Check equivalence of two numbers. Use if statement.

#Variable initialization

m = raw_input("Enter two numbers : ")
n = raw_input("Enter two numbers : ")

#In python, raw_input() is used to read values

m = int(m)
n = int(n)

#Result
if m - n == 0 :
    print '\nTwo numbers are equal'
Enter two numbers : 5
Enter two numbers : 5

Two numbers are equal

Example 5.3, Page number: 66

In [3]:
#Check whether the candidate's age is greater than 17 or not.  If yes, display
#message "Eligible for Voting"

#Variable initialization
age = raw_input("Enter age : ")
age = int(age)

#In python, raw_input() is used to read values

#Result
if age > 17 :
    print '\nEligible for Voting.'
Enter age : 20

Eligible for Voting.

Example 5.4, Page number: 66

In [5]:
#Use curly brace in the if block.  Enter only the three numbers and calculate
#their sum and multiplication

#Variable initialization
#in python,the map(int,raw_input().split()) function splits the input characters
#and converts it into integers and returns a value if all the values are integers
#otherwise an exception will be generated and initializes v as 0.
#using exception handling, this result can be achieved.

#Exception handling
try:
    #use space to separate the input characters
    v = raw_input("Enter Three Numbers : ")
    a,b,c = map(int,v.split())
    x = 3
except:
    x = 0

#Result
#in python, block of statements are identified using indentation
    
if x == 3:
    print "Addition : %d"%(a+b+c)
    print "Multiplication : %d"%(a*b*c)
Enter Three Numbers : 1 2 4
Addition : 7
Multiplication : 8

Example 5.5, Page number: 68

In [6]:
#Read the values of a,b,c through the keyboard.  Add them and after addition
#check if it is in the range of 100 & 200 or not. Print separate message for each.


#Variable initialization
a = raw_input("Enter Three Numbers a b c : ")
b = raw_input("Enter Three Numbers a b c : ")
c = raw_input("Enter Three Numbers a b c : ")

a = int(a)
b = int(b)
c = int(c)

print 'a = %d b = %d c = %d'%(a,b,c)
#Calculation
d = a + b + c

#Condition evaluation and Result
if d <= 200 and d >= 100 :
    print "Sum is %d which is in between 100 & 200"%(d)
else:
    print "\nSum is %d which is out of range"%(d)
Enter Three Numbers a b c : 50
Enter Three Numbers a b c : 52
Enter Three Numbers a b c : 54
a = 50 b = 52 c = 54
Sum is 156 which is in between 100 & 200

Example 5.6, Page number: 68

In [7]:
#Find the roots of a quadratic equation by using if else condition

#Variable initialization
a = raw_input("Enter Values for a, b, c : ")
b = raw_input("Enter Values for a, b, c : ")
c = raw_input("Enter Values for a, b, c : ")

a = int(a)
b = int(b)
c = int(c)

#Condition evaluation and Result
if b * b > 4 * a * c :
    x1 = b + sqrt(b*b - 4*a*c)/2*a
    x2 = b - sqrt(b*b - 4*a*c)/2*a
    print "\nx1 = %f x2 = %f"%(x1,x2)
else:
    print "\nRoots are Imaginary"
Enter Values for a, b, c : 5
Enter Values for a, b, c : 1
Enter Values for a, b, c : 5

Roots are Imaginary

Example 5.7, Page number: 69

In [8]:
#Calculate the square of those numbers only whose least significant digit is 5.


#Variable initialization
s = raw_input("Enter a Number : ")
s = int(s)

d = s % 10;

#Condition evaluation and Result
#There is no increment/decrement operator in python.
if d==5 :
    s = s/10
    s += 1
    print "\nSquare = %d%d"%(s*(s-1),d*d)
else:
    print "\nInvalid Number"
Enter a Number : 25

Square = 625

Example 5.8, Page number: 70

In [9]:
#Calculate the salary of medical representative based on the sales.  Bonus and
#incentive to be offered to him will be based on total sales.  If the sale
#exceeds Rs.100000/- follow the particulars of table (1) otherwise (2)

#  1.  TABLE                            2. TABLE
# Basic = Rs. 3000                  Basic = Rs. 3000
# HRA = 20% of basic                HRA = 20% of basic
# DA = 110% of basic                DA = 110% of basic
# Conveyance = Rs. 500              Conveyance = Rs. 500
# Incentive = 10% of sales          Incentive = 5% of sales
# Bonus = Rs. 500                   Bonus = Rs. 200


#Variable initialization
sale = raw_input("Enter Total Sales in Rs. : ")
sale = int(sale)

#Condition evaluation
if sale >= 100000 :
    bs = 3000
    hra = 20 * bs/100
    da = 110 * bs/100
    cv = 500
    incentive = sale * 10/100
    bonus = 500
else:
    bs = 3000
    hra = 20 * bs/100
    da = 110 * bs/100
    cv = 500
    incentive = sale * 5/100
    bonus = 200

#Result
ts = bs + hra + da + cv + incentive + bonus
print "\nTotal Sales : %.2f"%(sale)
print "\nBasic Salary : %.2f"%(bs)
print "\nHra          : %.2f"%(hra)
print "\nDa           : %.2f"%(da)
print "\nConveyance   : %.2f"%(cv)
print "\nIncentive    : %.2f"%(incentive)
print "\nBonus        : %.2f"%(bonus)
print "\nGross Salary : %.2f"%(ts)
Enter Total Sales in Rs. : 100000

Total Sales : 100000.00

Basic Salary : 3000.00

Hra          : 600.00

Da           : 3300.00

Conveyance   : 500.00

Incentive    : 10000.00

Bonus        : 500.00

Gross Salary : 17900.00

Example 5.9, Page number: 72

In [11]:
#Calculate energy bill using the starting and ending meter reading.
#The charges are as follows:

# No. of Units consumed         Rates in (Rs.)
# 200 - 500                     3.50
# 100 - 200                     2.50
# Less than 100                 1.50

#Variable initialization
initial = raw_input("Initial & Final Readings : ")
final = raw_input("Initial & Final Readings : ")

consumed = int(final) - int(initial)

#Condition evaluation
if consumed >= 200 and consumed <= 500 :
    total = consumed * 3.50
else:
    if consumed >= 100 and consumed <= 199:
          total = consumed * 2.50
    else :
        if consumed < 100 :
           total = consumed * 1.50

#Result
print "Total bill for %d unit is %f"%(consumed,total)
Initial & Final Readings : 1200
Initial & Final Readings : 1500
Total bill for 300 unit is 1050.000000

Example 5.10, Page number: 73

In [14]:
#Calculate energy bill by  reading the starting and ending meter reading.
#If the consumed electricity energy is greater than or equal to 200 units
#the rate should be 2.50/unit otherwise 1.50/unit.


#Variable initialization
initial = raw_input("Initial & Final Readings : ")
final = raw_input("Initial & Final Readings : ")

consumed = int(final) - int(initial)

#Condition evaluation
if consumed >= 200 :
    total = consumed * 2.50
else:
    total = consumed * 1.50

#Result
print "Total bill for %d unit is %f"%(consumed,total)
Total bill for 100 unit is 150.000000

Example 5.11, Page number: 73

In [12]:
#Sort six numbers and find the largest one by using ladder of if else

#Variable initialization
a = int(raw_input("Enter 1st number : "))
b = int(raw_input("Enter 2nd number : "))
c = int(raw_input("Enter 3rd number : "))
d = int(raw_input("Enter 4th number : "))
e = int(raw_input("Enter 5th number : "))
f = int(raw_input("Enter 6th number : "))

#Condition evaluation and Result
if a > b and a > c and a > d and a > e and a > f :
    print "Highest of six Number is : %d"%(a)
else:
    if b > a and b > c and b > d and b > e and b > f :
        print "Highest of six Number is : %d"%(b)
    else:
        if c > a and c > b and c > d and c > e and c > f :
            print "Highest of six Number is : %d"%(c)
        else:
            if d > a and d > b and d > c and d > e and d > f :
                print "Highest of six Number is : %d"%(d)
            else:
                if e > a and e > b and e > c and e > d and e > f :
                   print "Highest of six Number is : %d"%(e)
                else:
                    print "Highest of six Number is : %d"%(f)
Enter 1st number : 52
Enter 2nd number : 74
Enter 3rd number : 90
Enter 4th number : 45
Enter 5th number : 10
Enter 6th number : 22
Highest of six Number is : 90

Example 5.12, Page number: 74

In [13]:
#Find largest number out of three numbers.  Read the numbers through the keyboard


#Variable initialization
x = int(raw_input("\nEnter Three Numbers x,y,z : "))
y = int(raw_input("\nEnter Three Numbers x,y,z : "))
z = int(raw_input("\nEnter Three Numbers x,y,z : "))

print "\nLargest out of Three Numbers is : "

#Condition evaluation and Result
if x > y :
    if x > z:
        print "x = %d\n"%(x)
    else:
        print "z = %d\n"%(z)
else:
    if z > y:
        print "z =  %d\n"%(z)
    else:
        print "y = %d\n"%(y)
Enter Three Numbers x,y,z : 10

Enter Three Numbers x,y,z : 20

Enter Three Numbers x,y,z : 30

Largest out of Three Numbers is : 
z =  30

Example 5.13, Page number: 75

In [14]:
#Find the smallest out of the three numbers.


#Variable initialization
a = int(raw_input("\nEnter Three Numbers : "))
b = int(raw_input("\nEnter Three Numbers : "))
c = int(raw_input("\nEnter Three Numbers : "))
          
#Condition evaluation and Result
if a < b :
    if a < c:
        smallest = a
    else:
        smallest = c
else:
    if b < c:
        smallest = b
    else:
        smallest = c

#Result
print "The smallest of %d %d %d is %d\n"%(a,b,c,smallest)
Enter Three Numbers : 1

Enter Three Numbers : 5

Enter Three Numbers : 8
The smallest of 1 5 8 is 1

Example 5.14, Page number: 76

In [15]:
#Calculate gross salary for the conditions given below

#  BASIC SALARY(Rs.)        DA(Rs.)         HRA(Rs.)        CONVEYANCE(Rs.)
#   >= 5000               110% of basic   20% of basic          500
#   bs>=3000 & bs<5000    100% of basic   15% of basic          400
#   bs<3000               90% of basic    10% of basic          300


#Variable initialization
bs = int(raw_input("\nEnter Basic Salary : "))

#Condition evaluation
if bs >= 5000 :
    hra = 20 * bs/100
    da = 110 * bs/100
    cv = 500
else:
    if bs >= 3000 and bs < 5000 :
        hra = 15 * bs/100
        da = 100 * bs/100
        cv = 400
    else:
        if bs < 3000:
            hra = 10 * bs/100
            da = 90 * bs/100
            cv = 300

#Calculation
ts = bs + hra + da + cv

#Result
print "Basic Salary : %5.0f"%(bs)
print "Hra          : %5.0f"%(hra)
print "Da           : %5.0f"%(da)
print "Conveyance   : %5.0f"%(cv)
print "Gross Salary : %5.0f"%(ts)
Enter Basic Salary : 5400
Basic Salary :  5400
Hra          :  1080
Da           :  5940
Conveyance   :   500
Gross Salary : 12920

Example 5.15, Page number: 77

In [16]:
#Calculate the total interest based on the following.

#Principle Amount(Rs.)          Rate of Interest(Rs.)
#   >= 10000                        20%
#   >= 8000 & <= 9999               18%
#   < 8000                          16%


#Variable initialization
princ = int(raw_input("\nEnter Loan & No. of years :- "))
nyrs = int(raw_input("\nEnter Loan & No. of years :- "))

#Condition evaluation
if princ >= 10000 :
    rate = 20
else:
    if princ >= 8000 and princ <= 9999 :
        rate = 18
    else:
        if princ < 8000:
            rate = 16

#Calculation
interest = princ * nyrs * rate/100

#Result
print "Loan     : %6.2f"%(princ)
print "Years    : %6.2f"%(nyrs)
print "Rate     : %6.2f"%(rate)
print "Interest : %6.2f"%(interest)
Enter Loan & No. of years :- 5500

Enter Loan & No. of years :- 3
Loan     : 5500.00
Years    :   3.00
Rate     :  16.00
Interest : 2640.00

Example 5.16, Page number: 78

In [1]:
#Find the average of six subjects and display the results as follows.

#    AVERAGE                         RESULT
#   >34 & <50                   Third Division
#   >49 & <60                   Second Division
#   >60 & <75                   First Division
#   >75 & <100                  Distinction


#Variable initialization
a = int(raw_input("\nEnter Marks\nP  C  B  M  E  H\n"))
b = int(raw_input("\nEnter Marks\nP  C  B  M  E  H\n"))
c = int(raw_input("\nEnter Marks\nP  C  B  M  E  H\n"))
d = int(raw_input("\nEnter Marks\nP  C  B  M  E  H\n"))
e = int(raw_input("\nEnter Marks\nP  C  B  M  E  H\n"))
f = int(raw_input("\nEnter Marks\nP  C  B  M  E  H\n"))

#Calculation
#here sum1 is used instead of sum because sum is a function in python.
sum1 = a + b + c + d + e + f
avg = sum1/6

print "Total  : %d \nAverage  : %.2f"%(sum1,avg)

#Condition evaluation and Result
if a < 35 or b < 35 or c < 35 or d < 35 or e < 35 :
    print "Result : Fail"
    exit
if avg >= 34 and avg < 50 :
    print "Result  : Third Division "
else:
    if avg >= 49 and avg < 60:
        print "Result  :  Second Division"
    else:
        if avg >= 60 and avg > 75:
            print "Result  :  First Division"
        else:
            if avg >= 75 and avg <= 100:
                  print "Result  :  Distinction"
                  
Enter Marks
P  C  B  M  E  H
75

Enter Marks
P  C  B  M  E  H
75

Enter Marks
P  C  B  M  E  H
75

Enter Marks
P  C  B  M  E  H
75

Enter Marks
P  C  B  M  E  H
75

Enter Marks
P  C  B  M  E  H
75
Total  : 450 
Average  : 75.00
Result  :  Distinction

Example 5.17, Page number: 80

In [2]:
#Detect the entered number as to whether it is even or odd.  Use goto statement.


#Variable initialization
x = int(raw_input("\nEnter a Number : "))

#Condition evaluation
#There is no goto/label statement in python

if x%2 == 0:
    print "\n%d is Even Number."%(x)
else:
    print "\n%d is Odd Number."%(x)
Enter a Number : 5

5 is Odd Number.

Example 5.18, Page number: 81

In [3]:
#Calculate telephone bill.  Transfer controls at different places according
#to number of calls and calculate the total charges.  Follow rates as per
#given in the table.

#  Telephone call               Rate in Rs.
#       < 100                    No charges
#       > 99 & < 200                1
#       > 199 & < 300               2
#       > 299                       3


#Variable initialization
nc = int(raw_input("\nEnter Number of Calls : "))

#Condition evaluation
#There is no goto/label statement in python

if nc < 100:
    print "\nNo charges"
else:
    if nc > 99 and nc < 200:
        print "\nTotal Charges : %d Rs."%(nc*1)
    else:
        if nc > 199 and nc < 300:
            print "\nTotal Charges : %d Rs."%(nc*2)
        else:
            print "\nTotal Charges : %d Rs."%(nc*3)
Enter Number of Calls : 500

Total Charges : 1500 Rs.

Example 5.19, Page number: 82

In [4]:
#Check whether the entered year is a leap year or not. Use goto statement.

#Variable initialization
leap = int(raw_input("\nEnter Year : "))

#Condition evaluation
#There is no goto/label statement in python

if leap%4 == 0:
    print "\n%d is a leap year."%(leap)
else:
    print "%d is not a leap year."%(leap)
Enter Year : 2000

2000 is a leap year.

Example 5.20, Page number: 84

In [5]:
#Print lines by selecting the choice.

print "\n[1] ............"
print "\n[2] ____________"
print "\n[3] ************"
print "\n[4] ============"
print "\n[5] EXIT"

#Variable initialization
ch = int(raw_input("\nENTER YOUR CHOICE : "))

#Condition evaluation
#there is no switch case statement in python, an alternative is to use
#dictionary and functions

def dot():
    print "\n......................................................"

def line():
    print "\n______________________________________________________"

def star():
    print "\n******************************************************"

def equal():
    print "\n======================================================"

def ex():
    exit
    
options = {1 : dot,
           2 : line,
           3 : star,
           4 : equal,
           5 : ex
}

options[ch]()
[1] ............

[2] ____________

[3] ************

[4] ============

[5] EXIT

ENTER YOUR CHOICE : 1

......................................................

Example 5.21, Page number: 85

In [6]:
#Provide multiple functions such as 1. addition 2.Subtraction 3. Multiplication
#4.Division 5.Remainder calculation 6.Larger out of two by using switch statement

print "\n============================="
print "\n\t\tMENU"
print "\n============================="
print "\n\t[1] ADDITION"
print "\n\t[2] SUBTRACTION"
print "\n\t[3] MULTIPLICATION"
print "\n\t[4] DIVISION"
print "\n\t[5] REMAINDER"
print "\n\t[6] LARGER OUT OF TWO"
print "\n\t[0] EXIT"
print "\n============================="

#Variable initialization
ch = int(raw_input("\nENTER YOUR CHOICE : "))

#Condition evaluation
#there is no switch case statement in python, an alternative is to use
#dictionary and functions

if ch <= 6 and ch > 0:
    a = int(raw_input("Enter Two Numbers : "))
    b = int(raw_input("Enter Two Numbers : "))
    
def add():
    c = a + b
    print "\nAddition  : %d"%(c)

def sub():
    c = a - b
    print "\nSubtraction  : %d"%(c)

def mul():
    c = a * b
    print "\nMultiplication  : %d"%(c)

def div():
    c = a/b
    print "\nDivision  : %d"%(c)

def rem():
    c = a % b
    print "\nRemainder  : %d"%(c)

def larger():
    if a > b:
        print "\n%d (a) is larger than %d (b)"%(a,b)
    else:
        if b > a:
            print "\n%d (b) is larger than %d (a)"%(b,a)
        else:
            print "\n%d (a) & %d (b) are same"%(a,b)

def ex():
    print "\nTerminated by choice"
    exit

def default():
    print "\nInvalid Choice"

options = { 1 : add,
            2 : sub,
            3 : mul,
            4 : div,
            5 : rem,
            6 : larger,
            7 : ex,
            0 : default,
            8 : default,
            9 : default
}

options[ch]()
       
=============================

		MENU

=============================

	[1] ADDITION

	[2] SUBTRACTION

	[3] MULTIPLICATION

	[4] DIVISION

	[5] REMAINDER

	[6] LARGER OUT OF TWO

	[0] EXIT

=============================

ENTER YOUR CHOICE : 6
Enter Two Numbers : 9
Enter Two Numbers : 8

9 (a) is larger than 8 (b)

Example 5.22, Page number: 87

In [7]:
#Convert years into Minutes, Hours, Days, Months and Seconds using switch()
#statement


print "[1] MINUTES"
print "[2] HOURS"
print "[3] DAYS"
print "[4] MONTHS"
print "[5] SECONDS"
print "[0] EXIT"

#Variable initialization
ch = int(raw_input("\nEnter Your Choice : "))

#Condition evaluation
#there is no switch case statement in python, an alternative is to use
#dictionary and functions

if ch > 0 and ch < 6:
    yrs = int(raw_input("Enter Years : "))

#Calculation
#since min is a keyword in python, min1 is used instead.
mon = yrs * 12
ds = mon * 30
hrs = ds * 24
min1 = hrs * 60
se = min1 * 60

def minute():
    print "\nMinutes  : %ld"%(min1)

def hours():
    print "\nHours  : %ld"%(hrs)

def days():
    print "\nDays  : %ld"%(ds)

def months():
    print "\nMonths : %ld"%(mon)

def seconds():
    print "\nSeconds : %ld"%(se)

def ex():
    print "\nTerminated by choice"
    exit

def default():
    print "\nInvalid Choice"

options = { 1 : minute,
            2 : hours,
            3 : days,
            4 : months,
            5 : seconds,
            6 : ex,
            0 : default,
            8 : default,
            9 : default
}

options[ch]()
       
[1] MINUTES
[2] HOURS
[3] DAYS
[4] MONTHS
[5] SECONDS
[0] EXIT

Enter Your Choice : 4
Enter Years : 2

Months : 24

Example 5.23, Page number: 89

In [8]:
#Display the names of the days of a week.


#Variable initialization
day = int(raw_input("\nEnter a number between 1 to 7 : "))

#Condition evaluation
#there is no switch case statement in python, an alternative is to use
#dictionary and functions

def first():
    print "\n1st day of week is Sunday"

def second():
    print "\n2nd day of week is Monday"

def third():
    print "\n3rd day of week is Tuesday"

def fourth():
    print "\n4th day of week is Wednesday"

def fifth():
    print "\n5th day of week is Thursday"

def sixth():
    print "\n6th day of week is Friday"

def seventh():
    print "\n7th day of week is Saturday"

def default():
    print "\nInvalid day"

options = { 1 : first,
            2 : second,
            3 : third,
            4 : fourth,
            5 : fifth,
            6 : sixth,
            7 : seventh,
            0 : default,
            8 : default,
            9 : default
}
for i in range(1,day+1):
    options[i]()
       
Enter a number between 1 to 7 : 4

1st day of week is Sunday

2nd day of week is Monday

3rd day of week is Tuesday

4th day of week is Wednesday

Example 5.24, Page number: 90

In [4]:
#Perform following operations

#1. Display any numbers or stars on the screen by using for loop
#2. Display the menu containing the following
#a) Whole screen b)Half screen c)Top 3 lines d)Bottom 3 lines

import os
import sys
import turtle


#Print numbers in the whole screen
for i in range(1,700):
    sys.stdout.write("%d"%i)

print "\nCLEAR MENU"
print "\t1] Whole Screen\t2] Half Screen\t3]Top 3 lines\t4] Bottom 3 lines\t5] Exit"

#Variable initialization
c = int(raw_input("Enter Your Choice : "))

#Condition evaluation
#there is no switch case statement in python, an alternative is to use
#dictionary and functions

def one():
    os.system('cls')

def two():
    for i in range(0,190):
        turtle.goto(i,1)
        sys.stdout.write("\t")
    
def three():
    for i in range(1,100):
        turtle.goto(i,1)
        sys.stdout.write("\t")

def four():
    for i in range(1,120):
        turtle.goto(i,21)
        sys.stdout.write("\t")

def five():
    exit


options = { 1 : one,
            2 : two,
            3 : three,
            4 : four,
            5 : five
}
options[c]()
       
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
CLEAR MENU
	1] Whole Screen	2] Half Screen	3]Top 3 lines	4] Bottom 3 lines	5] Exit
																																																																																																																																																																																														

Example 5.25, Page number: 91

In [3]:
#Display the files of current directory

import os

print "\nFILE LISTING MENU"
print "1] .EXE"
print "2] .BAT"
print "3] .OBJ"
print "4] .BAK"
#Variable initialization
c = int(raw_input("Enter Your Choice -: "))

#Condition evaluation
#there is no switch case statement in python, an alternative is to use
#dictionary and functions

def one():
    os.system('dir *.exe')

def two():
    os.system('dir *.c')

def three():
    os.system('dir *.obj')

def four():
    os.system('dir *.bak')

options = { 1 : one,
            2 : two,
            3 : three,
            4 : four
}
options[c]()

       
FILE LISTING MENU
1] .EXE
2] .BAT
3] .OBJ
4] .BAK

Example 5.26, Page number: 92

In [4]:
#Display number of days in calendar format of an entered month of year 2001.

import sys

#Variable initialization
m = int(raw_input("Enter Month No. of Year 2001 : "))

#Condition evaluation
#there is no switch case statement in python, an alternative is to use
#else-if ladder.

print "\nMonth - %d - 2001"%(m)
print "\n\tSUN\tMON\tTUE\tWED\tTHU\tFRI\tSAT"

#Find a day any month of 2001

if m == 1:
    a = 2
    j = 31
else:
    if m == 2:
        a = 5
        j = 28
    else:
        if m == 3:
            a = 5
            j = 31
        else:
            if m == 4:
                a = 1
                j = 30
            else:
                if m == 5:
                    a = 3
                    j = 31
                else:
                    if m == 6:
                        a = 6
                        j = 30
                    else:
                        if m == 7:
                            a = 1
                            j = 31
                        else:
                            if m == 8:
                                a = 4
                                j = 31
                            else:
                                if m == 9:
                                    a = 7
                                    j = 30
                                else:
                                    if m == 10:
                                        a = 2
                                        j = 31
                                    else:
                                        if m == 11:
                                            a = 5
                                            j = 30
                                        else:
                                            if m == 12:
                                                a = 7
                                                j = 31
                                            else:
                                                print "Invalid Month"
                                                exit

#Starting day is to be adjusted under the respective day
#sys.stdout.write() function performs the same task as printf() function
                                                
i = 1
if a == 1:
    sys.stdout.write("\t%d"%(i))
else:
    if a == 2:
        sys.stdout.write("\t\t%d"%(i))
    else:
        if a == 3:
            sys.stdout.write("\t\t\t%d"%(i))
        else:
            if a == 4:
                sys.stdout.write("\t\t\t\t%d"%(i))
            else:
                if a == 5:
                    sys.stdout.write("\t\t\t\t\t%d"%(i))
                else:
                    if a == 6:
                        sys.stdout.write("\t\t\t\t\t\t%d"%(i))
                    else:
                        if a == 7:
                            sys.stdout.write("\t\t\t\t\t\t\t%d"%(i))


h = 8 - a        #The starting day is subtracted from 8
for i in range(2,h+1):       #to display the first row
    sys.stdout.write("\t%d"%(i))
sys.stdout.write("\n")
b = 1
for i in range(h+1,j+1):          #to continue with second row onwards
    if b == 8:
        sys.stdout.write("\n")
        b = 1
    sys.stdout.write("\t%d"%(i))
    b += 1
Month - 1 - 2001

	SUN	MON	TUE	WED	THU	FRI	SAT
		1	2	3	4	5	6
	7	8	9	10	11	12	13
	14	15	16	17	18	19	20
	21	22	23	24	25	26	27
	28	29	30	31

Example 5.27, Page number: 95

In [9]:
#Convert decimal to hexadecimal number.

import sys
import turtle

#Variable initialization
x = int(raw_input("Enter a number : "))
y = 30

#Condition evaluation
#there is no switch case statement in python, an alternative is to use
#else-if ladder.

print "\nConversion of Decimal to Hexadecimal Number"

#for loop without condition is not supported in python. so while loop is used.

c = 1
z = [0 for i in range(0,15)]

while x != 0:
    z[c] = x % 16
    c = c + 1
    x = x/16


for i in range(c-1,0,-1):
    if z[i] == 10:
       sys.stdout.write("A")
    else:
       if z[i] == 11:
          sys.stdout.write("B")
       else:
          if z[i] == 12:
             sys.stdout.write("C")
          else:
             if z[i] == 13:
                sys.stdout.write("D")
             else:
                if z[i] == 14:
                   sys.stdout.write("E")
                else:
                    if z[i] == 15:
                       sys.stdout.write("F")
                    else:
                       sys.stdout.write("%d"%(z[i]))
    
    
    
Enter a number : 31

Conversion of Decimal to Hexadecimal Number
1F

Example 5.28, Page number: 97

In [10]:
#Detect whether the entered number is even or odd. use nested switch-case


#Variable initialization
x = int(raw_input("Enter a Number : "))

#Condition evaluation
#there is no switch case statement in python, an alternative is to use
#else-if ladder.

if x == 0:
    print "Number is Even"
else:
    if x == 1:
        print "Number is odd"
    else:
        y = x % 2
        if y == 0:
            print "Number is Even"
        else:
            print "Number is odd"
Enter a Number : 5
Number is odd

Example 5.29, Page number: 98

In [11]:
#Count number of 1s, 0s, blank spaces and others using nested
#switch() statement in a given stream

import sys

#Variable initialization
txt = raw_input("Enter Numbers : ")

#Processing
x = 0
s = 0
a = 0
z = 0
o = 0

while x < len(txt):
    if txt[x] == ' ':
        s = s + 1
    else:
        if txt[x] == '1':
            a = a + 1
        else:
            if txt[x] == '0':
                z = z + 1
            else:
                o = o + 1
    x = x + 1
    
#Result
sys.stdout.write("\nTotal Spaces : %d"%(s))
sys.stdout.write("\nTotal 1s  :  %d"%(a))
sys.stdout.write("\nTotal 0s  :  %d"%(z))
sys.stdout.write("\nOthers    :  %d"%(o))
sys.stdout.write("\nString Length  : %d"%(s+a+z+o))
        
    
Enter Numbers : 1110022 222

Total Spaces : 1
Total 1s  :  3
Total 0s  :  2
Others    :  5
String Length  : 11

Example 5.30, Page number: 99

In [12]:
#Convert integer to character using if condition


#Variable initialization
x = int(raw_input("Enter a Number : "))

#Condition evaluation
#ord() function converts the character ASCII to integer

if x == ord('A'):
    print "%c"%(x)
Enter a Number : 65
A

Example 5.31, Page number: 100

In [1]:
#Use nested if..else statements in switch() statement.  Also show the effect
#of conversion of integer to character


#Variable initialization
i = int(raw_input("Enter any ASCII Number : "))

#Condition evaluation
#there is no switch..case statement in python. alternative is to use
#if..else and else..if ladder

if i == ord('A'):
    print "Capital A"
else:
    if i == ord('B'):
        print "Capital B"
    else:
        if i == ord('C'):
            print "Capital C"
        else:
            if i > 47 and i < 58:
                print "Digit : [%c]"%(i)
            else:
                if i >= 58 and i <= 64:
                    print "Symbol : [%c]"%(i)
                else:
                    if i > 64 and i < 91:
                        print "Capital : [%c]"%(i)
                    else:
                        if i > 96 and i < 123:
                            print "Small : [%c]"%(i)
                        else:
                            print "Invalid Choice"
Enter any ASCII Number : 65
Capital A
In [ ]: