Download Chapter 2 – Data and Expressions

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 2 – Data and Expressions
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 give students an understanding of data representation,
variables, expressions, expression evaluation and data types.
Section 2.1 – Literals
At the start of the chapter, students are introduced to the notion of a literal. Only numeric and
string literals are discussed. Boolean values are introduced in Chapter 3 with the discussion of
control structures.
Section 2.1.1 provides the definition of a literal. In section 2.1.2 numeric literals are introduced.
(Note that python allows the representation of floating-point values without a digit before the
decimal point.) Limitations in the range and precision of floating-points is also discussed in this
section, along with the notion of arithmetic overflow and underflow, as well as the built-in
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
1
format function for controlling the display of numeric types. (The formatting of strings in
covered in section 2.1.5.)
Section 2.1.3 covers string literals. Examples are given, including the use of both single and
double quotes, and the ability to embed single quotes in a string delimited by double quotes
(and vice versa). Triple quoted strings (docstrings) are left for Chapter 7 in the discussion of
module specification. The empty string is introduced (without an example of its use at this
point). Also, the representation of strings and the Unicode (and ASCII) encoding schemes is
discussed, along with the use of built-in functions ord and char.
Section 2.1.4 introduces control characters. Students are given the notion of an escape
character and escape sequence. The only escape sequence given is for newline (\n). String
formatting is covered in section 2.1.5. Use of the built-in format function is demonstrated for
left and right justification and centering of strings within a specified field width. It is also shown
how to easily produce as string of a given number of blanks (making use of the default blank fill
character), or how to specify a specific fill character (for producing a sequence of periods).
Section 2.1.6 explains the two fundamental means of line joining – implicit line joining that
occurs when multiple lines are delimited by either matching parentheses, square brackets, curly
braces, or triple quotes. And explicit line joining by use of the backslash character (\) at the end
of lines.
Section 2.1.7 Let’s Apply It – “Hello World Unicode Encoding”
This Let’s Apply It section involves a modified Hello World program. Rather than the traditional
example of a simple program that displays “Hello World”, this version displays the Unicode
(UTF-8, ASCII) values for each character in the string “Hello World.”
Section 2.2 – Variables and Identifiers
In this section, the notion of a variable, variable assignment and related issues are discussed.
Section 2.2.1 provides the definition of a variable. This includes discussion of the assignment
operator and variable assignment, immutable values, and memory deallocation. In addition,
the point is made that a variable may be assigned to values of different type.
Section 2.2.2 describes keyboard input as a means of variable assignment. It is pointed out that
values returned from the input function are of string type, and thus type conversion functions
int() and float() are discussed as a way of converting such input values to a numeric type.
Section 2.2.3 introduces the notion of an identifier, and the fact that Python is case sensitive is
mentioned. Section 2.2.4 introduces the notion of a keyword, and provides the keywords (and
means of displaying them) in Python.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
2
Section 2.2.5 Let’s Apply It – “Restaurant Tab Calculation”
This Let’s Apply It section involves a program capable of determining the final tab for a couple
at a restaurant making use of a $200 gift certificate (either having money left on the gift
certificate, and owing addition money for the meal).
Section 2.3 – Operators
In this section, the notion of an operator is discussed. Expressions are left for the following
section.
Section 2.3.1 provides the definition of an operator as a symbol that represents are operation
that may be performed on one or more operands. This includes discussion of unary and binary
operators.
Section 2.3.2 discusses arithmetic operators. The – symbol is pointed out to be both a unary
(for negation) and binary (for subtraction) operator. Here is where “true” division (/) vs.
truncating division (//) is introduced. Integer division is described as truncated division on
integer operands. The modulus operator (%) is also introduced here.
Section 2.3.3 Let’s Apply It – “Your Place in the Universe”
This Let’s Apply It section involves the calculation of the approximate number of atoms that the
average person contains, and the percentage of the universe that they comprise.
Section 2.4 – Expressions and Data Types
In this section, arithmetic expressions are introduced, as well as the notion of a data type.
Section 2.4.1 defines an expression as a combination of symbols that evaluates to a value.
Examples of arithmetic expressions are given, as well as examples of subexpressions.
Section 2.4.2 discusses operator precedence. Expressions in Python are described as being in
infix notation. Prefix and postfix expressions are mentioned to give a broader view of the ways
that expressions may be represented. It is explained that the order that operators are
evaluated in various programming languages depends on the operator precedence table
defined in that particular language. Section 2.4.3 discusses operator associativity. They learn
that of the arithmetic operators, all have left-to-right associativity except for exponentiation.
Section 2.4.4 introduces the notion of a data type. They learn that the integer, float and string
values that they have seen so far as part of the built-in types in Python. Here is where students
are told about static vs. dynamic typing, and that the Python programming language uses
dynamic typing. Mixed-type expressions are discussed in section 2.4.5. Here the notion of
implicit conversion (via coercion) vs. explicit conversion (via type conversion) is introduced.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
3
Section 2.4.6 Let’s Apply It – “Temperature Conversion Program”
This Let’s Apply It section involves the conversion of degrees Fahrenheit to degrees Celsius. This
example appears again in Chapter 3 in the discussion of control structures modified to allow the
user to select a conversion from Fahrenheit to Celsius or Celsius to Fahrenheit.
Section 2.5 COMPUTATIONAL PROBLEM SOLVING – Age In Seconds Program
This Computational Problem Solving Section demonstrates the development of a program that
calculates an estimate of the number of seconds that a person has been alive based on their
date of birth.
Section 2.5.1 states the problem as determining the age of an individual in seconds within 99%
accuracy of results obtained from online sources. The program must work for dates of birth
from January 1, 1900 to the present.
Section 2.5.2 analyzes the problem and determines that calculating the “exact” age in seconds
of an individual requires much information that is impractical to utilize (such as the time of
birth to the second, daylight savings time, etc.) and is most likely unneeded to obtain a result
that is within 99% of the actual result.
Section 2.5.3 presents a program design for this problem. The description of data needed for
this program is straightforward. Only individual integer values need to be stored for the
current date, date of birth, and some fixed values such as the number of seconds in a minute,
number of minutes in an hour, number of hours in a day, and number of days in a year.
The algorithmic approach described relies on obtaining the current date from the Python
Standard Library module datetime, and the date of birth from the user. To avoid the special
handling of leap years, the average number of seconds in a year is calculated as the average
number of second in three non-leap years and one leap year (since leaps years generally occur
every four years). To simplify the calculation of the number of years, months and days that
someone has been alive, rather than calculating the number of days from the given date of
birth to the current date, the number of seconds from January 1 1900 is calculated. Then the
different between these two values is taken,
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
4
Overall Program Steps
Section 2.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 inputs
the date of birth entered by the user, and the current date by use of standard library module
datetime. Each date is displayed on the screen at this point for testing. The code that is
developed is shown to be correct.
Stage 2 adds code to calculate an estimate of the number of seconds in a year (as the average
of the number of seconds over one non-leap year and one leap year), an estimated number of
seconds in a month, as well as the exact number of seconds in a day. The program is tested
(with the code developed in stage 1 commented out) and found to produce a reasonable value
for the average number of seconds in a year (and month), and the correct number of seconds in
a day.
The final stage of the program adds the remaining code that performs the calculations to
determine an estimated number of seconds that someone has been alive. Below is the test plan
used including “average”, “extreme” and “special case” test cases.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
5
The test results are incorrect for all dates except for the last test case. By inspection of variables
at the end of the program execution in the Python shell, negative values are found for variables
meant to store the number of second from 1900 to the given date of birth, and the number of
seconds from 1900 to the current date. By working backwards to what could cause such an
error, it is considered that if the calculations performed were, for example,
numsecs_1900_dob =
(year_birth – (1900 * avg_numsecs_year) ) + \
(month_birth – (1 * avg_numsecs_month) ) + \
(day_birth * numsecs_day)
instead of the correct expression,
numsecs_1900_dob =
(year_birth – 1900) * avg_numsecs_year ) + \
(month_birth – 1) * avg_numsecs_month ) + \
(day_birth * numsecs_day)
that would explain the erroneous results. This is in fact the problem, since parentheses were
not used, leaving the operator evaluation based on the rules of operator precedence. This also
explains why a recent date of birth is correctly calculated. Fixing the problem, the following
results are obtained, all within the required 99% of accuracy.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
6
SOLUTIONS TO CHAPTER EXERCISES
Section 2.1
1. Based on the information in Figure 2-1, how many novels can be stored in one terabyte of storage?
ANSWER: One million
2. Give the following values in the exponential notation of Python, such that there is only one
significant digit to the left of the decimal point.
(a) 4580.5034
(a) 4.5805034e3
(b) 0.00000046004
(b) 4.6004e-7
(c) 5000402.000000000006
(c) 5.00040200000000000e6
3. Which of the floating-point values in question 2 would exceed the representation of the precision of
floating points typically supported in Python, as mentioned in the chapter? ANSWER: (c)
4. Regarding the built-in format function in Python,
(a) Use the format function to display the floating-point value in variable result with three
decimal digits of precision.
print(format(result, '.3f'))
(b) Give a modified version of the format function in (a) so that commas are included in the
displayed results.
print(format(result, ',.3f'))
5. Give the string of binary digits that represents,
(a) The string 'Hi!' in ASCII code.
(b) The literal string 'I am 24'.
(a) 01001000 01101001 00100001
(b) 01001001 00100000 01100001 00100000 00110010 00110100
6. Give a call to print that is provided one string that displays the following address on three
separate lines.
John Doe
123 Main Street
Anytown, Maryland 21009
print('John Doe\n123 Main Street\nAnytown, Maryland 21009')
7. Use the print function in Python to output It's raining today.
print("It's raining today.")
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
7
Section 2.2
8. Regarding variable assignment,
(a) What is the value of variables num1 and num2 after the following instructions are executed?
num = 0
k=5
num1 = num + k * 2
num2 = num + k * 2
ANSWER: both num1 and num2 equal to 10
(b) Are the values id(num1) and id(num2) equal after the last statement is executed?
ANSWER: yes
9. Regarding input function in Python,
(a) Give an instruction that prompts a user for their last name and stores it in a variable named
last_name.
last_name = input('Please enter your last name:')
(b) Give an instruction that prompts a user for their age and stores it as an integer in a variable
named age.
age = int(input('What is your current age?:'))
(c) Give an instruction that prompts a user for their temperature and stores it as a float in a
variable named current_temperature.
current_temperature = float(input('What is your temperature?:'))
10. Regarding keywords and other predefined identifiers in Python, give the result for each of the
following,
(a) 'int' in dir(__builtins__)
(b) 'import' in dir(__builtins__)
ANSWERS:
(a) True
(b) False
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
8
Section 2.3
11. Which of the following operator symbols can be used as either a unary operator or a binary
operator? +, -, *, /
ANSWER: + and 12. What is the exact result of each of the following when evaluated?
(a) 12 / 6.0
(b) 21 // 10
(c) 25 // 10.0
ANSWERS:
(a) 2.0
(b) 2
(c) 2.0
13. If variable n contains an initial value of 1, what is the largest value that will be assigned to n after
the following assignment statement is executed an arbitrary number of times?
n = (n + 1) % 100
ANSWER: 99
14. Which of the following arithmetic expressions could potentially result in arithmetic overflow,
where n,k are each assigned integer values, and q,r are each assigned floating-point values?
(a) n * k
(b) n ** k
(c) n * q
(d) r * q
ANSWER: (c) and (d)
Section 2.4
15. Evaluate the following expressions in Python.
(a) 10 – (5 * 4)
(b) 40 % 6
(c) - (10 / 3) + 2
ANSWERS
(a) –10
(b) 4
(c) -1.3333333333333335
16. Give all the possible evaluated results for the following arithmetic expression assuming no rules of
operator precedence.
2 * 4 + 25 – 5
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
9
ANSWER:
(2 * 4) + 25 – 5 equals 28
2 * (4 + 25) – 5 equals 53
2 * (4 + 25 – 5) equals 48
17. Parenthesize all of the subexpressions in the following expressions following operator precedence
in Python.
(a) var1 * 8 – var2 + 32 / var3
(b) var1 – 6 ** 4 * var2 ** 3
ANSWERS:
(a) ((var1 * 8) – var2) + (32 / var3)
(b) var1 – ((6 ** 4) * (var2 ** 3))
18. Evaluate each of the expressions in question 17 above for var1 = 10, var2 = 30, and
var3 = 2.
ANSWERS:
(a) ((var1 * 8) – var2) + (32 / var3) equals 66.0
(b) var1 – ((6 ** 4) * (var2 ** 3)) equals -34991990
19. For each of the following expressions, indicate where operator associativity of Python is used to
resolve ambiguity in the evaluation of each expression.
(a) var1 * var2 * var3 – var4
(b) var1 * var2 / var3
(c) var1 ** var2 ** var3
ANSWERS:
(a) var1 * var2 * var3 (left-to-right)
(b) var1 * var2 / var3 (left-to-right)
(c) var1 ** var2 ** var3 (right-to-left)
20. Using the built-in type conversion function float(), alter the following arithmetic expressions
so that each arithmetic operation is performed with floating-point accuracy, with the overall
expression evaluating to evaluates to a floating-point result. Assume that each of var1, var2 and
var3 are assigned integer values. Use the minimum number of calls to function float() needed
to produce the results.
(a) var1 + var2 * var3
(b) var1 // var2 + var3
(c) var1 // var2 / var3
ANSWERS:
(a) var1 + float(var2) * var3
(b) float(var1) // var2 + var3
(c) float(var1) // var2 / var3
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
10
SOLUTIONS TO PYTHON PROGRAMMING EXERCISES
P1. Write a Python program that prompts the user for two integer values and displays the result of the
first number divided by the second, with exactly two decimal places displayed.
num1 = int(input('Enter first integer: '))
num2 = int(input('Enter second integer: '))
print(format(num1 / num2, '.2f'))
P2. Write a Python program that prompts the user for two floating-point values and displays the result
of the first number divided by the second, with exactly six decimal places displayed.
num1 = float(input('Enter first floating-point value: '))
num2 = float(input('Enter second floating-point value: '))
print(format(num1 / num2, '.6f'))
P3. Write a Python program that prompts the user for two floating-point values and displays the result
of the first number divided by the second, with exactly six decimal places displayed in scientific
notation.
num1 = float(input('Enter first floating-point value: '))
num2 = float(input('Enter second floating-point value: '))
print(format(num1 / num2, '.6e'))
P4. Write a Python program that prompts the user to enter an upper or lower case letter and displays
the corresponding Unicode encoding.
letter = input('Enter a lower or upper case letter: ')
print('The Unicode value for the letter', letter, 'is', ord(letter))
P5. Write a Python program that allows the user to enter two integer values, and displays the results
when each of the following arithmetic operators are applied. For example, if the user enters the
values 7 and 5, the output would be,
7 + 5 = 12
7– 5=2
7 * 5 = 35
7 / 5 = 1.40
7 // 5 = 1
7%5=2
7 ** 5 = 16,807
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print("num1
print("num1
print("num1
print("num1
',.2f'))
print("num1
print("num1
print("num1
','))
+
*
/
num2
num2
num2
num2
=",
=",
=",
=",
num1 + num2)
num1 - num2)
format(num1 * num2, ','))
format(num1 / num2,
// num2 =", num1 // num2)
% num2 =", num1 % num2)
** num2 =", format(num1 ** num2,
All floating-point results should be displayed with two decimal places of accuracy. In addition, all
values should be displayed with commas where appropriate.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
11
SOLUTIONS TO PROGRAM MODIFICATION PROBLEMS
M1. Restaurant Tab Calculation Program: User-Entered Tax Rate
Modify the Restaurant Tab Calculation program of section 2.2.5 so that, instead of the restaurant
tax being hard coded in the program, the tax rate is entered by the user.
# Restaurant Tab Calculation Program
# This program will calculate a restaurant tab with a gift certificate
# MODIFICATION: User-entered tax rate
# program greeting
print('This program will calculate a restaurant tab for a couple with')
print('a gift certificate, for a provided restaurant tax.\n')
# get restaurant tax rate
tax = float(input('Enter restaurant tax rate (integer): '))
tax = tax / 100
# get amount of gift certificate
amt_certificate = float(input('Enter amount of the gift certificate: '))
# cost of ordered items
print('Enter ordered items for person 1')
appetizer_per1 = float(input('Appetizier: '))
entree_per1 = float(input('Entree: '))
drinks_per1 = float(input('Drinks: '))
dessert_per1 = float(input('Dessert: '))
print('\nEnter ordered items for person 2')
appetizer_per2 = float(input('Appetizier: '))
entree_per2 = float(input('Entree: '))
drinks_per2 = float(input('Drinks: '))
dessert_per2 = float(input('Dessert: '))
# total items
amt_person1 = appetizer_per1 + entree_per1 + drinks_per1 + dessert_per1
amt_person2 = appetizer_per2 + entree_per2 + drinks_per2 + dessert_per2
# compute tab with tax
items_cost = amt_person1 + amt_person2
tab = items_cost + items_cost * tax
# display amount owe
print('\nOrdered items: $', format(items_cost, '.2f'))
print('Restaurant tax: $', format(items_cost * tax, '.2f'))
print('Tab: $', format(tab - amt_certificate, '.2f'))
print('(negative amount indicates unused amount of gift certificate)')
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
12
This program will calculate a restaurant tab for a couple with
a gift certificate, for a provided restaurant tax.
Enter restaurant tax rate (integer): 6
Enter amount of the gift certificate: 100
Enter ordered items for person 1
Appetizier: 5.00
Entree: 15.99
Drinks: 8.50
Dessert: 5.50
Enter ordered items for person 2
Appetizier: 4.50
Entree: 17.99
Drinks: 11.50
Dessert: 4.50
Ordered items: $ 73.48
Restaurant tax: $ 4.41
Tab: $ -22.11
(negative amount indicates unused amount of gift certificate)
>>>
M2. Restaurant Tab Calculation Program: Breakdown of Cost of Drinks and Dessert
Modify the Restaurant Tab Calculation program of section 2.2.5 so that, in addition to displaying
the total of the items ordered, it also displays the total amount spent on drinks and dessert, as well
as the percentage of the total cost of the meal (before tax) that these items comprise. Display the
monetary amount rounded to two decimal places.
# Restaurant Tab Calculation Program
# This program will calculate a restaurant tab with a gift certificate
# MODIFICATION: Subtotaled drinks and dessert
# initialization
tax = 0.08
# program greeting
print('This program will calculate a restaurant tab for a couple with')
print('a gift certificate, with a restaurant tax of', tax * 100, '%\n')
# get amount of gift certificate
amt_certificate = float(input('Enter amount of the gift certificate: '))
# cost of ordered items
print('Enter ordered items for person 1')
appetizer_per1 = float(input('Appetizier: '))
entree_per1 = float(input('Entree: '))
drinks_per1 = float(input('Drinks: '))
dessert_per1 = float(input('Dessert: '))
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
13
print('\nEnter ordered items for person 2')
appetizer_per2 = float(input('Appetizier: '))
entree_per2 = float(input('Entree: '))
drinks_per2 = float(input('Drinks: '))
dessert_per2 = float(input('Dessert: '))
# total items
amt_person1_meal = appetizer_per1
amt_person1_other = drinks_per1 +
amt_person2_meal = appetizer_per2
amt_person2_other = drinks_per2 +
+ entree_per1
dessert_per1
+ entree_per2
dessert_per2
# compute tab with tax
items_cost = amt_person1_meal + amt_person1_other + \
amt_person2_meal + amt_person2_other
tab = items_cost + items_cost * tax
# display amount owe
print('\nOrdered items: $', format(items_cost, '.2f'))
print('(incl $', format(amt_person1_other + amt_person2_other, '.2f'),
'for drinks and dessert,',
(amt_person1_other + amt_person2_other) * 100 // items_cost,
'% of the total tab)\n')
print('Restaurant tax: $', format(items_cost * tax, '.2f'))
print('Tab: $', format(tab - amt_certificate, '.2f'))
print('(negative amount indicates unused amount of gift certificate)')
This program will calculate a restaurant tab for a couple with
a gift certificate, with a restaurant tax of 8.0 %
Enter amount of the gift certificate: 100
Enter ordered items for person 1
Appetizier: 5.50
Entree: 15.99
Drinks: 6.50
Dessert: 6.50
Enter ordered items for person 2
Appetizier: 7.50
Entree: 18.99
Drinks: 12.50
Dessert: 4.50
Ordered items: $ 77.98
(incl $ 30.00 for drinks and dessert, 38.0 % of the total tab)
Restaurant tax: $ 6.24
Tab: $ -15.78
(negative amount indicates unused amount of gift certificate)
>>>
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
14
M3. Your Place in the Universe Program: Modified for Units of Kilograms
Modify the Your Place in the Universe program in section 2.3.3 for international users, so that the
user enters their weight in kilograms, and not in pounds.
# Your Place in the Universe Program
# This program will determine the approximate number of atoms that a person is
# person consists of and the percent of the universe that they comprise
# MODIFICATION: User-entered kilograms rather than pounds.
# Initialization
num_atoms_universe = 10e80
weight_avg_person = 70 # 70 kg (154 lbs)
num_atoms_avg_person = 7e27
# Program greeting
print('This program will determine your place in the universe.')
# Prompt for user's weight
weight_kg = int(input('Enter your weight in kilograms: '))
# Convert weight to kilograms
weight_kg = 2.2 * weight_lbs
(REMOVED)
(REMOVED)
# Determine number atoms and percentage of universe
num_atoms = (weight_kg / weight_avg_person) * num_atoms_avg_person
percent_of_universe = (num_atoms / num_atoms_universe) * 100
# Display results
print('You contain approximately', format(num_atoms, '.2e'), 'atoms')
print('Therefore, you comprise', format(percent_of_universe, '.2e'), '% of the
universe')
This program will determine your place in the universe.
Enter your weight in kilograms: 70
You contain approximately 7.00e+27 atoms
Therefore, you comprise 7.00e-52 % of the universe
>>>
M4. Temperature Conversion Program: Modified for Conversion of Celsuis to Fahrenheit
Modify the Temperature Conversion program in section 2.4.6 to convert from Celsius to Fahrenheit
instead. The formula for the conversion is f = (c * 9/5) + 32.
#
#
#
#
Temperature Conversion Program (Celsius to Fahrenheit)
This program will convert a temperature entered in Celsius
to the equivalent degrees in Fahrenheit
MODIFICATION: Opposite conversion (Celsius to Fahrenheit)
# program greeting
print('This program will convert degrees Celsius to degrees Fahrenheit')
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
15
# get temperature in Celsius
celsius = float(input('Enter degrees Celsius: '))
# calc degrees Fahrenheit
fahrenheit = (celsius * 9 / 5) + 32
# output degrees Fahrenheit
print(celsius, 'degrees Celsius equals',
format(fahrenheit, '.1f'), 'degrees Fahrenheit')
This program will convert degrees Celsius to degrees Fahrenheit
Enter degrees Celsius: 100
100.0 degrees Celsius equals 212.0 degrees Fahrenheit
>>>
M5. Age in Seconds Program: Modification of Estimated Age
Modify the Age in Seconds program so that it displays the estimated age in number of days, hours,
and minutes.
import datetime
#
#
#
#
Age in Seconds Program
This program will calculate a person's approximate age in months, days and
seconds.
MODIFICATION: Displays age in days, hours and minutes rather than in years.
# Program Greeting
print ('This program computes the approximate age in days, hours and minutes')
print ('of an individual based on a provided date of birth. Only ages for')
print ('dates of birth from 1900 and after can be computed\n')
# get month, day, year of birth
month_birth = int(input('Enter month born (1-12): '))
day_birth = int(input ('Enter day born (1-31): '))
year_birth = int(input('Enter year born: (4-digit)'))
# get current month, day, year
current_month = datetime.date.today().month
current_day = datetime.date.today().day
current_year = datetime.date.today().year
# determine number of seconds in a day, average month and average year
numsecs_day = 24 * 60 * 60
numsecs_year = 365 * numsecs_day
avg_numsecs_year = ((4 * numsecs_year) + numsecs_day) // 4
avg_numsecs_month = avg_numsecs_year // 12
# calculate approximate age in seconds
numsecs_1900_dob = (year_birth - 1900) * avg_numsecs_year + \
(month_birth - 1) * avg_numsecs_month + \
(day_birth * numsecs_day)
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
16
numsecs_1900_today = (current_year
(current_month
(current_day *
age_in_secs = numsecs_1900_today -
- 1900) * avg_numsecs_year + \
- 1) * avg_numsecs_month + \
numsecs_day)
numsecs_1900_dob
# convert age in seconds to months, days and minutes
num_months = age_in_secs // avg_numsecs_month
age_in_secs = age_in_secs % avg_numsecs_month
num_days = age_in_secs // numsecs_day
age_in_secs = age_in_secs % numsecs_day
num_minutes = age_in_secs // 60
# output results
print ('\nYou are approximately', num_months, 'months,',
num_days, 'days, and', num_minutes, 'minutes old')
This program computes the approximate age in days, hours and minutes
of an individual based on a provided date of birth. Only ages for
dates of birth from 1900 and after can be computed
Enter month born (1-12): 4
Enter day born (1-31): 12
Enter year born: (4-digit)1992
You are approximately 253 months, 20 days, and 630 minutes old
>>>
M6. Age in Seconds Program: Determination of Age Differences in Seconds
Modify the Age in Seconds program so that it determines the difference in age in seconds of two
friends.
import datetime
# Age in Seconds Program
# This program will display the approximate difference in age in seconds
# two people.
# MODIFICATION: Displays difference in two person's age.
# Program Greeting
print('This program computes the approximate difference in age in seconds of
two persons\n')
# get month, day, year of birth of first person
print('First person ...')
month_birth_1 = int(input('Enter month born (1-12): '))
day_birth_1 = int(input ('Enter day born (1-31): '))
year_birth_1 = int(input('Enter year born: (4-digit)'))
# get month, day, year of birth of second person
print('\nSecond person ...')
month_birth_2 = int(input('Enter month born (1-12): '))
day_birth_2 = int(input ('Enter day born (1-31): '))
year_birth_2 = int(input('Enter year born: (4-digit)'))
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
17
# get current month, day, year
current_month = datetime.date.today().month
current_day = datetime.date.today().day
current_year = datetime.date.today().year
# determine number of seconds in a day, average month and average year
numsecs_day = 24 * 60 * 60
numsecs_year = 365 * numsecs_day
avg_numsecs_year = ((4 * numsecs_year) + numsecs_day) // 4
avg_numsecs_month = avg_numsecs_year // 12
# calculate the number of seconds from Jan 1, 1900 to today
numsecs_1900_today = (current_year - 1900) * avg_numsecs_year + \
(current_month - 1) * avg_numsecs_month + \
(current_day * numsecs_day)
# calculate approximate age in seconds of person 1
numsecs_1900_dob = (year_birth_1 - 1900) * avg_numsecs_year + \
(month_birth_1 - 1) * avg_numsecs_month + \
(day_birth_1 * numsecs_day)
age_in_secs_1 = numsecs_1900_today - numsecs_1900_dob
# calculate approximate age in seconds of person 2
numsecs_1900_dob = (year_birth_2 - 1900) * avg_numsecs_year + \
(month_birth_2 - 1) * avg_numsecs_month + \
(day_birth_2 * numsecs_day)
age_in_secs_2 = numsecs_1900_today - numsecs_1900_dob
# output results
print ('\nThe two individuals are approximately',
abs(age_in_secs_1 - age_in_secs_2), 'seconds apart in age.')
This program computes the approximate age in days, hours and minutes
of an individual based on a provided date of birth. Only ages for
dates of birth from 1900 and after can be computed
Enter month born (1-12): 4
Enter day born (1-31): 12
Enter year born: (4-digit)1992
You are approximately 253 months, 20 days, and 630 minutes old
>>>
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
18
SOLUTIONS TO PROGRAM DEVELOPMENT PROBLEMS
D1. Losing Your Head over Chess
The game of chess is generally believed to have been invented in India in the sixth century for a
ruling king by one of his subjects. The king was supposedly very delighted with the game and asked
the subject what he wanted in return. The subject, being clever, asked for one grain of wheat on
the first square, two grains of wheat on the second square, four grains of wheat on the third
square, and so forth, doubling the amount on each next square. The king thought that this was a
modest reward for such an invention. However, the total amount of wheat would have been more
than 1,000 times the current world production. When the king realized that he could not fulfill his
promise, he had the inventor’s head cut off. Develop and test a Python program that calculates
how much wheat this would be in pounds, using the fact that a grain of wheat weighs
approximately 1/7,000 of a pound.
# This program will calculate the total weight of the number of grains of
# wheat it takes to cover a chess board,starting with one grain, and placing
# double the number of grains on each successive square of the board.
# init
weight_single_grain = 1 / 7000
# in pounds
# calculate total number of grains
num_grains_row1 = (2 ** 0) + (2 ** 1) + (2 ** 2) + (2 ** 3) + \
(2 ** 4) + (2 ** 5) + (2 ** 6) + (2 ** 7)
num_grains_row2 = (2 ** 8) + (2 ** 9) + (2 ** 10) + (2 ** 11) + \
(2 ** 12) + (2 ** 13) + (2 ** 14) + (2 ** 15)
num_grains_row3 = (2 ** 16) + (2 ** 17) + (2 ** 18) + (2 ** 19) + \
(2 ** 20) + (2 ** 21) + (2 ** 22) + (2 ** 23)
num_grains_row4 = (2 ** 24) + (2 ** 25) + (2 ** 26) + (2 ** 27) + \
(2 ** 28) + (2 ** 29) + (2 ** 30) + (2 ** 31)
num_grains_row5 = (2 ** 32) + (2 ** 33) + (2 ** 34) + (2 ** 35) + \
(2 ** 36) + (2 ** 37) + (2 ** 38) + (2 ** 39)
num_grains_row6 = (2 ** 40) + (2 ** 41) + (2 ** 42) + (2 ** 43) + \
(2 ** 44) + (2 ** 45) + (2 ** 46) + (2 ** 47)
num_grains_row7 = (2 ** 48) + (2 ** 49) + (2 ** 50) + (2 ** 51) + \
(2 ** 52) + (2 ** 53) + (2 ** 54) + (2 ** 55)
num_grains_row8 = (2 ** 56) + (2 ** 57) + (2 ** 58) + (2 ** 59) + \
(2 ** 60) + (2 ** 61) + (2 ** 62) + (2 ** 63)
total_num_grains = num_grains_row1 + num_grains_row2 + num_grains_row3 + \
num_grains_row4 + num_grains_row5 + num_grains_row6 + \
num_grains_row7 + num_grains_row8
# calculate total weight
total_weight = total_num_grains * weight_single_grain
# display results
print('The total weight (lbs.) is', format(total_weight, ',.2f'))
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
19
The total weight (lbs.) is 2,635,249,153,387,079.00
>>>
PEDAGOGICAL NOTE: At this point, iteration has not yet been introduced. Therefore,
their solution is expected to be done as a straight-line program. Thus, programs such as
this that provide a natural use of loops will help students appreciate the use of
interation when they encounter it (specifically the while loop in Chapter 3).
D2. All That Talking
Develop and test a Python program that determines how much time it would take to download all
instances of every word ever spoken. Assume the size of this information as given in Figure 2-1. The
download speed is to be entered by the user in million of bits per second (mbps). To find your
actual connection speed, go to the following website (from Intel Corporation) or similar site,
www.intel.com/content/www/us/en/gamers/broadband-speed-test.html
Because connection speeds can vary, run this connection speed test three times. Take the average
of three results, and use that as the connection speed to enter into your program. Finally,
determine what is an appropriate unit of time to express your program results in: minutes? hours?
days? other?
# This program will determine how much time it would take to download all
# instances of every word ever spoken for a given download connection speed,
# based on the approximated value of 5 EB (Exabytes) to store all the words.
# init
size_allwords_spoken = 10**18
numsecs_year = 60 * 60 * 24 * 365
# exabytes
# secs * minutes * hours * days
# program greeting
print('This program will determine the amount of time it would take to')
print('download all the words ever spoken for a given connection speed.\n')
# get download connection speed
download_speed = float(input('What is your connection speed (mbps)? '))
# calculate time to download
size_allwords_spoken = size_allwords_spoken * 8 # convert to num bits
secs_to_download = size_allwords_spoken / download_speed
# convert to number of days
years_to_download = int(secs_to_download / numsecs_year)
# display results
print('The total time to download all words ever spoken for')
print('your connection speed is approximately',
format(years_to_download, ',d'), 'years')
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
20
This program will determine the amount of time it would take to
download all the words ever spoken for a given connection speed.
What is your connection speed (mbps)? 6
The total time to download all words ever spoken for
your connection speed is approximately 42,279,722,645 years
>>>
D3. Pictures on the Go
Develop and test a Python program that determines how many images can be stored on a given
size USB (flash) drive. The size of the USB drive is to be entered by the user in gigabytes (GB). The
number of images that can be stored must be calculated for GIF, JPEG, PNG, and TIFF image file
formats. The program output should be formatted as given below.
Enter
xxxxx
xxxxx
xxxxx
xxxxx
USB size (GB): 4
images in GIF format can be stored
images in JPEG format can be stored
images in PNG format can be stored
images in TIFF format can be stored
The ultimate file size of a given image depends not only on the image format used, but also on the
image itself. In addition, formats such as JPEG allow the user to select the degree of compression
for the image quality desired. For this program, we assume the image compression ratios given
below. Also assume that all the images have a resolution of 800 x 600 pixels.
Thus, for example, a 800 x 600 resolution image with 16-bit (2 bytes) color depth would have a
total number of bytes of 800 x 600 x 2 = 960,000. For a compression rate of 25:1, the total number
of bytes needed to store the image would be 960000/25 = 38400.
Finally, assume that a GB (gigabyte) equals 1,000,000,000 bytes, as given in Figure 2.1.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
21
Note that a “lossless” compression is one in which no information is lost. A “lossy” compression
does lose some of the original information.
# Pictures on the Go
#
#
#
#
#
This program will estimate how many images can
USB drive for image formats GIF, JPEG, PNG and
images have a resolution of 800x600 pixels. In
assumed are 5:1 (GIF), 25:1 (JPEG), 8:1 (PNG).
utilize compression.
be stored on a given size
TIFF. It is assumed that all
addition, the compression
He TIFF image format does not
# init
num_pixels = 800 * 600
# get USB size
USB_size = int(input('Enter USB size (GB): '))
USB_size = USB_size * (10 ** 9)
# num GIF images
color_depth = 1 # bytes
compression_ratio = 5
GIF_size = (num_pixels * color_depth) // compression_ratio
# num JPEG images
color_depth = 3 # bytes
compression_ratio = 25
JPEG_size = (num_pixels * color_depth) // compression_ratio
# num PNG images
color_depth = 3 # bytes
compression_ratio = 8
PNG_size = (num_pixels * color_depth) // compression_ratio
# num TIFF images (compressionless format)
color_depth = 6 # bytes
TIFF_size = num_pixels * color_depth
# display results
print()
print(format(USB_size
print(format(USB_size
print(format(USB_size
print(format(USB_size
//
//
//
//
GIF_size, ',d'), 'GIF format images can be stored')
JPEG_size, ',d'), 'JPEG format images can be stored')
PNG_size, ',d'), 'PNG format images can be stored')
TIFF_size, ',d'), 'TIFF format images can be stored')
Enter USB size (GB): 32
333,333 GIF format images can be stored
555,555 JPEG format images can be stored
177,777 PNG format images can be stored
11,111 TIFF format images can be stored
>>>
D4. Life Signs (omitted)
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
22