Chapter 3 Control Structures - Department of...
Transcript of Chapter 3 Control Structures - Department of...
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 1
Chapter 3 – Control Structures With this chapter, we begin a detailed discussion of the concepts and techniques of computer programming. We start by looking at issues related to the representation, manipulation, and input/ output of data—fundamental to all computing.
OBJECTIVES
After reading this chapter and completing the exercises, you will be able to:
Explain and use numeric and string literal values Explain the limitations in the representation of floating-point values Explain what a character-encoding scheme is Explain what a control character is Explain and use variables, identifiers, and keywords Describe and perform variable assignment Describe and use operators and expressions Describe and use operator precedence and operator associativity Define a data type, and explain type coercion vs. type conversion Explain the difference between static and dynamic typing Effectively use arithmetic expressions in Python Write a simple straight-line Python program Explain the importance and use of test cases in program testing
Chapter Overview
The purpose of this chapter is to introduce to students the fundamental control flows of sequence, selection and iteration. Specifically, the if (including multi-way selection) and while statements (including discussion of infinite loops, and definite vs. indefinite loops) are presented, along with a first discussion of Boolean values and Boolean expressions.
Section 3.1 – What is a Control Structure?
In this brief first section students are introduced to the notion of sequential, selection and iterative control. The distinction is made between a control statement and a control structure. Also, the term straight-line program is mentioned.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 2
Section 3.2 – Boolean Expressions (Conditions)
In this section, the Boolean data type and Boolean expressions are introduced. Section 3.2.1 introduces the relational operators ==, !=, <, <=, >, and >=. Examples are given of the use of these operators on string, as well as numeric values. The term lexographical (dictionary) ordering is given. It is explained that the ordering of strings is based on the underlying character encoding scheme. Section 3.2.2 presents membership operators in and not in. The term tuple is mentioned as a list of comma-separate items within parentheses, said to be covered in Chapter 4. Membership operators are described as applying to tuples and substrings within a string. (Mentioned of lists is deferred to Chapter 4.) Section 3.2.3 presents the Boolean operators and, or and not in Python. George Boole is mentioned as having developed (what we now call) Boolean algebra. Here it is explained that Python properly interprets Boolean expressions of the form value1 <= var <=
value2, with the warning that most languages require the form value1 <= var and var <= value2. Boolean literals true and false are also presented here. Section 3.2.4 discusses again operator precedence (first introduced in Chapter 2), this time incorporating Boolean operators and, or and not. Section 3.2.5 introduces the notion of short-circuit (lazy) evaluation, and said that Python performs this form of evaluation. Section 3.2.6 discusses logically equivalent Boolean expressions.
Section 3.3 – Selection Control
In this section, selection control statements of Python are introduced, including if and while. Section 3.3.1 introduces the if statement. Nested if statements are discussed, referred to as a compound statement. Only if statement with else header are presented at this point. Section 3.3.2 is the first place where the use of indentation in Python is presented. The definition of a suite in Python is given, with examples showing that requirement that all the statements of a given suite must be indented the same amount. Section 3.3.3 introduces multi-way selection. This is demonstrated both with the use of nested if statements, as well as an if statements with varying number of elif headers. Section 3.3.4 Let’s Apply It – “Number of Days in Month Program” This Let’s Apply It section involves multi-way selection by use of the if statement with elif headers. The program example will displays the number of days in a given month for a given month and year entered by the user. Leap years are counted for in the determination of the number of days in February.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 3
Section 3.4 – Iterative Control
In this section, iterative control is introduced by way of the while statement in Python. Section 3.4.1 introduces while loops. The first example demonstrates the use of a counter variable for control of the loop. Section 3.4.2 shows the use of while loop for input error checking. In section 3.4.3, the notion of an infinite loop is presented. Definite vs. indefinite loops are discussed in section 3.4.4. And the use of Boolean flags for iterative control of indefinite loops is given in section 3.4.5. Section 3.4.6 Let’s Apply It – “Coin Change Exercise Program” The program example incorporates the use of the while and if statements, a Boolean flag, and a random number generator. It provides a game for children by displaying a random amount of cents between 1 and 99, and asks the user to enter a set of coins that sums exactly to that amount.
Section 3.5 COMPUTATIONAL PROBLEM SOLVING – Calendar Month Program
This Computational Problem Solving section demonstrates the development of a program that displays a calendar month for a given month and year. Section 3.5.1 states the problem as displaying a calendar month between January 1800 and December 2099, formatted as shown. Section 3.5.2 analyzes the problem and determines that two algorithms are needed – one for determining the first day of a given month, and the other for appropriately displaying a calendar month. Section 3.5.3 presents a program design for this problem. The description of data needed for this program is the entered month and year, whether the year is a leap year or not, the number of days in the month, and which day the first of the month falls on. Given that information, the calendar month can be displayed. The algorithmic approach involves determining the day of the week that the first day of a given month falls on. The algorithm for this is given in Chapter 1. This algorithm depends on determining whether a given year is a leap year or not. The general rule for determining leap years is given (years divided by 4 and not divided by 100 are leap years, with the exception that years divided by 400 are also leap years). An algorithm for displaying a given calendar month in the format required is developed (jn code).
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 4
Overall Program Steps
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 5
Section 3.5.4 demonstrates implementation and testing of the program. The program is developed in three stages. Stage 1 implements and tests the portion of the program that determines whether a given year is a leap year or not, and the number of days in a given month (for a given year). The code is tested by use of a test plan for a number of different months for years in the 1800s, 1900s, and 2000 including leap years and non-leap years. Stage 2 adds code to determine the day of the week for the first day of a given month and year. It is tested using the test cases used in the stage 1 testing. The final stage of the program displays a calendar month based on the number of days in the month and the day of the week for the first of the month given. It is initially presented with erroneous code. This is obvious since each week (row) of the month is displayed with eight days (only appropriate for a certain Beatle’s song). Through the demonstrated use of deskchecking, an “off by one” error is found (in which the condition for controlling the number of columns displayed should be current_col < 7, but is given as current_col <= 7). The correction is made and the program is found to be correct after passing a final test plan.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 6
SOLUTIONS TO CHAPTER EXERCISES
Section 3.1
1. Which of the three forms of control is an implicit form of control? ANSWER: Sequential control
2. What is meant by a “straight-line” program? ANSWER: A program using only sequential control
3. What is the difference between a control statement and a control structure?
ANSWER: A control statement (e.g., if n < 0) is a statement that determines the control flow of a set of statements. A control structure is a set of instructions and the control statement controlling their execution.
Section 3.2 4. The Boolean data type contains two values, denoted as literals __True__ and __False__ in Python. 5. Which of the following relational expressions evaluate to True?
(a) 5 < 8 (b) '5' < '8' (c) '10' < '8' (d) 'Jake' < 'Brian'
ANSWER: (a), (b), (c) 6. Which of the following relational expressions evaluate to True? (a) 5 <= 5 (b) 5 >= 5 (c) 5 == 5 (d) 5 != 5 (e) 5 != 10
ANSWER: (a), (b), (c), (e)
7. Give an appropriate expression for each of the following. (a) To determine if the number 24 does not appear in a given list of numbers assigned to variable nums.
ANSWER: 24 not in nums
(b) To determine if the name 'Ellen' appears in a list of names assigned to variable names.
ANSWER: 'Ellen' in names
(c) To determine if a single last name stored in variable last_name is either 'Morris' or
'Morrison'.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 7
ANSWER: last_name == 'Morris' or last_name == 'Morrison'
8. Evaluate the following Python expressions. (a) (12 * 2) == (3 * 8) (b) (14 * 2) != (3 * 8)
ANSWERS:
(a) True (b) True 9. What value for x makes each of the following Boolean expressions True?
(a) x or False
(b) x and True
(c) not (x or False) (d) not (x and True) ANSWERS:
(a) True (b) True (c) False (d) False 10. Evaluate the Boolean expressions below for n = 10 and k = 20.
(a) (n > 10) and (k == 20)
(b) (n > 10) or (k == 20) (c) not((n > 10) and (k == 20))
(d) not(n > 10) and not(k == 20)
(e) (n > 10) or (k == 10 or k != 5) ANSWERS:
(a) False (b) True (c) True (d) False (e) True
11. Give an appropriate Boolean expression for each of the following.
(a) Determine if variable num is greater than or equal to 0, and less than 100.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 8
ANSWER: num >= 0 and num < 100 NOTE: Although Python allows the form 0 <= num < 100, it’s use should be discouraged for beginner programmers.
(b) Determine if variable num is less than 100 and greater than or equal to 0, or it is equal to 200.
ANSWER: num >= 0 and num < 100 or num == 200 (c) Determine if either the name 'Thompson' or 'Wu' appears in a list of names assigned to variable last_names.
ANSWER: 'Thompson' in last_names or 'Wu' in last_names (d) Determine if the name 'Thomson' appears and the name 'Wu' does not appear in a list of last names assigned to variable last_names. ANSWER:
'Thompson' in last_names and not 'Wu' in last_names
or 'Thompson' in last_names and 'Wu' not in last_names
12. Evaluate the following Boolean expressions for num1 = 10 and num2 = 20.
(a) not (num1 < 1) and num2 < 10 (b) not (num1 < 1) and num2 < 10 or num1 + num3 < 100
ANSWERS:
(a) False (b) Textbook error (num3 not defined)
13. Give a logically equivalent expression for each of the following.
(a) num != 25 or num == 0 (b) 1 <= num and num <= 50 (c) not num > 100 and not num < 0 (d) (num < 0 or num > 100)
ANSWERS: (a) not (num == 25) or num == 0 (b) not(num < 1 or num > 50) (c) 0 <= num and num <= 100 (d) not (0 <= num and num <= 100)
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 9
Section 3.3
14. Give an appropriate if statement for each of the following.
(a) An if statement that displays 'within range' if num is between 0 and 100, inclusive.
if 0 <= num and num <= 100:
print('within range')
(b) An if statement that displays 'within range' if num is between 0 and 100, inclusive, and
displays 'out of range' otherwise.
if 0 <= num and num <= 100:
print('within range')
else:
print('out of range')
15. Rewrite the following if-else statements using a single if statement and the elif: header.
if temperature >= 85 and humidity > 60:
print('muggy day today')
else:
if temperature >= 85:
print('warm, but not muggy today')
else:
if temperature >= 65:
print('pleasant today')
else:
if temperature <= 45:
print('cold today')
else:
print('cool today')
if temperature <= 85 and humidity > 60:
print('muggy day today') elif temperature >= 85:
print('warm, but not too muggy today') elif temperature >= 65:
print('pleasant today') elif temperature <= 45:
print('cold today') else:
print('cool today')
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 10
16. Regarding proper indentation,
(a) Explain the change in indentation needed in order for the following code to be syntactically
correct. ANSWER: The lines following elif level <= 3 must be indented the same amount
(b) Indicate other changes in the indentation of the code that is not strictly needed, but would
make the code more readable.
ANSWER: To have all the indented lines indented the same amount.
if level <= 1:
print('Value is well within range')
print('Recheck in one year')
elif level <= 2:
print('Value is within range')
print('Recheck within one month')
elif level <= 3:
print('Value is slightly high)
print('Recheck in one week')
elif level <= 4:
print('Value abnormally high')
print('Shut down system immediately')
Section 3.4
17. Write a program segment that uses a while loop to add up all the even numbers between 100 and
200, inclusive.
total = 0 num = 100
while num <= 200:
total = total + num
num = num + 2
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 11
18. The following while loop is meant to multiply a series of integers input by the user, until a sentinel
value of 0 is entered. Indicate any errors in the code given.
product = 1
num = input('Enter first number: ')
while num != 0:
num = input('Enter first number: ')
product = product * num
print('product = ', product)
product = 1
num = int(input('Enter first number: ')) # needed conversion
while num != 0:
num = int(input('Enter next number: ')) # needed conversion
product = product * num
print('product = ', product) # indentation
19. For each of the following, indicate which is a definite loop, and which is an indefinite loop.
(a) num = input('Enter a non-zero value: ')
while num == 0:
num = input('Enter a non-zero value: ')
ANSWER: indefinite loop
(b) num = 0
while n < 10:
print 2 ** n
n = n + 1
ANSWER: definite loop
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 12
SOLUTIONS TO PYTHON PROGRAMMING EXERCISES
P1. Write a Python program in which the user enters either 'A','B', or 'C'. If 'A' is entered,
the program should display the word 'Apple'; if 'B' is entered, it displays 'Banana'; and if
'C' is entered, it displays 'Coconut'. Use nested if statements for this as depicted in Figure
3-15.
fruit = input("Enter 'A' for apple, 'B' for banana, and 'C' for coconut: ")
if fruit == 'A':
print('Apple')
else:
if fruit == 'B':
print('Banana')
else:
if fruit == 'C':
print('Coconut')
P2. Repeat question P1 using an if statement with elif headers instead.
fruit = input("Enter 'A' for apple, 'B' for banana, and 'C' for coconut: ")
if fruit == 'A':
print('Apple')
elif fruit == 'B':
print('Banana')
elif fruit == 'C':
print('Coconut')
P3. Write a Python program in which a student enters the number of college credits earned. If the
number of credits is greater than or equal to 90, 'Senior Status' is displayed; if greater than
or equal to 60, 'Junior Status' is displayed; if greater than or equal to 30, 'Sophomore
Status' is displayed; else, 'Freshman Status' is displayed. (Noted omissions)
num_credits = int(input('Enter number of credits earned: '))
if num_credits >= 90:
print('Senior Status')
elif num_credits >= 60:
print('Junior Status')
elif num_credits >= 30:
print('Sophomore Status')
else:
print('Freshman Status')
P4. Write a program that sums a series of (positive) integers entered by the user, excluding all numbers
that are greater than 100.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 13
num = int(input('Enter first number to sum (enter -1 to quit): '))
sum = 0
while num != -1:
if num <= 100:
sum = sum + num
num = int(input('Enter next number: '))
print('sum = ', sum)
P5. Write a program, in which the user can enter any number of positive and negative integer values,
that displays the number of positive values entered, as well as the total number of negative values.
entry = input("Enter first number (enter 'q' to quit): ")
pos_count = 0
neg_count = 0
while entry != 'q':
num = int(entry)
if num >= 0:
pos_count = pos_count + 1
else:
neg_count = neg_count + 1
entry = input("Enter first number (enter 'q' to quit): ")
print('Number of postive values entered: ', pos_count)
print('Number of negative values entered: ', neg_count)
P6. Write a program containing a pair of nested while loops that displays the integer values 1–100, ten
numbers per row, with the columns aligned as shown below,
col_num = 1
row_num = 1
while row_num <= 10:
while col_num <= 10:
print(format((row_num - 1) * 10 + col_num, '>4d'), end='')
col_num = col_num + 1
print()
col_num = 1
row_num = row_num + 1
P7. Display the integer values 1–100 as given in question P6 using only one while loop.
num = 1
while num <= 100:
print(format(num, '>4d'), end='')
if num % 10 == 0:
print()
num = num + 1
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 14
SOLUTIONS TO PROGRAM MODIFICATION PROBLEMS
M1. Temperature Conversion Program: Input Error Checking
Modify the Temperature Conversion program in Figure 3-19 to perform input error checking of
temperatures. On the Fahrenheit scale, absolute zero is –459.67. Therefore, all valid Fahrenheit
temperatures start at that value (with no upper limit). On the Celsius scale, absolute zero is
–273.15 (also with no upper limit). Thus, the program should reprompt the user for any invalid
entered temperatures.
# Display program welcome
# MODIFICATION: Input error checking of temperatures
print('This program will convert temperatures (Fahrenheit/Celsius)')
print('Enter (F) to convert Fahrenheit to Celsius')
print('Enter (C) to convert Celsius to Fahrenheit')
# Get temperature to convert
which = input('Enter selection: ')
while which != 'F' and which != 'C':
which = input("Please enter 'F' or 'C': ")
temp = float(input('Enter temperature to convert: '))
while (which == 'F' and temp < -459.67) or (which == 'C' and temp < -273.15):
temp = float(input('Invalid temperature. Please re-enter: '))
# Determine temperature conversion needed and display results
if which == 'F':
converted_temp = format((temp - 32) * 5/9, '.1f')
print(temp, 'degrees Fahrenheit equals', converted_temp, 'degrees Celsius')
else:
converted_temp = format((9/5 * temp) + 32, '.1f')
print(temp, 'degrees Celsius equals', converted_temp, 'degrees Fahrenheit')
This program will convert temperatures (Fahrenheit/Celsius)
Enter (F) to convert Fahrenheit to Celsius
Enter (C) to convert Celsius to Fahrenheit
Enter selection: F
Enter temperature to convert: -460
Invalid temperature. Please re-enter: 32
32.0 degrees Fahrenheit equals 0.0 degrees Celsius
>>> ================================ RESTART ================================
>>>
This program will convert temperatures (Fahrenheit/Celsius)
Enter (F) to convert Fahrenheit to Celsius
Enter (C) to convert Celsius to Fahrenheit
Enter selection: C
Enter temperature to convert: -274
Invalid temperature. Please re-enter: 100
100.0 degrees Celsius equals 212.0 degrees Fahrenheit
>>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 15
M2. Temperature Conversion Program: Addition of Kelvin Scale
Modify the Temperature Conversion program in Figure 3-19 to add an additional option of
converting to and from degrees Kelvin. The formula for conversion to Kelvin (K) from Celsius (C) is K
= C + 273.15. (This program is completely modified)
# Temperature Conversion Program
# MODIFICATION: Addition of Kelvin scale
# Display program welcome
print('This program converts temperatures between Fahrenheit/Celsius/Kelvin')
# Get temperature to convert
temp = int(input('Enter temperature: '))
temp_scale = input('Is this in (F)ahrenheit, (C)elsius or (K)elvin?: ')
while temp_scale != 'F' and temp_scale != 'C' and temp_scale != 'K':
temp_scale = input("Please enter 'F', 'C' or 'K': ")
# Get temperature scale to convert to
convert_temp_scale = input('Convert to (F)ahrenheit, (C)elsius or (K)elvin?: ')
while convert_temp_scale != 'F' and convert_temp_scale != 'C' and \
convert_temp_scale != 'K':
convert_temp_scale = input("Please enter 'F', 'C' or 'K': ")
# Convert temp
if temp_scale == 'F':
converting_from = 'Fahrenheit'
if convert_temp_scale == 'C':
converting_to = 'Celsius'
converted_temp = (temp - 32) * 5/9
elif convert_temp_scale == 'K':
converting_to = 'Kelvin'
converted_temp = (temp - 32) * 5/9 + 273.15
elif temp_scale == 'C':
converting_from = 'Celsius'
if convert_temp_scale == 'F':
converting_to = 'Fahrenheit'
converted_temp = (9/5 * temp) + 32
elif convert_temp_scale == 'K':
converting_to = 'Kelvin'
converted_temp = temp_scale + 273.15
elif temp_scale == 'K':
converting_from = 'Kelvin'
if convert_temp_scale == 'F':
converting_to = 'Fahrenheit'
converted_temp = (9/5 * (temp - 273.15)) + 32
elif convert_temp_scale == 'C':
converting_to = 'Celsius'
converted_temp = temp_scale + 273.15
# Display results
print(temp, 'degrees', converting_from ,'equals',
format(converted_temp, '.1f'), 'degrees', converting_to)
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 16
M3. Number of Days in Month Program: Input Error Checking
Modify the Number of Days in Month Program of section 3.3.4 so that the program prompts the
user to re-enter any invalid month (not in the range 1–12) or invalid year. (NOTE: Valid years begin
with the start of the Gregorian calendar in 1582.)
# Number of Day in Month Program
# MODIFICATION: Input error checking for invalid months/years
# program greeting
print('This program will display the number of days in a given month\n')
# init
valid_input = True
# get user input
month = int(input('Enter the month (1-12): '))
while month < 1 or month > 12:
month = int(input('Enter the month (1-12): '))
# determine num of days in month
# february
if month == 2:
year = int(input('Please enter the year (e.g., 2010): '))
while year < 1582:
year = int(input('Please enter year 1582 or later: '))
if (year % 4 == 0) and (not (year % 100 == 0) or (year % 400 == 0)):
num_days = 29
else:
num_days = 28
This program converts temperatures between Fahrenheit/Celsius/Kelvin
Enter temperature: 100
Is this in (F)ahrenheit, (C)elsius or (K)elvin?: C
Convert to (F)ahrenheit, (C)elsius or (K)elvin?: F
100 degrees Celsius equals 212.0 degrees Fahrenheit
>>> ================================ RESTART ================================
>>>
This program converts temperatures between Fahrenheit/Celsius/Kelvin
Enter temperature: 212
Is this in (F)ahrenheit, (C)elsius or (K)elvin?: F
Convert to (F)ahrenheit, (C)elsius or (K)elvin?: C
212 degrees Fahrenheit equals 100.0 degrees Celsius
>>> ================================ RESTART ================================
>>>
This program converts temperatures between Fahrenheit/Celsius/Kelvin
Enter temperature: 212
Is this in (F)ahrenheit, (C)elsius or (K)elvin?: F
Convert to (F)ahrenheit, (C)elsius or (K)elvin?: K
212 degrees Fahrenheit equals 373.1 degrees Kelvin
>>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 17
# january, march, may, july, august, october, december
elif month in (1, 3, 5, 7, 8, 10, 12):
num_days = 31
# april, june, september, november
elif month in (4, 6, 9, 11):
num_days = 30
# invalid input
else:
print('* Invalid Value Entered - ', month, '*')
valid_input = False
# output result
if valid_input:
print ('There are', num_days, 'days in the month')
M4. Number of Days in Month Program: Indication of Leap Years
Modify the Number of Days in Month program of section 3.3.4 so that the program displays, in
addition to the number of days in the month, that the year is a leap year as shown below.
Enter the month (1-12): 2
Please enter the year (e.g., 2010): 2000
There are 29 days in the month (a leap year)
# Number of Days in Month Program (Figure 3-16)
# MODIFICATION: Indication of leap years
# program greeting
print('This program will display the number of days in a given month')
print('and also indicate if an entered year is a leap year or not\n')
This program will display the number of days in a given month
Enter the month (1-12): 14
Enter the month (1-12): 0
Enter the month (1-12): 4
There are 30 days in the month
>>> ================================ RESTART ================================
>>>
This program will display the number of days in a given month
Enter the month (1-12): 2
Please enter the year (e.g., 2010): 1500
Please enter the year (e.g., 2010): 1600
There are 29 days in the month
>>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 18
# init
valid_input = True
leap_year = False
# get month and year from user
month = int(input('Enter the month (1-12): '))
year = int(input('Enter the year (e.g., 2010): '))
# determine if a leap year
if (year % 4 == 0) and (not (year % 100 == 0) or (year % 400 == 0)):
leap_year = True
# determine num of days in month
# february
if month == 2:
if leap_year:
num_days = 29
else:
num_days = 28
# january, march, may, july, august, october, december
elif month in (1, 3, 5, 7, 8, 10, 12):
num_days = 31
# april, june, september, november
elif month in (4, 6, 9, 11):
num_days = 30
# invalid input
else:
print('* Invalid Value Entered - ', month, '*')
valid_input = False
# output result
if valid_input:
if leap_year:
print ('There are', num_days, 'days in the month (a leap year)')
else:
print ('There are', num_days, 'days in the month (not a leap year)')
This program will display the number of days in a given month
and also indicate if an entered year is a leap year or not
Enter the month (1-12): 1
Enter the year (e.g., 2010): 2005
There are 31 days in the month (not a leap year)
>>> ================================ RESTART ================================
>>>
This program will display the number of days in a given month
and also indicate if an entered year is a leap year or not
Enter the month (1-12): 2
Enter the year (e.g., 2010): 2004
There are 29 days in the month (a leap year)
>>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 19
M5. Oil Change Notification Program: Numbers of Miles before Change
Modify the Oil Change Notification program in Figure 3-21 so that the program displays the number
of miles left before the next oil change, or the number of miles overdue for an oil change, as
appropriate.
# Oil Change Notification Program (Figure 3-21)
# MODIFICATION: Indication of number of miles due, or past due
# display program welcome
print('This program will determine if your car is in need of an oil change')
# init
miles_between_oil_change = 7500 # num miles between oil changes
miles_warning = 500 # how soon to warn of needed oil change
valid_entries = False
# get mileage of last oil change and current mileage and display
while not valid_entries:
mileage_last_oilchange = int(input('Enter mileage of last oil change: '))
current_mileage = int(input('Enter current mileage: '))
if current_mileage - mileage_last_oilchange < 0:
print('Invalid entry – current mileage entered is less than')
print('mileage entered of last oil change')
else:
miles_traveled = current_mileage - mileage_last_oilchange
valid_entries = True
if miles_traveled >= miles_between_oil_change:
print('You are', miles_traveled - miles_between_oil_change,
'miles past due for an oil change')
elif miles_traveled >= miles_between_oil_change - miles_warning:
print('You will be due for an oil change after the next',
miles_between_oil_change - miles_traveled, 'miles')
else:
print('You are not in immediate need of an oil change. Another',
miles_between_oil_change - miles_traveled, 'miles to go')
This program will determine if your car is in need of an oil change
Enter mileage of last oil change: 45801
Enter current mileage: 52400
You are not in immediate need of an oil change. Another 901 miles to go
>>> ================================ RESTART ================================
>>>
This program will determine if your car is in need of an oil change
Enter mileage of last oil change: 62504
Enter current mileage: 69906
You will be due for an oil change after the next 98 miles
>>>
This program will determine if your car is in need of an oil change
Enter mileage of last oil change: 38284
Enter current mileage: 46400
You are 616 miles past due for an oil change
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 20
M6. Coin Change Exercise Program: Addition of Half-Dollar Coins
Modify the Coin Change Exercise program in section 3.4.6 to allow for the use of half-dollar coins.
Make all necessary changes in the program.
# Coin Change Exercise Program (Figure 3-22)
# MODIFICATION: Addition of half-dollar coins
import random
# program greeting
print('The purpose of this exercise is to enter a number of coin values')
print('that add up to a displayed target value.\n')
print('Enter coins values as 1-penny, 5-nickel, 10-dime, 25-quarter, 50-half dollar')
print('Hit return after the last entered coin value.')
print('----------------')
# init
terminate = False
empty_str = ''
# start game
while not terminate:
amount = random.randint(1,99)
print('Enter coins that add up to', amount, 'cents, one per line.\n')
game_over = False
total = 0
while not game_over:
valid_entry = False
while not valid_entry:
if total == 0:
entry = input('Enter first coin: ')
else:
entry = input('Enter next coin: ')
if entry in (empty_str,'1','5','10','25', '50'):
valid_entry = True
else:
print('Invalid entry')
if entry == empty_str:
if total == amount:
print('Correct!')
else:
print('Sorry - you only entered', total, 'cents.')
game_over = True
else:
total = total + int(entry)
if total > amount:
print('Sorry - total amount exceeds', amount, 'cents.')
game_over = True
if game_over:
entry = input('\nTry again (y/n)?: ')
if entry == 'n':
terminate = True
print('Thanks for playing ... goodbye')
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 21
M7. Coin Change Exercise Program: Raising the Challenge
Modify the Coin Change Exercise program in section 3.4.6 so that the least possible number of
coins must be entered. For example, the least number of coins that total to 43 cents is 6 (one
quarter, one dime, one nickel, and three pennies).
# Exercise M7 (Chapter 3)
# Coin Change Exercise Program (Figure 3-22)
# MODIFICATION: Mininum number of coins requirement
import random
# program greeting
print('The purpose of this exercise is to enter a minimum number of coin')
print('values that add up to a displayed target value.\n')
print('Enter coins values as 1-penny, 5-nickel, 10-dime, 25-quarter')
print('Hit return after the last entered coin value.')
print('----------------')
# init
terminate = False
empty_str = ''
min_num_coins = 0
# start game
while not terminate:
amount = random.randint(1,99)
# determine min number of coins needed
temp_amount = amount
The purpose of this exercise is to enter a number of coin values
that add up to a displayed target value.
Enter coins values as 1-penny, 5-nickel, 10-dime, 25-quarter, 50-half dollar
Hit return after the last entered coin value.
----------------
Enter coins that add up to 91 cents, one per line.
Enter first coin: 50
Enter next coin: 25
Enter next coin: 10
Enter next coin: 5
Enter next coin: 1
Enter next coin:
Correct!
Try again (y/n)?: n
Thanks for playing ... goodbye
>>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 22
num_quarters = temp_amount // 25
temp_amount = temp_amount % 25
num_dimes = temp_amount // 10
temp_amount = temp_amount % 10
num_nickels = temp_amount // 5
temp_amount = temp_amount % 5
num_pennies = temp_amount
min_num_coins = num_quarters + num_dimes + num_nickels + num_pennies
# prompt user for coin entry
print('Enter the minimum number of coins that add up to', amount,
'cents, one per line.\n')
# init for each new game
game_over = False
total = 0
num_coins_entered = 0
while not game_over:
valid_entry = False
while not valid_entry:
if total == 0:
entry = input('Enter first coin: ')
else:
entry = input('Enter next coin: ')
if entry in (empty_str,'1','5','10','25'):
valid_entry = True
else:
print('Invalid entry')
if entry == empty_str:
if total == amount:
if num_coins_entered > min_num_coins:
print('This can be done with less coins. Try again.')
print('Enter the minimum number of coins that add up to',
amount, 'cents.\n')
total = 0
num_coins_entered = 0
else:
print('Correct!')
game_over = True
else:
print('Sorry - you only entered', total, 'cents.')
game_over = True
else:
num_coins_entered = num_coins_entered + 1
total = total + int(entry)
if total > amount:
print('Sorry - total amount exceeds', amount, 'cents.')
game_over = True
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 23
if game_over:
entry = input('\nTry again (y/n)?: ')
if entry == 'n':
terminate = True
print('Thanks for playing ... goodbye')
The purpose of this exercise is to enter the minimum number of coin
values that add up to a displayed target value.
Enter coins values as 1-penny, 5-nickel, 10-dime, 25-quarter
Hit return after the last entered coin value.
----------------
Enter the minimum number of coins that add up to 81 cents, one per line.
Enter first coin: 25
Enter next coin: 10
Enter next coin: 10
Enter next coin: 10
Enter next coin: 10
Enter next coin: 10
Enter next coin: 5
Enter next coin: 1
Enter next coin:
This can be done with less coins. Try again.
Enter the minimum number of coins that add up to 81 cents.
Enter first coin: 25
Enter next coin: 25
Enter next coin: 25
Enter next coin: 5
Enter next coin: 1
Enter next coin:
Correct!
Try again (y/n)?: n
Thanks for playing ... goodbye
>>> Thanks for playing ... goodbye
>>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 24
M8. Calendar Month Program: Indication of Leap Year
Modify the final version of the Calendar Month program in section 3.5 so that for leap years, the
month heading is displayed as in the following,
June 1984 (leap year)
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
# Exercise M8 (Chapter 3)
# Calendar Month Program (Section 3.5)
# MODIFICATION: Indication of Leap Years
# init
terminate = False
# program greeting
print('This program will display a calendar month between 1800 and 2099')
while not terminate:
# get month and year
month = int(input('Enter month 1-12 (-1 to quit): '))
if month == -1:
terminate = True
else:
while month < 1 or month > 12:
month = int(input('INVALID - Enter month (1-12): '))
year = int(input('Enter year (yyyy): '))
while year < 1800 or year > 2099:
year = int(input('INVALID - Enter year (1800-2099): '))
# determine if leap year
if (year % 4 == 0) and (not (year % 100 == 0) or (year % 400 == 0)):
leap_year = True
else:
leap_year = False
# determine num of days in month
if month in (1,3,5,7,8,10,12):
num_days_in_month = 31
elif month in (4,6,9,11):
num_days_in_month = 30
elif leap_year: # February
num_days_in_month = 29
else:
num_days_in_month = 28
# determine day of the week
century_digits = year // 100
year_digits = year % 100
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 25
value = year_digits + (year_digits // 4)
if century_digits == 18:
value = value + 2
elif century_digits == 20:
value = value + 6
if month == 1 and not leap_year:
value = value + 1
elif month == 2:
if leap_year:
value = value + 3
else:
value = value + 4
elif month == 3 or month == 11:
value = value + 4
elif month == 5:
value = value + 2
elif month == 6:
value = value + 5
elif month == 8:
value = value + 3
elif month == 9 or month == 12:
value = value + 6
elif month == 10:
value = value + 1
day_of_week = (value + 1) % 7 # 1-Sunday, 2-Monday, ..., 0-Saturday
# determine month name
if month == 1:
month_name = 'January'
elif month == 2:
month_name = 'February'
elif month == 3:
month_name = 'March'
elif month == 4:
month_name = 'April'
elif month == 5:
month_name = 'May'
elif month == 6:
month_name = 'June'
elif month == 7:
month_name = 'July'
elif month == 8:
month_name = 'August'
elif month == 9:
month_name = 'September'
elif month == 10:
month_name = 'October'
elif month == 11:
month_name = 'November'
else:
month_name = 'December'
# display month and year heading
if leap_year:
print('\n', ' ' + month_name, year, '(leap year)')
else:
print('\n', ' ' + month_name, year)
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 26
# display rows of dates
if day_of_week == 0:
starting_col = 7
else:
starting_col = day_of_week
current_col = 1
column_width = 4
blank_char = ' '
blank_column = format(blank_char, str(column_width))
while current_col < starting_col:
print(blank_column, end='')
current_col = current_col + 1
current_day = 1
while current_day <= num_days_in_month:
if current_day < 10:
print(format(blank_char, '3') + str(current_day), end='')
else:
print(format(blank_char, '2') + str(current_day), end='')
if current_col < 7:
current_col = current_col + 1
else:
current_col = 1
print()
current_day = current_day + 1
print('\n')
This program will display a calendar month between 1800 and 2099
Enter month 1-12 (-1 to quit): 2
Enter year (yyyy): 2024
February 2024 (leap year)
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
Enter month 1-12 (-1 to quit): 4
Enter year (yyyy): 2025
April 2025
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
Enter month 1-12 (-1 to quit): -1
>>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 27
M9. Calendar Month Program: User Entry of Month Name
Modify the final version of the Calendar Month program to allow the user to enter a month’s name
(e.g., 'January') rather than a number (e.g., 1). Make all appropriate changes in the program as a
result of this change.
# Exercise M9 (Chapter 3)
# Calendar Month Program (Section 3.5)
# MODIFICATION: User Entry of Month Names
# init
terminate = False
empty_str = ''
# program greeting
print('This program will display a calendar month between 1800 and 2099')
while not terminate:
# get month and year
month_name = \
input('Enter month as January, February, ... (hit Enter to quit): ')
if month_name == empty_str:
terminate = True
else:
while month_name not in ('January', 'February', 'March', 'April',
'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'):
print('INVALID Month Name\n')
month_name = input('Enter January, February, ... : ')
year = int(input('Enter year (yyyy): '))
while year < 1800 or year > 2099:
year = int(input('INVALID - Enter year (1800-2099): '))
# determine if leap year
if (year % 4 == 0) and (not (year % 100 == 0) or (year % 400 == 0)):
leap_year = True
else:
leap_year = False
# determine num of days in month
if month_name in ('January', 'March', 'May', 'July', 'August',
'October', 'December'):
num_days_in_month = 31
elif month_name in ('April', 'June', 'September', 'November'):
num_days_in_month = 30
elif leap_year: # February
num_days_in_month = 29
else:
num_days_in_month = 28
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 28
# determine day of the week
century_digits = year // 100
year_digits = year % 100
value = year_digits + (year_digits // 4)
if century_digits == 18:
value = value + 2
elif century_digits == 20:
value = value + 6
if month_name == 'January' and not leap_year:
value = value + 1
elif month_name == 'February':
if leap_year:
value = value + 3
else:
value = value + 4
elif month_name == 'March' or month_name == 'November':
value = value + 4
elif month_name == 'May':
value = value + 2
elif month_name == 'June':
value = value + 5
elif month_name == 'August':
value = value + 3
elif month_name == 'September' or month_name == 'December':
value = value + 6
elif month_name == 'October':
value = value + 1
day_of_week = (value + 1) % 7 # 1-Sunday, 2-Monday, ..., 0-Saturday
# determine month name
if month == 1:
month_name = 'January'
elif month == 2:
month_name = 'February'
elif month == 3:
month_name = 'March'
elif month == 4:
month_name = 'April'
elif month == 5:
month_name = 'May'
elif month == 6:
month_name = 'June'
elif month == 7:
month_name = 'July'
elif month == 8:
month_name = 'August'
elif month == 9:
month_name = 'September'
elif month == 10:
month_name = 'October'
elif month == 11:
month_name = 'November'
else:
month_name = 'December'
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 29
# display month and year heading
print('\n', ' ' + month_name, year)
# display rows of dates
if day_of_week == 0:
starting_col = 7
else:
starting_col = day_of_week
current_col = 1
column_width = 4
blank_char = ' '
blank_column = format(blank_char, str(column_width))
while current_col < starting_col:
print(blank_column, end='')
current_col = current_col + 1
current_day = 1
while current_day <= num_days_in_month:
if current_day < 10:
print(format(blank_char, '3') + str(current_day), end='')
else:
print(format(blank_char, '2') + str(current_day), end='')
if current_col < 7:
current_col = current_col + 1
else:
current_col = 1
print()
current_day = current_day + 1
print('\n')
This program will display a calendar month between 1800 and 2099
Enter month as January, February, ... (hit Enter to quit): Septmber
INVALID Month Name
Enter January, February, ... : September
Enter year (yyyy): 2024
September 2024
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
Enter month as January, February, ... (hit Enter to quit):
>>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 30
M10. Calendar Month Program: Addition of Day Heading
Modify the final version of the Calendar Month program in section 3.5 so that there is day
heading for each of the columns as shown below.
January 1800
Su Mo Tu We Th Fr Sa
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
# Exercise M10 (Chapter 3)
# Calendar Month Program (Section 3.5)
# MODIFICATION: Addition of Day Heading
# init
terminate = False
column_width = 4 # moved from below
empty_str = ''
# program greeting
print('This program will display a calendar month between 1800 and 2099')
while not terminate:
# get month and year
month = int(input('Enter month 1-12 (-1 to quit): '))
if month == -1:
terminate = True
else:
while month < 1 or month > 12:
month = int(input('INVALID - Enter month (1-12): '))
year = int(input('Enter year (yyyy): '))
while year < 1800 or year > 2099:
year = int(input('INVALID - Enter year (1800-2099): '))
# determine if leap year
if (year % 4 == 0) and (not (year % 100 == 0) or (year % 400 == 0)):
leap_year = True
else:
leap_year = False
# determine num of days in month
if month in (1,3,5,7,8,10,12):
num_days_in_month = 31
elif month in (4,6,9,11):
num_days_in_month = 30
elif leap_year: # February
num_days_in_month = 29
else:
num_days_in_month = 28
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 31
# determine day of the week
century_digits = year // 100
year_digits = year % 100
value = year_digits + (year_digits // 4)
if century_digits == 18:
value = value + 2
elif century_digits == 20:
value = value + 6
if month == 1 and not leap_year:
value = value + 1
elif month == 2:
if leap_year:
value = value + 3
else:
value = value + 4
elif month == 3 or month == 11:
value = value + 4
elif month == 5:
value = value + 2
elif month == 6:
value = value + 5
elif month == 8:
value = value + 3
elif month == 9 or month == 12:
value = value + 6
elif month == 10:
value = value + 1
day_of_week = (value + 1) % 7 # 1-Sunday, 2-Monday, ..., 0-Saturday
# determine month name
if month == 1:
month_name = 'January'
elif month == 2:
month_name = 'February'
elif month == 3:
month_name = 'March'
elif month == 4:
month_name = 'April'
elif month == 5:
month_name = 'May'
elif month == 6:
month_name = 'June'
elif month == 7:
month_name = 'July'
elif month == 8:
month_name = 'August'
elif month == 9:
month_name = 'September'
elif month == 10:
month_name = 'October'
elif month == 11:
month_name = 'November'
else:
month_name = 'December'
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 32
# display month and year heading
print('\n', ' ' + month_name, year, '\n')
# display day heading
print(format('Su', '>' + str(column_width)), end=empty_str)
print(format('Mo', '>' + str(column_width)), end=empty_str)
print(format('Tu', '>' + str(column_width)), end=empty_str)
print(format('We', '>' + str(column_width)), end=empty_str)
print(format('Th', '>' + str(column_width)), end=empty_str)
print(format('Fr', '>' + str(column_width)), end=empty_str)
print(format('Sa', '>' + str(column_width)))
# display rows of dates
if day_of_week == 0:
starting_col = 7
else:
starting_col = day_of_week
current_col = 1
column_width = 4 # moved above
blank_char = ' '
blank_column = format(blank_char, str(column_width))
while current_col < starting_col:
print(blank_column, end='')
current_col = current_col + 1
current_day = 1
while current_day <= num_days_in_month:
if current_day < 10:
print(format(blank_char, '3') + str(current_day), end='')
else:
print(format(blank_char, '2') + str(current_day), end='')
if current_col < 7:
current_col = current_col + 1
else:
current_col = 1
print()
current_day = current_day + 1
print('\n')
This program will display a calendar month between 1800 and 2099
Enter month 1-12 (-1 to quit): 5
Enter year (yyyy): 2016
May 2016
Su Mo Tu We Th Fr Sa
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
Enter month 1-12 (-1 to quit): -1
>>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 33
M11. Sage Program Modification
Following is the output of an “all knowing” Sage program that replies with random responses to
questions posed by the user. The responses generated have no meaningful connection to the
questions asked.
In the 1960s, a program called Eliza was developed that was able to behave as a psychotherapist.
It did not really understand anything, it only looked for certain words to turn the patient’s
comments or questions back to the patient. For example, if a patient said, “My mom drives me
crazy,” it might reply with “Tell me more about your mom.” Modify this program so that it
appears to have understanding by similar means of word recognition as used in the Eliza
program. Specifically, incorporate a set of “trigger” words that, if found, causes a specific
response to be given. For example, if the word “I” appears in the question (for example, “Will I
ever be rich?” or “Am I always going to be happy?”), the response may be “You are in charge of
your own destiny.” If the word “new” appears in the question (for example, “Will I find a new
boyfriend soon?” or “Will I find a new life?,” the response may be “Changes are up to you and
the unpredictable events in life.”
Be creative. In order to determine if a given word (or phrase) appears in a given question, make
use of the in membership operator.
# Fortune Teller Program
import random
have_question = 'y'
while have_question == 'y':
question = input('What is your question?:\n')
print('\nYou ask me', '"' + question + '" . . .')
rand_num = random.randint(1,8)
if rand_num == 1:
print ('The probabilities are in your favor')
elif rand_num == 2:
print ("I wouldn't make any definite plans")
elif rand_num == 3:
print ('The outlook is dim')
elif rand_num == 4:
print ('I would focus my thoughts on something else')
elif rand_num == 5:
print ('You are the only one that can answer that!')
elif rand_num == 6:
print ("You know the answer to that already, don't you?")
elif rand_num == 7:
print ('Someone unexpected can be most helpful with this')
elif rand_num == 8:
print ('It is close to certainty')
have_question = input('\nDo you have another question? (y/n): ')
print('Goodbye ... hope I was of some help!')
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
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 34
What is your question?:
When will I finally finish the book?
You ask me "When will I finally finish the book?" . . .
You know the answer to that already, don't you?
Do you have another question? (y/n): y
What is your question?:
Do you really know what I am asking?
You ask me "Do you really know what I am asking?" . . .
I would focus my thoughts on something else.
Do you have another question? (y/n): y
What is your question?:
Can't you answer my questions directly?
You ask me "Can't you answer my questions directly?" . . .
The probabilities are in your favor.
Do you have another question? (y/n): y
What is your question?:
So, what's the difference between an orange?
You ask me "So, what's the difference between an orange?" . . .
It is close to certainty.
Do you have another question? (y/n): y
What is your question?:
I think you are bogus, aren't you?
You ask me "I think you are bogus, aren't you?" . . .
Someone you would not expect can be most helpful about this.
Do you have another question? (y/n): n
Goodbye ... hope I was of some help!
>
>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 35
(complete modification)
# Exercise M11 (Chapter 3)
# Sage Program
# MODIFICATION: Addition of Word Recognition
import random
# init
empty_str = ''
references = ('She ', 'she ', 'He ', 'he ', 'Her ', 'her ', 'him ',
'They ', 'they ')
select_1 = 0
select_2 = 0
select_3 = 0
select_4 = 0
# get first response
print('I am here to help you. (Hit Enter to quit)\n')
response = input('So, tell me, how are you?\n> ')
print()
while response != empty_str:
if 'unhappy' in response or 'sad' in response or \
'depressed' in response:
print('What are you so unhappy about?')
elif 'angry' in response:
print('What are you angry about?')
elif 'frustrated' in response:
print('What are you frustrated about?')
elif 'jealous' in response:
print('Who are you jealous of?')
elif 'change' in response:
print('Are you afraid of change?')
elif 'no ' in response:
print('So what can you do about that?')
elif 'cannot' in response:
print('Are you really trying?')
elif 'not' in response:
print('What is the problem?')
elif '?' in response:
select_1 = select_1 + 1
if select_1 <= 3:
if select_1 == 1:
print('Is that why you came here?')
elif select_1 == 2:
print('Should you be asking yourself that question?')
elif select_1 == 3:
print('Do you have trouble making decisions for yourself?')
else:
print('What do you think?')
elif 'I ' in response and 'am ' in response:
select_2 = select_2 + 1
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 36
if select_2 <= 3:
if select_2 == 1:
print('Tell me more about your feelings')
elif select_2 == 2:
print('Is that how you want to be feeling?')
elif select_2 == 3:
print('So do you want to change?')
print('You are in charge of your own destiny')
else:
print('You are in charge of your own destiny')
elif 'I ' in response:
select_3 = select_3 + 1
if select_3 <= 3:
if select_3 == 1:
print('Tell me more about yourself')
elif select_3 == 2:
print('Tell me more about that')
elif select_3 == 3:
print('Are you fine with that?')
else:
print('So what does that tell you?')
elif 'my ' in response or 'My ' in response:
select_4 = select_4 + 1
if select_4 <= 3:
if select_4 == 1:
print('Is this an important person in your life?')
elif select_4 == 2:
print('How long has this person been a part of your life?')
elif select_4 == 3:
print('Do you worry about losing this relationship?')
else:
print('So what else about them?')
else:
rand_select = random.randint(1,4)
if rand_select == 1:
print('Tell me more')
elif rand_select == 2:
print('How has this been affecting you?')
elif rand_select == 3:
print('Have you talked to anyone else about this?')
else:
print('I understand')
response = input('> ')
print()
print('Goodbye ... hope I was of some help!')
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 37
I am here to help you. (Hit Enter to quit)
So, tell me, how are you? > not so good
What is the problem? > I am feeling depressed
What are you so unhappy about? > my girlfriend and I just broke up
Tell me more about yourself > I just keep thinking about her
Tell me more about that > I see her every day on campus
Are you fine with that? > no
How has this been affecting you? > I just feel so bad
So what does that tell you? > That I still miss her
So what does that tell you? > what else can I say?
Is that why you came here? > yes
I understand > so what can I do?
Should you be asking yourself that question? > I guess
So what does that tell you? > That I need to be able to deal with this?
Do you have trouble making decisions for yourself? > sometimes
I understand > so what should I do?
What do you think? > I guess I just have to get used to it and hope to feel better later
So what does that tell you? > that I know the answer to the problem
So what does that tell you? >
Goodbye ... hope I was of some help! >>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 38
SOLUTIONS TO PROGRAM DEVELOPMENT PROBLEMS
D1. Metric Conversion
Develop and test a Python program that converts pounds to grams, inches to centimeters, and
kilometers to miles. The program should allow conversions both ways.
# Metric Conversion Program
# Problem D1 (Chapter 3)
# This program will convert between pounds and grams, inches and centimeters,
# and miles and kilometers.
# init
GRAMS_PER_POUND = 453.592
CENTIMETERS_PER_INCH = 2.54
KILOMETERS_PER_MILE = 1.60934
done = False
while not done:
# get user conversion selection
print('\nEnter desired conversion')
print('------------------------')
print('1 - pounds / grams')
print('2 - inches / centimeters')
print('3 - miles / kilometers\n')
# get conversion type
which_conv = input('Enter: ')
while which_conv not in ('1', '2', '3'):
print('INVALID SELECTION\n')
which_conv = input('Enter: ')
if which_conv == '1': # pounds / grams
which_way = input('(a) pounds to grams, or (b) grams to pounds: ')
while which_way not in ('a', 'b'):
print('INVALID SELECTION\n')
which_way = input('(a) pounds to grams, or (b) grams to pounds: ')
print()
if which_way == 'a': # convert pounds to grams
amount = float(input('Enter number of pounds: '))
print(amount, 'pounds is equal to',
format(amount * GRAMS_PER_POUND, '.2f'), 'grams')
else: # convert grams to pounds
amount = float(input('Enter number of grams: '))
print(amount, 'grams is equal to',
format(amount/GRAMS_PER_POUND, '.2f'), 'pounds')
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 39
elif which_conv == '2': # inches / centimeters
which_way = input('(a) inches to cm, or (b) cm to inches: ')
while which_way not in ('a', 'b'):
print('INVALID SELECTION\n')
which_way = input('(a) inches to cm, or (b) cm to inches: ')
print()
if which_way == 'a': # convert inches to centimeters
amount = float(input('Enter number of inches: '))
print(amount, 'inches is equal to',
format(amount * CENTIMETERS_PER_INCH, '.2f'), 'centimeters')
else: # convert centimeters to inches
amount = float(input('Enter number of centimeters: '))
print(amount, 'centimeters is equal to',
format(amount / CENTIMETERS_PER_INCH, '.2f'), 'inches')
else: # miles / kilometers
which_way = input('(a) miles to km, or (b) km to miles: ')
while which_way not in ('a', 'b'):
print('INVALID SELECTION\n')
which_way = input('(a) miles to km, or (b) km to miles: ')
print()
if which_way == 'a': # convert miles to kilometers
amount = float(input('Enter number of miles: '))
print(amount, 'miles is equal to',
format(amount * KILOMETERS_PER_MILE, '.2f'), 'kilometers')
else: # convert kilometers to miles
amount = float(input('Enter number of kilometers: '))
print(amount, 'kilometers is equal to',
format(amount / KILOMETERS_PER_MILE, '.2f'), 'miles')
# ask user if wish to continue
print()
more = input('Do you wish to do another conversion (y/n): ')
while more not in ('y', 'Y', 'n', 'Y'):
more = input('Do you wish to do another conversion (y/n): ')
if more == 'n' or more == 'N':
done = True
print('Goodbye ...')
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 40
Enter desired conversion ------------------------ 1 - pounds / grams 2 - inches / centimeters 3 - miles / kilometers Enter: 1 (a) pounds to grams, or (b) grams to pounds: a Enter number of pounds: 155 155.0 pounds is equal to 70306.76 grams Do you wish to do another conversion (y/n): y Enter desired conversion ------------------------ 1 - pounds / grams 2 - inches / centimeters 3 - miles / kilometers Enter: 2 (a) inches to cm, or (b) cm to inches: b Enter number of centimeters: 100 100.0 centimeters is equal to 39.37 inches Do you wish to do another conversion (y/n): y Enter desired conversion ------------------------ 1 - pounds / grams 2 - inches / centimeters 3 - miles / kilometers Enter: 3 (a) miles to km, or (b) km to miles: 1 INVALID SELECTION (a) miles to km, or (b) km to miles: 1000 INVALID SELECTION (a) miles to km, or (b) km to miles: 1 INVALID SELECTION (a) miles to km, or (b) km to miles: a Enter number of miles: 1000 1000.0 miles is equal to 1609.34 kilometers Do you wish to do another conversion (y/n): n Goodbye ... >>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 41
D2. Leap Years to Come
Develop and test a Python program that displays future leap years, starting with the first occurring
leap year from the current year, until a fi nal year entered by the user. (HINT: Module datetime
used in the Age in Seconds Program of Chapter 2 will be needed here.)
# Leap Years to Come
# Problem D2 (Chapter 3)
# This program will list all the leap years starting from the current year
# to a year specified by the user
import datetime
# init
current_year = datetime.date.today().year
leapyear_found = False
# welcome
print('This program will list all leap years from the current year')
print('to a specified ending year\n')
# get last year of range from user
ending_year = int(input('Enter last year of range: '))
while ending_year < current_year:
print('Year must be current year or after\n')
ending_year = int(input('Enter last year of range: '))
# display leap years
print('\nThe following are leap years from', current_year, 'to',
ending_year, '\n')
while current_year <= ending_year:
if (current_year % 4 == 0) and \
(not (current_year % 100 == 0) or (current_yearyear % 400 == 0)):
print(current_year)
leapyear_found = True
current_year = current_year + 1
# check if any leap years found
if not leapyear_found:
print('(No leap years in specified range)')
This program will list all leap years from the current year
to a specified ending year
Enter last year of range: 2012
Year must be current year or after
Enter last year of range: 2050
The following are leap years from 2013 to 2050
2016
2020
2024
2028
2032
2036
2040
2044
2048
>>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 42
D3. The First-Time Home Buyer Tax Credit
Develop and test a Python program that determines if an individual qualifi es for a government
First-Time Home Buyer Tax Credit of $8,000. The credit was only available to those that (a) bought
a house that cost less than $800,000, (b) had a combined income of under $225,000 and (c) had
not owned a primary residence in the last three years.
# First-Time Home Buyer Tax Credit
# Problem D3 (Chapter 3)
# This program will determine if a person is eligible for a first-time
# home buyer federal tax credit based on the purchase price, income,
# and previous home ownership
# init
MAX_ALLOWED_HOME_VALUE = 800000
MAX_ALLOWED_COMBINED_INCOME = 225000
MIN_YEARS_PREVIOUS_OWNER = 3
# welcome
print('This program will determine if a person is eligible for a first-time')
print('home buyer federal tax credit\n')
# get purchase price of home
purchase_price = int(input('Enter purchase price: '))
if purchase_price > MAX_ALLOWED_HOME_VALUE:
print('\nThe purchase price is limited to $', MAX_ALLOWED_HOME_VALUE)
print('Therefore, you do not qualify for this federal tax credit')
else:
# get combined salary income
combined_income = int(input('Enter combined income: '))
if combined_income > MAX_ALLOWED_COMBINED_INCOME:
print('\nYour combined income exceeds the allowed maximum of $',
MAX_ALLOWED_COMBINED_INCOME)
print('Therefore, you do not qualify for this federal tax credit')
else:
response = input('Have you previously owned a home (y/n)? :')
while response not in ('y', 'Y', 'n', 'N'):
print('Invalid Response')
response = input('Have you previously owned a home (y/n)? :')
qualified = True
if response in ('y', 'Y'):
num_years_ago = \
int(input('How many years ago were you a home owner?: '))
if num_years_ago < MIN_YEARS_PREVIOUS_OWNER:
qualified = False
if not qualified:
print('\nYou do not qualify for this tax credit since you',
'were a homeowner within the\nlast',
MIN_YEARS_PREVIOUS_OWNER, 'years')
else:
print('\nCONGRATULATIONS!')
print('Based on the information provided,',
'you qualify for this federal tax credit')
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 43
D4. Home Loan Automization
Develop and test a Python program that calculates the monthly mortgage payments for a given
loan amount, term (number of years) and range of interest rates from 3% to 18%. The fundamental
formula for determining this is
A r(1 + r)n / ((1 + r)n - 1
where A is the original loan amount, r is the monthly interest rate (in decimal form), and n is the
total number of (monthly) mortgage payments.
This program will determine if a person is eligible for a first-time
home buyer federal tax credit
Enter purchase price: 280000
Enter combined income: 85000
Have you previously owned a home (y/n)? :n
CONGRATULATIONS!
Based on the information provided, you qualify for this federal tax credit
>>> ================================ RESTART ================================
>>>
This program will determine if a person is eligible for a first-time
home buyer federal tax credit
Enter purchase price: 450000
Enter combined income: 240000
Your combined income exceeds the allowed maximum of $ 225000
Therefore, you do not qualify for this federal tax credit
>>> ================================ RESTART ================================
>>>
This program will determine if a person is eligible for a first-time
home buyer federal tax credit
Enter purchase price: 325000
Enter combined income: 125000
Have you previously owned a home (y/n)? :n
CONGRATULATIONS!
Based on the information provided, you qualify for this federal tax credit
>>> ================================ RESTART ================================
>>>
This program will determine if a person is eligible for a first-time
home buyer federal tax credit
Enter purchase price: 500000
Enter combined income: 190000
Have you previously owned a home (y/n)? :y
How many years ago were you a home owner?: 2
You do not qualify for this tax credit since you were a homeowner within the
last 3 years
>>>
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 44
# First-Time Home Buyer Tax Credit
# Problem D4 (Chapter 3)
# This program will calculate the monthly mortage payment for a given
# loan amount and term (number of years) for interest rates between
# 3% and 18%.
# init
empty_str = ''
LOWEST_INT_RATE = 3
HIGHEST_INT_RATE = 18
# welcome
print('This program will display the monthly mortage payments for a given')
print('loan amount and loan period for interest rates from 3%-18%\n')
# get loan amount
loan_amount = int(input('Enter loan amount: '))
# get term of loan
num_years = int(input('Enter number of years of loan: '))
# display output heading
print('\nLoan Amount: $', format(loan_amount, ',.2f'),
'Term:', num_years, 'years\n')
print('Interest Rate Monthly Payment')
rate = LOWEST_INT_RATE
while rate <= HIGHEST_INT_RATE:
# calculate monthly payment
num_payments = num_years * 12 # total number of monthly payments
decimal_rate = (rate / 100) / 12 # monthly decimal interest rate
monthly_payment = \
(loan_amount * decimal_rate * (1 + decimal_rate) ** num_payments) / \
((1 + decimal_rate) ** num_payments - 1)
# display monthly payment
leading_blanks = ' '
if rate < 10:
print(leading_blanks, rate, '%', format(empty_str, '>15'),
format(monthly_payment, '.2f'))
else:
print(leading_blanks, rate, '%', format(empty_str, '>14'),
format(monthly_payment, '.2f'))
rate = rate + 1
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 45
This program will display the monthly mortage payments for a given
loan amount and loan period for interest rates from 3%-18%
Enter loan amount: 330000
Enter number of years of loan: 30
Loan Amount: $ 330,000.00 Term: 30 years
Interest Rate Monthly Payment
3 % 1391.29
4 % 1575.47
5 % 1771.51
6 % 1978.52
7 % 2195.50
8 % 2421.42
9 % 2655.25
10 % 2895.99
11 % 3142.67
12 % 3394.42
13 % 3650.46
14 % 3910.08
15 % 4172.67
16 % 4437.70
17 % 4704.73
18 % 4973.38
>>>