Chapter 5 - Making Decisions: if and switch Statements¶

example 5.1, page no. 100¶

In [1]:
a = 4
b = 5
print a, " > ", b, " is ", (a > b)
print a, " >= ", b, " is ", (a >= b)
print a, " == ", b, " is ", (a == b)
print a, " <= ", b, " is ", (a <= b)
print a, " < ", b, " is ", (a < b)

4  >  5  is  False
4  >=  5  is  False
4  ==  5  is  False
4  <=  5  is  True
4  <  5  is  True


example 5.2, page no. 102¶

In [2]:
print "Enter number of preregistered students: ",
total = int(raw_input())
print "Enter number of students adding the course: ",
print "Total number of students: ", total

Enter number of preregistered students: 30
Enter number of students adding the course: 3
Total number of students:  33


example 5.3, page no. 104¶

In [4]:
print "Enter a whole number: ",
num = int(raw_input())
if (num % 2 == 0):
print "The number is even"

Enter a whole number: 4
The number is even


example 5.4, page no. 108¶

In [5]:
print "Enter a whole number: ",
num = int(raw_input())
if (num % 2 == 0):
print "The number is even"
else:
print "The number is odd"

Enter a whole number: 5
The number is odd


example 5.4, page no. 109¶

In [6]:
print "Enter a whole number: ",
num = int(raw_input())
print "The number is", ("even" if num %2 == 0 else "odd")

Enter a whole number: 6
The number is even


example 5.6, page no. 112¶

In [7]:
print "Enter your test score: ",
testScore = int(raw_input())
if (testScore >= 90 ):
elif (testScore >= 80 ):
elif (testScore >= 70 ):
elif (testScore >= 60 ):
else:

Enter your test score: 70


example 5.7, page no. 115¶

In [9]:
print "Enter your grade: ",

print "Your average must be between 90 - 100"
print "Your average must be between 80 - 89"
print "Your average must be between 70 - 79"
print "Your average must be between 60 - 69"
else:
print "Your average must be below 60"

Enter your grade: D
Your average must be between 60 - 69


example 5.8, page no. 118¶

In [10]:
print "Enter your grade: ",

print "Your average must be between 90 - 100"
print "Your average must be between 80 - 89"
print "Your average must be between 70 - 79"
print "Your average must be between 60 - 69"
else:
print "Your average must be below 60"

Enter your grade: d
Your average must be between 60 - 69


example 5.9, page no. 119¶

In [*]:
print "Choose your car"
print "S for Standard"
print "L for Leather Seats"
print "D for Leather Seats + Chrome Wheels"
choice = raw_input()
print "Extra features purchased"
if choice == 'D':
print "Chrome wheels\n"
elif choice == 'L':
print "Leather seats"
else:
print "None selected"

In [ ]: