Chapter 1 Solutions *

 

 

 

Checkpoint 1.1 

A program is a(n) ________ that a computer follows to perform a task.

a. user interface

b. operating system

c. set of instructions

d. programming language

Answer: c

 

 

 

Checkpoint 1.2 

What term refers to the physical devices, or components, of which a computer is made?

a. hardware

b. software

c. input

d. output

Answer: a

 

 

Checkpoint 1.3 

What part of the computer actually runs programs?

a. main memory

b. the CPU

c. secondary memory

d. I/O devices

Answer : b

 

 

Checkpoint 1.4 

What part of the computer serves as a work area to store a program and its data while the program is running?

a. I/O devices

b. secondary memory

c. main memory

d. the CPU

Answer : c

 

 

 

Checkpoint 1.5 

What part of the computer holds data for long periods of time, even when there is no power to the computer?

a. I/O devices

b. main memory

c. the CPU

d. secondary storage

Answer : d

 

 

Checkpoint 1.6 

What part of the computer collects data from people and from other devices?

a. input device

b. output device

c. CPU

d. RAM

Answer: a

 

 

 

Checkpoint 1.7 

What part of the computer formats and presents data for people or other devices?

a. input device

b. output device

c. CPU

d. RAM

Answer: b

 

 

 

Checkpoint 1.8 

What fundamental set of programs control the internal operations of the computers hardware?

a. file system

b. backup program

c. application interface

d. operating system

Answer: d

 

 

 

Checkpoint 1.9 

What do you call a program that performs a specialized task, such as a virus scanner, a file compression program, or a data backup program?

a. utility program

b. application software

c. operating system

d. central processor

Answer: a

 

 

Checkpoint 1.10 

Word processing programs, spreadsheet programs, email programs, web browsers, and game programs belong to what category of software?

a. utility program

b. application software

c. operating system

d. central processor

Answer: b

 

 

 

Quiz 1.2 (Scored)

 

Question 1

Monitors, printers, status lights are all examples of _______ devices.

a.  output

b.  input

c.  both input and output

d.  neither input nor output

Answer: a

 

 

 

Question 2

When a program runs on a computer, the part of the computer that carries out the instructions is called the ___

a. RAM

b. GPU

c. ROM

d. CPU

Answer: d

 

 

 

Question 3

When a program runs on a computer, it is stored in _____

a. ROM

b. RAM

c. GPU

d. CPU

Answer: b

 

Checkpoint 1.11 

The amount of memory enough to store a letter of the alphabet or a small number is one bit.

a. True

b. False

Answer: False

 

 

 

Checkpoint 1.12 

A tiny “switchthat can be set to either on or off is called a _________.

a. bit

b. byte

c. nibble

d. frame

Answer: a

 

 

Checkpoint 1.13 

The binary numbering system are all numeric values written as sequences of 0s and 1s.

a. True

b. False

Answer: True

 

 

Checkpoint 1.14 

ASCII is an encoding scheme that uses a set of __________ to store characters in a computer’s memory.

a. 128 character codes

b. 128 numeric codes

c. 256 numeric codes

d. 256 character codes

Answer: b

 

 

Checkpoint 1.15 

What encoding scheme is extensive enough to represent the characters of many of the languages in the world?

a. Universal

b. Hexadecimal

c. ASCII

d. Unicode

Answer: d

 

Checkpoint 1.16 

Any data that is stored in binary is known as analog data.

a. True

b. False

Answer: False

 

 

 

Quiz 1.3 (Scored)

 

Question 1

A bit is

a. an alternative term for byte.

b. a small amount of data.

c. an electronic device used in computers.

d. a binary digit, like 0 or 1.

Answer: d

 

 

 

Question 2

A byte is made up of ___________ bits.

2

8

16

32

ANSWER:  8

 

 

 

Question 3

A binary digit

a. requires one byte of storage.

b. is none of the above.

c. is zero or one.

d. is either positive or negative.

e. is 2.

Answer: c

 

 

 

Checkpoint 1.17 

A CPU understands instructions that are written only in _________.

a. object code

b. program code

c. hex language

d. machine language

Answer: d

 

 

Checkpoint 1.18  

A program has to be copied into what type of memory each time the CPU executes it?

a. RAM

b. ROM

c. BUS

d. DISC

Answer: a

 

 

Checkpoint 1.19 

When a CPU executes the instructions in a program, it is engaged in what process?

a. code switching

b. fetch-decode-execute cycle

c. in-out processing

d. device communication

Answer: b

 

 

Checkpoint 1.20 

What format uses short words that are known as mnemonics?

a. hexadecimal format

b. binary format

c. assembly language

d. high-level language

Answer: c

 

 

Checkpoint 1.21 

A high-level programming language allows you to create powerful and complex programs without knowing how the CPU works.

a. True

b. False

Answer: True

 

Checkpoint 1.22 

Each language has a set of rules that must be strictly followed when writing a program. What is this set of rules called?

a. grammar

b. protocols

c. semantics

d. syntax

Answer: d

 

 

Checkpoint 1.23 

What type of program translates a high-level language program into a separate machine language program?

a. compiler

b. router

c. analyzer

d. processor

Answer: a

 

 

 

Checkpoint 1.24 

A mistake that is usually caused by a misspelled key word, a missing punctuation character, or the incorrect use of an operator is called a logical error.

a. True

b. False

Answer: False

 

 

 

Quiz 1.4 (Socred)

 

Question 1

Which statement is not true:

a. Machine languages can be used to express algorithms.

b. Machine language is produced by compilers.

c. Machine language consists of zeros and ones.   

d. Machine languages can be used to write programs that can run on any machine.

Answer: d

 

 

 

Question 2

A(n) _____________ is a program that both translates and executes the instructions in a program.

a. compiler

b. linker

c. editor

d. interpreter

Answer: d

 

 

 

Question 3

A compiler

a. translates executable code to machine code

b. maintains a collection of programs

c. tests a program's logic

d. translates source code into executable machine language code

Answer: d

 

 

 

Question 4

The code that a programmer writes is called _____ code.

a. exe

b. source

c. machine

d. object

Answer: b

 

 

 

Question 5

The rules that govern the correct order and usage of the elements of a language are called the ______ of the language.

a. syntax

b. lexicon

c. form

d. method

Answer: a

 

 

 

Question 6

Words that have a special meaning in a programming language are called _____.

a. format words

b. special words

c. programming words

d. key words

Answer: d

 

 

Live Code Example 1.1

Type the following statement in the interface shown below.

print('Python programming is fun!')

 

Answer:

 

 

Live Code Example 1.2

Type the following statement in the interface shown below.

print('To be or not to be')

 

Answer:

print('To be or not to be')

 

 

Checkpoint 1.25 

The program that can read Python programming statements and execute them is called a Python _________.

a. analyzer

b. router

c. interpreter

d. processor

Answer: c

 

 

Checkpoint 1.26  

When programming in _________ mode, the interpreter waits for you to type a Python statement on the keyboard and then executes it.

a. user

b. batch

c. interactive

d. script

Answer: c

 

 

Checkpoint 1.27  

When programming in _________ mode, the interpreter reads the contents of a file that contains Python statements and executes each statement as it reads it.

a. user

b. batch

c. interactive

d. script

Answer: d

 

 

Checkpoint 1.28

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

 

Chapter 2 Solutions

 

 

 

Checkpoint 2.1

Any person, group, or organization that is asking you to write a program is known as a _________.

a. user interface

b. systems administrator

c. domain controller

d. programmer’s customer

Answer: d

 

 

 

Checkpoint 2.2

A single function that the program must perform in order to satisfy a customer is known as a protocol.

a. True

b. False

Answer: False

 

 

Checkpoint 2.3

A set of well-defined logical steps that must be taken to perform a task is called a(n) _________.

a. policy

b. algorithm

c. matrix

d. solution

Answer: b

 

 

Checkpoint 2.4

What is an informal language that is used to create “mock-ups” of programs?

a. script

b. policy

c. pseudocode

d. interface

Answer: c

 

 

Checkpoint 2.5

A diagram that graphically depicts the steps that take place in a program is called a factorization.

a. True

b. False

Answer: False

 

 

Checkpoint 2.6

In a flowchart, _________ are terminal symbols.

a. ovals

b. parallelograms

c. rectangles

d. triangles

Answer: a

 

 

 

Checkpoint 2.7

In a flowchart, _________ are either output or input.

a. ovals

b. parallelograms

c. rectangles

d. triangles

Answer: b

 

 

Checkpoint 2.8

In a flowchart, _________ are processing symbols.

a. ovals

b. parallelograms

c. rectangles

d. triangles

Answer: c

 

 

 

Checkpoint 2.9

Any data that the program receives while it is running is known as _________.

a. translation

b. compilation

c. output

d. input

Answer: d

 

 

Checkpoint 2.10

The results of a(n) ________ are sent out of a program as output.

a. operating system

b. CPU state

c. executing process

d. memory module

Answer: c

 

 

 

Checkpoint 2.11

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 2.12

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 2.13

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

 

Quiz 2.3 (Scored)

 

Question 1

Which of the following statements displays this output:

 

one two three

 

a.       print('one two three')

b.      print("one two three")

c.       print('''one two three''')

d.      All of the above

 

ANSWER:

d)        All of the above

 

 

 

 

Checkpoint 2.14

Comments are intended for any person reading a program’s code, not the computer.

a. True

b. False

Answer: True

 

Checkpoint 2.15

What component of a program references a value in the computer's memory?

a. syntax

b. header

c. variable

d. package

Answer: c

 

 

Checkpoint 2.16

What is an illegal variable name in Python?

a. x

b. july_2019

c. theSalesFigureForFiscalYear

d. r&d

Answer: d

 

 

 

Checkpoint 2.17

The variable name Sales is considered to be the same as sales in Python.

a. True

b. False

Answer: False

 

 

Checkpoint 2.18

The following assignment statement is valid:

72 = amount

a. True

b. False

Answer: False

 

 

Checkpoint 2.19

What will the following code display?

val = 99

print('The value is', 'val')

a. The value is ‘99’

b. The value is ‘val’

c. The value is 99

d. The value is val

Answer: d

 

 

Checkpoint 2.20

After the statements below execute, what is the Python data type of the values referenced by each variable?

value1 = 99

value2 = 7

a. int

b. float

c. char

d. str

Answer: a

 

 

 

Checkpoint 2.21

After the statements below execute, what is the Python data type of the values referenced by each variable?

value1 = 45.9

value2 = 7.0

a. int

b. float

c. char

d. str

Answer: b

 

 

Checkpoint 2.22

After the statements below execute, what is the Python data type of the value referenced by the variable?

value1 = 'abc'

a. int

b. float

c. char

d. str

Answer: d

 

 

Checkpoint 2.23

What will be displayed by the following program?

my_value = 99

my_value = 0

print(my_value)

a. 0

b. 99

c. my_value

d. my_value = 0

Answer: a

 

 

 

Quiz 2.5 (Scored)

 

Question 1

Assign 7 to a variable named seven.

Answer:

seven = 7

 

 

 

Question 2

Assign 8 to a variable named eight.

Answer:

eight = 8

 

 

 

Question 3

Write two assignment statements. The first should  assign 3.5 to a variable named length, and the second should assign 1.55 to a variable named width.

Answer:

length = 3.5
width = 1.55

 

 

 

Question 4

Which of the following names in a program is equivalent to the name int?

Answer:

Neither

 

 

 

Question 5

Which of the following is NOT a legal identifier?

Answer:

7thheaven

 

 

 

Question 6

Which is the best identifier for a variable to represent the amount of money your boss pays you each month?

Answer:

monthlyPay

 

 

 

Question 7

Given a variable count, which contains an integer value, write a statement that writes the value of count to standard output.

Answer:

print(count)

 

 

 

Checkpoint 2.24

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

 

Checkpoint 2.25

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

 

Quiz 2.6 (Scored)

 

Question 1

Write code that performs the following input operations:

 

·         Read an int from the keyboard and assign it to a variable named k. (Do not print a prompt. Use the input() function without a prompt-string to read the input.)

·         Read a float from the keyboard and assign it to a variable named d. (Do not print a prompt. Use the input() function without a prompt-stringto read the input.)

·         Read a string from the keyboard and assign it to a variable named s. (Do not print a prompt. Use the input() function without a prompt-string to read the input.)

 

After you have performed the input, on one line, print these variables in reverse order (s followed by d, followed by k) with exactly one space in between each. On a second line, print them in the original order (k followed by d, followed by s) with one space in between them.

Answer 1:

k = int(input())
d = float(input())
s = input()
print(s, d, k)
print(k, d, s)


 

 

 

Checkpoint 2.26

What is the value of the following expression?

6 + 3 * 5

a. 14

b. 21

c. 45

d. 90

Answer: b

 

 

Checkpoint 2.27

What is the value of the following expression?

12 / 2 – 4

a.  -6

b. 2

c. 4

d. 6

Answer: b

 

 

Checkpoint 2.28

What is the value of the following expression?

9 + 14 * 2 – 6

a. 29

b. 31

c. 33

d. 40

Answer: b

 

 

Checkpoint 2.29

What is the value of the following expression?

(6 + 2) * 3

a. 12

b. 20

c. 24

d. 36

Answer: c

 

 

Checkpoint 2.30

What is the value of the following expression?

14 / (11 − 4)

a. -3

b. -2

c. 10/11

d. 2

Answer: d

 

 

Checkpoint 2.31

What is the value of the following expression?

9 + 12 * (8 − 3)

a. 26

b. 69

c. 105

d. 165

Answer: b



 

Checkpoint 2.32

What value will be assigned to result after the following statement executes?

result = 9 // 2

a. 4

b. 4.5

c. 5

Answer: a

 

 

Checkpoint 2.33

What value will be assigned to result after the following statement executes?

result = 9 % 2

a. 1

b. 2

c. 4

d. 5

Answer: a

 

 

 

Checkpoint 2.34

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

 

Quiz 2.7 (Scored)

 

Question 1

A wall has been built with two pieces of sheetrock, a smaller one and a larger one. The length of the smaller one is stored in the variable small. Similarly, the length of the larger one is stored in the variable large. Write a single expression whose value is the length of this wall.

 

Note: Simply write the math expression. Do not assign the value of the expression to a variable.

Answer:

large + small

 

 

Question 2

Write an expression that computes the difference of the variables ending_time and starting_time.

 

Note: Simply write the math expression. Do not assign the value of the expression to a variable.

Answer:

ending_time - starting_time

 

 

 

Question 3

Given the variables full_admission_price and discount_amount (already defined), write a math expression that gives the price of a discount admission.

 

Note: Simply write the math expression. Do not assign the value of the expression to a variable.

 

Answer:

full_admission_price - discount_amount

 

 

 

Question 4

Given the variable price_per_case, write a math expression that gives the price of a dozen cases.

 

Note: Simply write the math expression. Do not assign the value of the expression to a variable.

Answer:

price_per_case * 12

 

 

 

Question 5

Given the variables cost_of_bus_rental and max_bus_riders, write a math expression that gives the cost per rider (assuming the bus is full).

 

Note: Simply write the math expression. Do not assign the value of the expression to a variable.

Answer:

cost_of_bus_rental / max_bus_riders

 

 

 

Question 6

Write a math expression that computes the remainder of the variable principal when divided by the variable divisor. (Assume that each is refers to an int.)

 

Note: Simply write the math expression. Do not assign the value of the expression to a variable.

Answer:

principal % divisor

 

 

Question 7

Write a statement that calculates the average of 12 and 40, and assigns the result to a variable named avg.

Answer:

avg = (12 + 40) / 2

 

 

 

Question 8

Calculate the average of the variables ab, and c, and assign the result to a variable named avg. Assume that the variables ab, and c have already been assigned a value, but do not assume that the values are all floating-point. Make sure the value that you assign to avg is a floating-point value.

Answer:

avg = float(a+b+c)/3


 

 

 

Live Code Example 2.1
Complete the code below to produce this output:

Enter the value of num_1: 15
Enter the value of num_2: 4
num_1 + num_2 = 19
num_1 - num_2 = 11
num_1 * num_2 = 60
num_1 // num_2 = 3

 

num_1 = int(input('Enter the value of num_1: '))

num_2 = int(input('Enter the value of num_2: '))

#add print statements here

 

Answer:

num_1 = int(input('Enter the value of num_1: '))

num_2 = int(input('Enter the value of num_2: '))

print('num_1 + num_2 =', num_1 + num_2)

print('num_1 - num_2 =', num_1 - num_2)

print('num_1 * num_2 =', num_1 * num_2)

print('num_1 // num_2 =', num_1 // num_2)

 

#Change the values of the variables and the operands and check your results.

 

 

Live Code Example 2.2
The given code should display the result of 5 * 2.6666666 as an integer, but it is not! Correct the error.

rounded_int = 5 * 2.6666666

print rounded_int

 

Answer:

rounded_int = int (5 * 2.6666666)

print (rounded_int)

 

 

 

Live Code Example 2.3
You are on a road trip and stopped for gas. You decide to calculate your average miles per gallon (MPG) since your last gas stop. Type in the code below and fill in the missing line under the last comment to display the MPG.

 

start = float(input('Enter your starting mileage: '))

end = float(input('Enter your ending mileage: '))

gallons = float(input('Enter the gallons used: '))

 

# Calculate the average miles per gallon.

average = (end - start) / gallons

 

# Display the average to two decimal places.

 

Answer:

start = float(input('Enter your starting mileage: '))

end = float(input('Enter your ending mileage: '))

gallons = float(input('Enter the gallons used: '))

average = (end - start) / gallons

print('The miles per gallon is', format(average, '.2f'))

 

 

 

Checkpoint 2.35

If you do not want the print function to start a new line of output when it finishes displaying its output, you can pass the special argument ________ to the function.

a. sep=

b. ‘new’

c. ‘\ln’

d. end = ' '

Answer: d

 

 

 

Checkpoint 2.36

You can change the character that is automatically displayed between multiple items that are passed to the print function by passing the ________ argument with the desired character.

a. end = ' '

b. ‘new’

c. ‘\c’

d. sep=

Answer: d

 

 

Checkpoint 2.37

The newline escape character is ________.

a. ‘n’

b. ‘nl’

c. '\n'

d. ‘\nl’

Answer: c

 

 

 

Checkpoint 2.38

The + operator, when used with two strings, joins them together as one string.

a. True

b. False

Answer: True

 

 

Checkpoint 2.39

What will the statement print(format(65.4321, '.2f')) display?

a. 65.4321

b. 6543.21

c. 65.00

d. 65.43

Answer: d

 

 

Checkpoint 2.40

What will the statement print(format(987654.129, ',.2f')) display?

a. 987,654.00

b. 987654.12

c. 987,654.13

d. 987654.13

Answer: c

 

 

 

Checkpoint 2.41

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

 

 

Quiz 2.8 (Scored)

Question 1

Given two variables iVal and fVal, containing respectively an integer and a float value, write a statement that writes both of their values to standard output in the following format: i=iVal f=fVal.

For example, if iVal is assigned 5 and fVal is assigned 2.4, the statement should print the following:


i=5 f=2.4

 

Answer:

print("i=" + str(iVal), "f=" + str(fVal))

 

 

Question 2

The character escape sequence to force the cursor to go to the next line is ____.
The character escape sequence to force the cursor to advance forward to the next tab setting is ____.
The character escape sequence to represent a single quote is ____.
The character escape sequence to represent a double quote is ____.
The character escape sequence to represent a backslash is ____.

Answer:

\n
\t
\'
\"
\\

 

 

 

Checkpoint 2.42

Named constants make programs more self-explanatory.

a. True

b. False

Answer: True

 

 

Checkpoint 2.43

Named constants make widespread changes more difficult to make in a program.

a. True

b. False

Answer: False

 

 

Checkpoint 2.44

Named constants help to prevent the typographical errors that are common when using magic numbers.

a. True

b. False

Answer: True

 

 

Checkpoint 2.45

Which Python statement best defines a named constant for a 10 percent discount?

a. PERCENTAGE = 10%

b. discount percent = 10

c. dp = 0.100

d. DISCOUNT_PERCENTAGE = 0.1

Answer: d

 

 

Checkpoint 2.46

Which command will move a turtle forward?

a. turtle.walk

b. turtle.forward

c. turtle.move

d. turtle.on

Answer: b

 

 


Checkpoint 2.47

Which command will turn a turtle right by 45 degrees?

a.  turtle.right = 45

b. turtle.move(45, right)

c. turtle.right(45)

d. turtle.move(right, 45)

Answer: c

 

 


Checkpoint 2.48

To move a turtle to a new location without drawing a line, first use the _________ command to raise the turtle’s pen.

a. turtle.penup()

b. turtle.liftpen()

c. turtle.locate()

d. turtle.moveup()

Answer: a

 

 

Checkpoint 2.49

What command would you use to display a turtle’s current heading?

a. turtle.current()

b. turtle.heading()

c. turtle.locate()

d. turtle.coordinates (x, y)

Answer: b

 

 

 

Checkpoint 2.50

What command would you use to display the coordinates of the turtle’s current position?

a. turtle.coor(x, y)

b. turtle.pos()

c. turtle.locate(x, y)

d. turtle.display()

Answer: b

 

 

 

Checkpoint 2.51

Which of the following commands will make the animation speed faster?

a. turtle.speed(on)

b. turtle.speed(1)

c. turtle.speed(true) 

d. turtle.speed(10)

Answer: d

 

 

 

Checkpoint 2.52

To fill a turtle shape with a color, use the ________ command before drawing the shape, then use the ________ command after the shape is drawn.

a. turtle.begin_fill(); turtle.end_fill()

b. turtle.start_fill(); turtle.finish_fill()

c. turtle.fill(start) ; turtle.fill(finish)

d. turtle.fill(begin) ; turtle.fill(end)

Answer: a

 

 

 

Checkpoint 2.53

What command would you use to display text in the turtle’s graphics window?

a. turtle.draw()

b. turtle.window()

c. turtle.write()

d. turtle.display()

Answer: c

 

 

 

Chapter 2 Programming Project 1 (Scored)

 

A cookie recipe calls for the following ingredients:
• 1.5 cups of sugar
• 1 cup of butter
• 2.75 cups of flour
The recipe produces 48 cookies with this amount of ingredients. Write a program that asks the user how many cookies they want to make and then displays the number of cups of each ingredient needed for the specified number of cookies.

 

When the program asks the user for the number of cookies, it should display the following string as a prompt:

'Enter number of cookies:'

 

When the program displays the number of cups of ingredients, it should display a message in the following format:


You need x cups of sugar, y cups of butter, and z cups of flour.

 

Where x is the number of cups of sugar, y is the number of cups of butter, and z is the number of cups of flour. Don’t worry about formatting the numbers in the output.

The following sample run shows an example of the program's output. The user's input is shown in bold.

 

Sample Run

Enter number of cookies:48
You need 1.5 cups of sugar, 1.0 cups of butter, and 2.75 cups of flour.

 

Answer:

num_cookies = int(input('Enter number of cookies:'))

cups_sugar = 1.5 * num_cookies / 48

cups_butter = num_cookies / 48

cups_flour = 2.75 * num_cookies / 48

 

print('You need', cups_sugar, 'cups of sugar,', cups_butter, 'cups of butter, and', cups_flour, 'cups of flour.')

 

 

 

Chapter 2 Programming Project 2 (Scored)

Several litters of new pups were recently born in the otter habitat at the local zoo. Write a program that calculates the percentage of male and female otters currently in the habitat.

 

The program should ask the user for the number of males and the number of females using two separate input statements. When the program asks for the number of males, it should display the following string as a prompt:

 

'Enter number of males:'

 

When the program asks for the number of females, it should display the following string as a prompt:

 

'Enter number of females:'

 

The program should display the percentage of males and females (round to the nearest whole number) in the following format:


Percent males: 35%
Percent females: 65%


Use string formatting in your output.

 

The following sample run shows an example of the program's output. The user's input is shown in bold.

Sample Run

Enter number of males:75
Enter number of females:25

Percent males: 75%

Percent females: 25%

 

Answer:

males = int(input('Enter number of males:'))

females = int(input('Enter number of females:'))

 

total = males + females

percentMale = males / total

percentFemale = females / total

 

print('Percent males:', format(percentMale, '.0%'))

print('Percent females:', format(percentFemale, '.0%'))

 

 

Chapter 3 Solutions



Checkpoint 3.1

A logical design that controls the order in which a set of statements execute is known as a _________.

a. decision structure

b. control structure

c. process diagram

d. flow diagram

Answer: b


 

Checkpoint 3.2

A program structure that can execute a set of statements only under certain circumstances is called a _________.

a. decision structure

b. control structure

c. process diagram

d. flow diagram

Answer: a


 

Checkpoint 3.3

In a single alternative decision structure, if the condition that is being tested is __________, the program takes the alternative path.

a.      zero

b.      true

c.       incorrect

d.     false

Answer: b


 

Checkpoint 3.4

A Boolean expression can be evaluated as either true, false, or null.

a. True

b. False

Answer: False



 

 

Checkpoint 3.5

Relational operators can be used to determine whether one value is greater than, less than, greater than

or equal to, less than or equal to, equal to, or not equal to another value.

a. True

b. False

Answer: True



Checkpoint 3.6

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 3.7

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Quiz 3.1 (Scored)

Question 1

Write a Boolean expression that is True if the value of x is equal to zero.

Answer:

x == 0

 

 

 

Question 2

Write a Boolean expression that is True if the variables profits and losses are exactly equal.

Answer:

profits == losses

 

 

 

Question 3

Write an expression that evaluates to True if the value of index is greater than the value of last_index.

Answer:

index > last_index

 

 

 

Question 4

Write an expression that evaluates to True if x is greater than or equal to y.

Answer:

x >= y

 

 

 

Question 5

Write a Boolean expression that is True if x is greater than y.

Answer:

x > y

 

 

 

Question 6

Assume the variables x and y have each been assigned an int. Write a fragment of code that assigns the greater of these two variables to another variable named max.

Answer:

max = x
if y > max:
    max = y

 

 

 

Question 7

Assume the variables x, y, and z have each been assigned an integer value. Write a fragment of code that assigns the least of these three variables to another variable named min.

Answer:

min = x
if  y < min:
     min = y
if  z < min:
     min = z

 

 

 

Question 8

Write an if statement that decreases the value of shelf_life by 4 if the value of outside_temperature is greater than 90.

 

 

Answer:
if outside_temperature > 90:

    shelf_life -= 4

 

 

 

Checkpoint 3.8

A ________ decision structure has two possible paths of execution; one path is taken if a condition is true, and the other path is taken if the condition is false.

a. primary-secondary

b. looping

c. dual alternative

d. phasing

Answer: c


 

Checkpoint 3.9

What statement do you use in Python to write a dual alternative decision structure?

a. do-until

b. if-else

c.  for

d. while

Answer: b

 

 


Live Code Example 3.1

The program below calculates the price of an order of bagels based on the number of bagels purchased. Up to 12 bagels are $1.50, and any bagels purchased in addition are $0.75 cents each.

 

num_bagels = float(input('How many bagels would you like to order? '))

 

# Write the if condition

    price = num_bagels * 1.5

else:

    # Write a statement to calculate the cost for

    # an order of more than 12 bagels   

 

print('Your total is $', format(price, ',.2f'), sep='')

Answer:

num_bagels = float(input('How many bagels would you like to order? '))

 

if num_bagels <= 12:

    price = num_bagels * 1.5

else:

    price = (12 * 1.5) + ((num_bagels - 12) * .75)

 

print('Your total is $', format(price, ',.2f'), sep='')

 

 

 

Live Code Example 3.2

Correct the error in the code below.

Expected Output:
Enter the length of the cube's side: 5
The area of this cube is 125

side = int(input('Enter the length of the cube\'s side: '))

 

if side >= 0:

    print('The volume of this cube is', side * 3 )

else:

    print('Please enter a positive number')

 

Answer:

side = int(input('Enter the length of the cube\'s side: '))

 

if side >= 0:

    print('The volume of this cube is', side ** 3 )

else:

    print('Please enter a positive number')

 

 

 

Checkpoint 3.10

When you write an if-else statement, the statements that appear after the else clause execute _________.

a. until the condition is false

b. when the condition is false

c. when the condition is true

d. until the condition is  true

Answer: b

 



Quiz 3.2 (Scored)

 

Question 1

Write an if-else statement that compares the age variable with the value 65. If age is greater than or equal to 65, add 1 to senior_citizens. Otherwise, add 1 to non_seniors.

Answer:

if age >= 65:
     senior_citizens += 1
else:
     non_seniors += 1

 

 

 

Question 2

Write an if-else statement that assigns True to fever if temperature is greater than 98.6; otherwise it assigns False to fever.

Answer:

if temperature > 98.6:
     fever = True
else:
     fever = False

 

 

 

Checkpoint 3.11

What would the following code display?

if 'z' < 'a':

    print('z is less than a.')

else:

    print('z is not less than a.')

 

a. z is less than a.

b. z is not less than a.

c. “”

Answer: b

 

 

Checkpoint 3.12

What would the following code display?

 

s1 = 'New York'

s2 = 'Boston'

if s1 > s2:

    print(s2)

    print(s1)

else:

    print(s1)

    print(s2)

 

a.

Boston

New York

b.

New York

Boston

c.

New York

d.

Boston

Answer: a

 

 

 

Live Code Example 3.3

 

The code below validates the password ThisI$MyPassw0rd. Provide the if statement.

 

password = input('Enter a password: ')

# Supply an if statement here to check for the password 'ThisI$MyPassw0rd'

    print('You\'re in.')

else:

    print('Sorry...invalid password')

 

Answer:

password = input('Enter a password: ')

if password == 'ThisI$MyPassw0rd':

    print('You\'re in.')

else:

    print('Sorry...invalid password')

 

 

 

Live Code Example 3.4

 

The code below first asks if a student is taking a course load of 12 or more hours. If the answer is no, they are asked to see their advisor. If the answer is yes, then the student is asked how many courses are in their major. If the answer is no, they are asked to double check the requirements for their major. If the answer is yes, their course load is acceptable.

Indent the 
if statements correctly.

 

num_hours = int(input('How many hours are you taking this semester? '))

num_majors = int(input('How many of these courses are in your major? '))

 

if num_hours >= 12:

if num_majors >= 3:

   print('Your course load is acceptable.')

else:

   print('Double check the requirements for your major.')   

else:

 

    print('Please see your advisor to register.')

Answer:

num_hours = int(input('How many hours are you taking this semester? '))

num_majors = int(input('How many of these courses are in your major? '))

 

if num_hours >= 12:

    # outer if block

    if num_majors >= 3:

        # inner if block

        print('Your course load is acceptable.')

    else:

        print('Double check the requirements for your major.')   

else:

    print('Please see your advisor to register.')

 

 

         

Quiz 3.3 (Scored)

 

Question 1

Write a Boolean expression that is True if s references the string "end".

Answer:

s == "end"

 

 

 

Question 2

Assume both the variables s1 and s2 have been assigned strings. Write an expression that evaluates to True if s1 is greater than s2.

Answer:

s1 > s2

 

 

 

Question 3

Write a Boolean expression that is True if the variable s does not reference the string "end".

Answer:

s != "end"



 

Live Code Example 3.5

The code below asks the user how many steps they have walked in a day. Feedback is given based on the number of steps, which are defined as constants.

 

# Constants for step levels

A_STEPS = 10000

B_STEPS = 8000

C_STEPS = 6000

D_STEPS = 4000

 

numsteps = int(input('How many steps did you walk today? '))

 

if numsteps >= A_STEPS:

   print('Great job!')

# Fill in the missing code here

   print('Good work! Just a few more left to go.')

elif numsteps >= C_STEPS:

   print('Nice! More than halfway there!')

elif numsteps >= D_STEPS:

   print('Good start! Keep active the rest of the day!')

# Fill in the missing code here

   print('No worries. Still time to get some steps in!')

 

Answer:

# Constants for step levels

A_STEPS = 10000

B_STEPS = 8000

C_STEPS = 6000

D_STEPS = 4000

 

numsteps = int(input('How many steps did you walk today? '))

 

if numsteps >= A_STEPS:

   print('Great job!')

elif numsteps >= B_STEPS:

   print('Good work! Just a few more left to go.')

elif numsteps >= C_STEPS:

   print('Nice! More than halfway there!')

elif numsteps >= D_STEPS:

   print('Good start! Keep active the rest of the day!')

else:

   print('No worries. Still time to get some steps in!')

 

 

Live Code Example 3.6

You have 1000 possible points in a class and are trying to decide whether to take an optional final. The code below contains an error. Fill in the commented line with the missing code to display the expected output. Running points that are above or equal to 800 points display the “You're doing fine” message.

 

running_total = int(input('How many points do you have in this course?  '))

if running_total >= 900:

    print('Congratulations! ')

    print('There is no need to take the final ')

elif running_total >= 850:

    print('Good work! ')

    print('You might want to take the final. ')

# Fill in the missing statement here

    print('You\'re doing fine. ')

    print('But you might consider taking the final. ')

else:

    print('We recommend taking the final. ')

    print('Find a study partner ... and good luck! ')

 

Answer:

running_total = int(input('How many points do you have in this course?  '))

if running_total >= 900:

    print('Congratulations! ')

    print('There is no need to take the final ')

elif running_total >= 850:

    print('Good work! ')

    print('You might want to take the final. ')

elif running_total >= 800:

    print('You\'re doing fine. ')

    print('But you might consider taking the final. ')

else:

    print('We recommend taking the final. ')

    print('Find a study partner ... and good luck! ')

 

 

 

Live Code Example 3.7

The program below asks the user to replace their default username and password if they have not done so already.

 

DEFAULT_USERNAME = 'user'

DEFAULT_PASSWORD = 'welcome'

 

username = input('What is your name? ')

password = input('What is the password? ')

if username == DEFAULT_USERNAME and password == DEFAULT_PASSWORD:

    print ('Please change your username and password to enter the forum.')

elif username == DEFAULT_USERNAME and password != DEFAULT_PASSWORD:

    print ('Your username is still set to the default. Please change it to enter the forum.')

# Fill in the missing statement here

    print ('Your user password is still set to the default. Please change it to enter the forum.')

else:

    print ('Welcome to the community forum.')

Answer:

 

DEFAULT_USERNAME = 'user'

DEFAULT_PASSWORD = 'welcome'

 

username = input('What is your name? ')

password = input('What is the password? ')

if username == DEFAULT_USERNAME and password == DEFAULT_PASSWORD:

    print ('Please change your username and password to enter the forum.')

elif username == DEFAULT_USERNAME and password != DEFAULT_PASSWORD:

    print ('Your username is still set to the default. Please change it to enter the forum.')

elif username != DEFAULT_USERNAME and password == DEFAULT_PASSWORD:

    print ('User password is still set to the default. Please change it to enter the forum.')

else:

    print ('Welcome to the community forum.')


 

 

Quiz 3.4 (Scored)

 

Question 1

Assume that ph has been assigned a float. Write an if-else-if statement that

compares ph to 7.0 and makes the following assignments (respectively) to the variables neutralbase, and acid:

·         0,0,1 if ph is less than 7

·         0,1,0 if ph is greater than 7

·         1,0,0 if ph is equal to 7

Answer:

 

if ph < 7:

     neutral = 0

     base = 0

     acid = 1

elif ph > 7:

     neutral = 0

     base = 1

     acid = 0

else:

     neutral = 1

     base = 0

     acid = 0

 

 

 

Checkpoint 3.13

A compound Boolean expression is created by using a concatenation operator to combine two

Boolean subexpressions.

a. True

b. False

Answer: False



Checkpoint 3.14

The following logical expression evaluates to either true (T) or false (F). Choose the correct result.

 

True and False

 

a. True

b. False

Answer: False

Checkpoint 3.15

The following logical expression evaluates to either true (T) or false (F). Choose the correct result.

 

True and True

 

a. True

b. False

Answer: True

Checkpoint 3.16

The following logical expression evaluates to either true (T) or false (F). Choose the correct result.

 

False and True

 

a. True

b. False

Answer: False

Checkpoint 3.17

The following logical expression evaluates to either true (T) or false (F). Choose the correct result.

 

False and False

 

a. True

b. False

Answer: False

Checkpoint 3.18

The following logical expression evaluates to either true (T) or false (F). Choose the correct result.

 

True or False

 

a. True

b. False

Answer: True

Checkpoint 3.19

The following logical expression evaluates to either true (T) or false (F). Choose the correct result.

 

True or True

 

a. True

b. False

Answer: True

 

Checkpoint 3.20

The following logical expression evaluates to either true (T) or false (F). Choose the correct result.

 

False or True

 

a. True

b. False

Answer: True

Checkpoint 3.21

The following logical expression evaluates to either true (T) or false (F). Choose the correct result.

 

False or False

 

a. True

b. False

Answer: False

Checkpoint 3.22

The following logical expression evaluates to either true (T) or false (F). Choose the correct result.

 

not True

 

a. True

b. False

Answer: False

Checkpoint 3.23

The following logical expression evaluates to either true (T) or false (F). Choose the correct result.

 

not False

 

a. True

b. False

Answer: True


 

Checkpoint 3.24

 

If a = 2, b = 4, and c = 6, indicate whether the following condition evaluates to true (T) or false (F).

a == 4 or b > 2

a. True

b. False

Answer: True

 



Checkpoint 3.25

If a = 2, b = 4, and c = 6, indicate whether the following condition evaluates to true (T) or false (F).

6 <= c and a > 3

a. True

b. False

Answer: False


 

Checkpoint 3.26

If a = 2, b = 4, and c = 6, indicate whether the following condition evaluates to true (T) or false (F).

1 != b and c != 3

a. True

b. False

Answer: True

 

Checkpoint 3.27

If a = 2, b = 4, and c = 6, indicate whether the following condition evaluates to true (T) or false (F).

a >= −1 or a <= b

a. True

b. False

Answer: True


 

Checkpoint 3.28

If a = 2, b = 4, and c = 6, indicate whether the following condition evaluates to true (T) or false (F).

not (a > 2)

a. True

b. False

Answer: True

 

 

 

Checkpoint 3.29

With the or operator, if the expression on the left side of the or operator is false,

the expression on the right side will not be checked.

a. True

b. False

Answer: False



Checkpoint 3.30

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 3.31

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

 

Live Code Example 3.8

The program below checks for a weekend day and displays the appropriate message. The last if statement displays the message “Enjoy your weekend” if weekday_day is True. Fill in the commented line with the missing code.

 

weekend = input('Enter the day of the week to see if the weekend is here: ')

 

if weekend == 'Saturday' or weekend == 'Sunday':

   weekend_day = True

   print('Yes, absolutely!')

else:

   weekend_day = False

   print('No, not quite!')

 

# Fill in the missing statement here

   print('Enjoy your weekend!')

 

Answer:
weekend = input('Enter the day of the week to see if the weekend is here: ')

 

if weekend == 'Saturday' or weekend == 'Sunday':

   weekend_day = True

   print('Yes, absolutely!')

else:

   weekend_day = False

   print('No, not quite!')

 

if weekend_day:

   print('Enjoy your weekend!')

 

 

 

Quiz 3.5 (Scored)

 

Question 1

Assume the variable age has been assigned an integer value, and the variable is_full_time_student has been assigned a Boolean value (True or False). Write an expression that evaluates to True if age is less than 19 or is_full_time_student is True.

Answer:

age < 19 or is_full_time_student == True

 

 

 

Question 2

Assume the variables x and y have been assigned integer values. Write an expression that evaluates to True if x is non-negative and y is negative.

Answer:

x >= 0 and y < 0

 

 

 

Question 3

Assume the variables temperature  and humidity have been assigned integer values. Write an expression that evaluates to True if temperature is greater than 90 and humidity is less than 10.

Answer:

temperature > 90 and humidity < 10

 

 

 

Question 4

Assume the variables years_with_company and department have been assigned integer values. Write an expression that evaluates to True if years_with_company is less than 5 and department is not equal to 99.

Answer:

(years_with_company < 5 and department != 99)

 

 

 

Question 5

Assume x refers to an int. Write a Boolean expression that is True if the variable x refers an even number.

Answer:

x%2 == 0

 

 

 

Checkpoint 3.32

A bool variable can be assigned the values of ________.

a. True or False

b. 0  or 1

c. Yes or No

d. On or Off

Answer: a


 

Checkpoint 3.33

A variable that signals when some condition exists in the program is called a(n) _________ variable.

a. byte

b. temporary

c. indicator

d. flag

Answer: d

 

 

 

Live Code Example 3.9

Suppose a salesperson has a quota of $50,000. Re-write line 6 below.

 

sales = int(input('What is the sales? '))

if sales >= 50000.0:

    sales_quota_met = True

else:

    sales_quota_met = False

if sales_quota_met == True: #re-write this line to eliminate the == operator

    print('You have met your sales quota!')

else:

    print('You have not met your sales quota.')

Answer:

sales = int(input('What is the sales? '))

if sales >= 50000.0:

    sales_quota_met = True

else:

    sales_quota_met = False

if sales_quota_met:

    print('You have met your sales quota!')

else:

    print('You have not met your sales quota.')

 

 

 

Quiz 3.6 (Scored)

 

Question 1

Assign True to the variable hasPassedTest.

Answer:

hasPassedTest = True

 

 

 

Question 2

Assume that a variable hoursWorked has been assigned an integer. Write a statement that assigns the value True to the variable workedOvertime if hoursWorked is greater than 40 and False otherwise.

Answer:

workedOvertime = hoursWorked > 40

 

 

 

Checkpoint 3.34

How do you retrieve a turtle’s X and Y coordinates?

a. Copy the turtle object.

b. Call the turtle’s coordinate (x, y) function.

c. Use the turtle.xcor() and turtle.ycor() functions.

d. Access the turtle’s x and y coordinates directly.

Answer: c


 

Checkpoint 3.35

How would you determine whether the turtle’s pen is up?

a. Use the not operator with the turtle.isdown() function.

b. Use the and operator with the turtle.isdown() function.

c. Use the or operator with the turtle.isup() function.

d. Use the equals operator with the turtle.isup() function.

Answer: a



Checkpoint 3.36

You can determine whether the turtle is visible with the _________ function.

a. turtle.display()

b. turtle.show()

c. turtle.isthere()

d. turtle.isvisible()

 Answer: d


 

Checkpoint 3.37

You use the _________ function to determine the current background color of the turtle’s graphics window.

a. turtle.currcol()

b. turtle.bgcolor()

c. turtle.rgbcolor()

d. turtle.mycolor()

Answer: b

 

 

 

Chapter 3 Programming Project 1 (Scored)

The date June 10, 1960, is special because when it is written numerically, the month time the day equals the year:

6/10/60 --> 6*10 = 60

Write a program that asks the user to enter a month (in numeric form), a day, and a two-digit year in three separate input statements. The program should determine whether the month times the day equals the year. If so, it should print, "This date is magic!" Otherwise, it should print, "This date is not magic."

 

Look carefully at the following sample runs of the program. In particular, notice the wording of the messages and the placement of spaces and colons. Your program's output must match this.


Sample Run (user input shown in bold)

Enter month (numeric):12
Enter day:8
Enter two digit year:96
This date is magic!

 

Sample Run (user input shown in bold)

Enter month (numeric):10
Enter day:2
Enter two digit year:75
This date is not magic

 

 

Answer:

month = int(input('Enter month (numeric):'))
day = int(input('Enter day:'))
year = int(input('Enter two digit year:'))

if month * day == year:
    print('This date is magic!')
else:
    print('This date is not magic.')

 

 

 

Chapter 3 Programming Project 2 (Scored)

The colors red, blue, and yellow are known as the primary colors because they cannot be made by mixing other colors. When you mix two primary colors, you get a secondary color:

When you mix red and blue, you get purple.
When you mix red and yellow, you get orange.
When you mix blue and yellow, you get green.

Write a program that prompts the user to enter the names of two primary colors, one at a time. If the user enters anything other than "red," "blue," or "yellow," the program should print "You didn't input two primary colors." Otherwise, it should print a message in the following format: "When you mix red and blue, you get purple." (Assuming the user entered "red" and "blue”.)

 

Look carefully at the following sample runs of the program. In particular, notice the wording of the messages and the placement of spaces, colons, and punctuation. Your program's output must match this.


Sample Run (User input shown in bold)
Enter primary color:red
Enter primary color:blue
When you mix red and blue, you get purple

 

Sample Run (User input shown in bold)
Enter primary color:teal
Enter primary color:orange
You didn't input two primary colors.

 

Answer:

prim1 = input('Enter primary color:')
prim2 = input('Enter primary color:')

 

prim1 = prim1.lower()
prim2 = prim2.lower()
color = 'no color'

if prim1 == 'yellow' and prim2 == 'blue' or prim1 == 'blue' and prim2 == 'yellow':
    color = 'green'
elif prim1 == 'red' and prim2 == 'yellow' or prim1 == 'yellow' and prim2 == 'red':
    color = 'orange'
elif prim1 == 'red' and prim2 == 'blue' or prim1 == 'blue' and prim2 == 'red':
    color = 'purple'

if color == 'no color':
    print("You didn't input two primary colors.")
else:
    print('When you mix ' + prim1 + ' and ' + prim2 + ', you get ' + color + '.')

 

 

 

Chapter 4 Solutions

 

 

Checkpoint 4.1

A control structure that causes a statement or group of statements to repeat as many times as necessary is known as a(n) _____.

a.      loop

b.     operator

c.      counter

d.     sequence

Answer: a



 

Checkpoint 4.2

A condition-controlled loop in Python _____.

a.      repeats a specific number of times

b.     uses a for clause

c.      is based on a counter

d.     relies on a true-false state

Answer: d

 



Checkpoint 4.3

In Python, you use a while statement to write code that repeats a specific number of times.

a. True

b. False

Answer: False

 

 

 

Checkpoint 4.4

A while loop contains a statement or set of statements that is repeated as long as a condition is true.

a. True

b. False

Answer: True

 

 

Checkpoint 4.5

If the condition is _____ in a while loop, the program exits the loop.

Answer: False

 

 

Checkpoint 4.6

An execution of the statements in the body of the loop is called a(n) _____.

a.      accumulation

b.     iteration

c.      range

d.     control

Answer: b

 

 

Checkpoint 4.7

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 4.8

A while loop tests its expression _____.

a.      once, during initialization 

b.     before each iteration

c.      after each iteration

d.     inside the loop

Answer: b

 

 

Live Code Example 4.1         

The following program uses a while loop to display I love to code! five times. Modify the program so it displays I love to code! ten times.

number = 0

while number < 5:

    print ('I love to code')

    number += 1

 

Answer:

number = 0

while number < 10:

    print ('I love to code')

    number += 1



Checkpoint 4.9

An important characteristic of the while loop is that the loop will never iterate if the test expression is false to start with.

a. True

b. False

Answer: True



 

Live Code Example 4.2

The following code snippet allows the user to enter a number, and then multiplies the number by 10 and assigns the result to a variable named product. The loop iterates as long as product is less than 100. Replace commented lines 2 and 4 with the appropriate code.

1 product = 0

2 # Write a loop statement                              

3       number = int(input('Enter a number: '))

4       # Enter the multiplication operation and assignment

 

Answer:

product = 0

while product < 100:                            

    number = int(input('Enter a number: '))

    product = number * 10



 

Live Code Example 4.3         

The following code snippet asks the user to enter two numbers. It then adds the numbers and displays the sum. Next, the user is asked, “Would you like to try this operation again”? If the answer is ‘y’, the loop repeats; if ‘n’, it terminates. Replace the commented lines 2, 5, and 7 with the missing code.

 

1 again = 'y'

2 # Write the loop statement.

3    num1 = float(input('Enter a number: '))

4    num2 = float(input('Enter another number: '))

5    # Enter the specified operations. 

6    print ('The sum of the numbers you entered is', sum)

7    # Ask the user to continue or stop.

Answer:

again = 'y'

while again == 'y':

    num1 = float(input('Enter a number: '))

    num2 = float(input('Enter another number: '))

    sum = num1 + num2 

    print ('The sum of the numbers you entered is', sum)

    again = input('Would you like to try this operation again”? (y/n): ')

 



Checkpoint 4.10

How many times will ‘Hello World’ be printed in the following code?

count = 10

while count < 1:

   print (‘Hello World’)

a.      0

b.     1

c.      10

d.     an infinite number of times

Answer: a

 

 

Checkpoint 4.11

How many times will ‘Hello World’ be printed in the following code?

 

count = 10

while count >= 10:

  print (‘Hello World’)

  count +=1

a.      0

b.     1

c.      10

d.     an infinite number of times

Answer: d

 

 

Checkpoint 4.12

An infinite loop repeats until the program is _____.

a.      replicated

b.     debugged

c.      interrupted

d.     recompiled

Answer: c

 

 

 

 

 

 

 

Quiz 4.2 (Scored)

 

Question 1

Given that n refers to a positive integer, use a while loop to compute the sum of the cubes of the first n counting numbers, and assign this value to total. In other words, total should be assigned:

 

1 * 1 * 1 + 2 * 2 * 2 + … n * n * n

 

Use no variables other than nk, and total.

Answer:

total = 0
k = 0
while k <= n:
     total += k * k * k
     k += 1

 

 

 

Question 2

In this exercise, use the following variables: ilohi, and result. Assume that lo and hi each are assigned an integer and that result is assigned 0.

Write a while loop that adds the integers from lo up through hi (inclusive), and assigns the sum to result.

 

Your code should not change the values associated with lo and hi. Also, just use these variables: ilohi, and result.

Answer:

i = lo
while i <= hi:
   result += i
   i += 1

 

 

 

Checkpoint 4.13

A for statement in Python has a typical format, as shown below, but without the header. What is the pseudocode of the “for” header used in this chapter?

 

_______________________

    statement:

    statement:

    Etc.

 

a. for {variable1, variable2, etc.} with value

b. for value [variable1; variable2; etc.]

c. for {variable1 : variable2} {etc.} with value

d. for value in {variable1, variable2, etc.}

Answer: d

 

 



Checkpoint 4.14

What is the first step in a for loop?

a.      The sequence of data items is initialized to the value of the variable.

b.     The variable is assigned the first value in the sequence of data items.

c.      The variable is tested against the value of each data item.

d.     The variable is initialized to zero before the loop.

Answer: b

 

 

Checkpoint 4.15

The variable used in a for clause is known as the _____ variable of an assignment at the beginning of each loop iteration.

Answer: target



 

Checkpoint 4.16

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 4.17

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 4.18

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

Checkpoint 4.19

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

 

Checkpoint 4.20

What will the following code display? 

 

for x in range(10, 15, 2):

⋅⋅⋅⋅print(x)

 

(Note: The ⋅⋅⋅⋅ symbols represent indentation.)

 

a)         10

            11

            12

            13

            14

 

b)         10

            2

 

c)         10

            12

            15

 

d)         10

            12

            14

 

Answer: 

d)         10

            12

            14

 

 

 

 

Checkpoint 4.21

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Live Code Example 4.4

The code snippet below results in the output that follows. Replace the commented second line with code that will correctly print the string team.  

 

for member in ['Jonathan', 'Joyce', 'Hopper']:

  # Assign a string to team to display output correctly.

  print (team)

 

 

Output:   

Hi Jonathan. Would you like to work together on the group project?

Hi Joyce. Would you like to work together on the group project?

Hi Hopper. Would you like to work together on the group project?

for member in ['Jonathan', 'Joyce', 'Hopper']:

  # Assign a string to team to display output correctly.

  print (team)

 

Answer:

for member in ['Jonathan', 'Joyce', 'Hopper']:

  team = "Hi " + member + ". Would you like to work together on the group project?"

  print (team)

   

 

 

Checkpoint 4.22

What sequence of numbers will the following code display?

 

for x in range(100, 0, -1):

⋅⋅⋅⋅print(x)

 

(Note: The ⋅⋅⋅⋅ symbols represent indentation.)

 

a)         100, 99, 98, … 0

b)         99, 98, … 1

c)         100, 99, 98, … 1

c)         100, 99, 98, … -1

 

ANSWER: 

c)         100, 99, 98, … 1

 

 

 

Live Code Example 4.5

The following code will calculate the total of the following series of numbers:

1/30 + 2/29 + 3/28 + … 30/1

Replace commented lines 1, 3, and 6 with the appropriate code.

 

# Initialize the denominator to its first value in the list.

total = 0

# Write a for statement for the numerator with start/end limits.

    value = numerator / denominator

    total = total + value

    # Decrement the denominator.

print (total)

 

Answer:

denominator = 30

total = 0

for numerator in range(1, 31):

    value = numerator / denominator

    total = total + value

    denominator -= 1

print (total)

 

 

Quiz 4.3 (Scored)

 

Question 1

Assume the variable upper_limit is assigned the value 50. How many times will the following for loop iterate?

 

for x in range(0, upper_limit):

 

a)    49

b)    50

c)    0

d)    51

 

Answer: 50

 

 

Question 2

Write code that assigns the average of the numbers from 1 to n (where n is a positive integer value) to the variable avg.

Answer:

total = 0

for i in range(1, n+1) :

    total += i

avg = float(total) / n

 

 

 

 

Checkpoint 4.23

What will the following code display?

 

total = 0

for count in range(1, 6):

   total = total + count

print(total)

 

A)6

B)1

C) 15

D) 21

Answer: C

 

 

Live Code Example 4.6

The following code snippet asks the user to enter a number inside a loop. The loop iterates 3 times and keep a running total of the numbers entered. Replace the commented line 2 and 4 with the appropriate code. 

 

1 total = 0.0

2    # write a for clause with the correct range

3        number = float(input('Enter a number: '))

4        # write the operation to be performed here

5    print ('The total is', total)

 

Answer:

total = 0.0

for counter in range(3):

    number = float(input('Enter a number: '))

    total += number

print ('The total is', total)

 

 

Checkpoint 4.24

What will the following code display?

 

number1 = 10

number2 = 5

number1 = number1 + number2

print(number1)

print(number2)

 

 

A)

10

5

 

B)

15

5

 

C)

5

10

 

D)

5

15

 

Answer:

15

5

 



Checkpoint 4.25

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 4.26

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 4.27

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 4.28

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

Checkpoint 4.29

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 4.30

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 4.31

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

Checkpoint 4.32

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Quiz 4.4 (Scored)

 

Question 1

Given a variable bridge_players, write a statement that increases its value by 4.

Answer:

bridge_players += 4

 

 

 

Checkpoint 4.33

A sentinel is a special value that marks the _____ of a list of items.
Answer: end

 

 

 

Checkpoint 4.34

A sentinel value must be unique enough that it will not be mistaken as a regular value in the list.

a. True

b. False

Answer: True

 

 

 

Quiz 4.5 (Scored)

 

Question 1

Write a program with a loop that repeatedly reads a string as input, where the string is either "duck" or "goose". The loop terminates when "goose" is entered. After the loop, your code should print out the number of "duck" strings that were read.

NOTE: When reading the input, do not display a prompt for the user. Use the input() function with no prompt string. Here is an example:

bird = input()

 

Answer:

ducks = 0

 

bird = input()

 

while bird!="goose":

   ducks += 1

   bird = input()

 

print(ducks)

 

 

Question 2

You want to know your grade in Computer Science, so write a program that continuously takes grades between 0 and 100 to standard input until you input "stop", at which point it should print your average to standard output.

 

NOTE: When reading the input, do not display a prompt for the user. Use the input() function with no prompt string. Here is an example:

grade = input()

 

 

Answer:

grades = input()

counter = 0

sum = 0

 

while grades != "stop":

    sum += int(grades)

    counter += 1

    grades = input()

print(sum/counter)

 

 

 

Checkpoint 4.35

The acronym GIGO means that if bad data (_____) is provided as _____ to a program, the

program will produce bad data (_____) as ______.
Answer:

garbage; input; garbage; output

 

 

 

Checkpoint 4.36

When the input to a program is invalid, it should be _____ and the user should be _____ the correct data.

a.      replaced; prompted to enter

b.     discarded; prevented from entering

c.      discarded; prompted to enter

d.     replaced; prevented from entering

Answer: c

 

 

Checkpoint 4.37

When a sentinel is used in a (pretest/posttest) loop to validate data, the loop repeats as long as the input is (valid/invalid).

A) pretest, invalid

B) posttest, invalid

C) pretest, valid

D) ) posttest, valid

Answer: pretest, invalid



 

Checkpoint 4.38

With an input validation loop, the purpose of the _____ _____ is to obtain the first input value.

Answer: priming read



 

Live Code Example 4.7

The following code snippet prompts the user to enter a positive nonzero number and validates the input. Replace commented lines 2 and 4 with the appropriate code.

 

1 number = float(input('Enter a positive nonzero number: '))

2 # write a while loop that tests for a positive nonzero number

3    print('That is an invalid value.')

4    # prompt the use appropriately  

5 print ('Thanks!')


Answer:

number = float(input('Enter a positive nonzero number: '))

while number <= 0:

    print('That is an invalid value.')

    number = float(input('Enter a positive nonzero number: '))

print ('Thanks!')

 

 

 

Live Code Example 4.8

The following code snippet prompts the user to enter a number in the range of 1 through 100 and validates the input. Replace commented lines 1 and 3 with the appropriate code

 

1 # write the appropriate user prompt for the specified data

2 while number < 1 or number > 100:

3    # output a statement indicating invalid input

4    number = int(input('Enter a number between 1 and 100: '))     

5 print ('Thanks!')

 

Answer:

number = int(input('Enter a number between 1 and 100: '))

while number < 1 or number > 100:

    print('That is an invalid value.')

    number = int(input('Enter a number between 1 and 100: '))     

print ('Thanks!')

 

 

 

Quiz 4.6 (Scored)

 

Question 1

You have a unique ID number, which is a string of digits. Assume the variable id references a string that contains your ID number. Write a program that repeatedly reads a string as input. If the string that was entered is not equal to your ID number, the program should display the following string: "This is not your ID number."

 

If the string that was entered is equal to your ID number, the  program should display the string: "This is your ID number:", followed by a space, followed by the ID number, and then terminate the loop.

 

NOTE: When reading the input, do not display a prompt for the user. Use the input() function with no prompt string. Here is an example:

 

number = input()

 

Answer:

number = input()

 

while number != id:

    print("This is not your ID number.")

    number = input()

print("This is your ID number:", number)

 

Checkpoint 4.39

In a nested loop, the outer loop goes through all of its iterations for every single iteration of the inner loop.

a. True

b. False
Answer: False

 

 

 

Checkpoint 4.40

To calculate the total number of iterations of a nested loop, add the number of iterations of all the loops.

a. True

b. False

Answer: False

 

 

Checkpoint 4.41

What will the following program display?

 

for r in range(1, 4):

⋅⋅⋅⋅for c in range(r):

⋅⋅⋅⋅⋅⋅⋅⋅print('#', end='')

⋅⋅⋅⋅print()

 

(Note: The ⋅⋅⋅⋅ symbols represent indentation.)

 

a)

###

##

#

 

b)

#

##

###

####

 

c)

#

##

###

 

d)

# ## ###

 

ANSWER: 

c)

#

##

###

 

 

 

 

 

 

Live Code Example 4.9

In the following code snippet, the for loop iterates eight times to draw the octagon shown in Figure 4-9. Modify this to draw a pentagon (a six-sided figure).

 

# This program won't run on Revel as Turtle Graphics is not supported

# Please try it on a Python interpreter that supports Turtle Graphics

for x in range(8):

   turtle.forward(100)

   turtle.right(45)

 

Answer:

for x in range(6):

    turtle.forward(100)

    turtle.right(45)

 

 

 

Chapter 4 Programming Project 1 (Scored)

 At one college, the tuition for a full-time student is $8,000 per semester. It has been announced that the tuition will increase by 3 percent each year for the next 5 years. Write a program with a loop that displays the projected semester tuition amount for the next 5 years.

 

Your program’s output must exactly match the output shown in the sample run below. Notice the wording of the messages and the placement of spaces and punctuation. Also, make sure that the tuition amounts are rounded to two decimal places.

 

Sample Run

In 1 year, the tuition will be $8240.00.

In 2 years, the tuition will be $8487.20.

In 3 years, the tuition will be $8741.82.

In 4 years, the tuition will be $9004.07.

In 5 years, the tuition will be $9274.19.

 

 

Answer:

tuition = 8000.0

 

for i in range(1, 6):

    tuition *= 1.03

    if i == 1:

        print('In 1 year, the tuition will be $' + format(tuition, '.2f') + '.')

    else:

        print('In ' + str(i) + ' years, the tuition will be $' + format(tuition, '.2f') + '.')

 

 

 

Chapter 4 Programming Project 2

In mathematics, the notation n! represents the factorial of the nonnegative integer n. The factorial of n is the product of all the nonnegative integers from 1 to n. For example:

7! = 1 x 2 x 3 x 4 x 5 x 6 x 7 = 5,040

Write a program that lets the user enter a nonnegative integer and then uses a loop to calculate the factorial of that number. Print the factorial to standard output.

 

Look carefully at the following sample run of the program. In particular, notice the wording of the message and the placement of spaces and colons. Your program's output must match this.


Sample Run (User input shown in bold)
Enter a nonnegative integer:7
5040

 

Answer:

num = int(input("Enter a nonnegative integer:"))
factorial = 1

for i in range(2, num+1):
    factorial *= i

print(factorial)

 

 

 

Chapter 5 Solutions

 



Checkpoint 5.1

A ________ is a group of statements that exist within a program for the purpose of performing a specific task.

a. protocol

b. blueprint

c. paradigm

d. function

Answer: d




Checkpoint 5.2

A large task is divided into several smaller tasks that are easily performed. This technique is known as _________.

a. pass and process

b. get and set

c. divide and conquer

d. break and build

Answer: c




Checkpoint 5.3

If a specific operation is performed in several places in a program, a function can be written once to perform that operation, and then be reused any time it is needed.

a. True

b. False

Answer: True




Checkpoint 5.4

Functions can be written for ________ across different programs to make development faster.

a. common tasks

b. unique tasks

c. open access

d. continual revision

Answer: a




Checkpoint 5.5

When a program is developed as a set of functions in which each performs an individual task, the same programmer should be assigned to the job of writing the different functions.

a. True

b. False

Answer: False

 



Checkpoint 5.6

A function definition has two parts: _________.

a. an ID and variable list 

b. an entry and an exit

c. a key and an access list

d. a header and a block

Answer: d




Checkpoint 5.7

To call a function means to _________ the function.

a. create

b. execute

c. test

d. pass

Answer: b




Checkpoint 5.8

When the end of a function is reached, the computer returns control back to the beginning of the program.

a. True

b. False

Answer: False




Checkpoint 5.9

The Python interpreter uses indentation to determine where a block begins and ends.

a. True

b. False

Answer: True

 

 

 

Live Code Example 5.1

The program below displays a coffee and tea menu. Fill in the missing tea menu to display the expected output.

Expected Output
The espresso menu:
cappucino
cortado
latte
macchiato
mocha

The tea menu:
assam
earl grey
masala chai
rose
turmeric

 

def espresso_menu():

    print('cappucino')

    print('cortado')

    print('latte')

    print('macchiato')

    print('mocha')

 

# Write a similar function called tea_menu to match the expected output.

 

def main():

    print ('The espresso menu:') 

    espresso_menu()

    print ('\nThe tea menu:') 

    tea_menu()

 

main()

 

Answer:

def espresso_menu():

    print('cappucino')

    print('cortado')

    print('latte')

    print('macchiato')

    print('mocha')

 

def tea_menu():

    print('assam')

    print('earl grey')

    print('masala chai')

    print('rose')

    print('turmeric')

 

def main():

    print ('The espresso menu:') 

    espresso_menu()

    print ('\nThe tea menu:') 

    tea_menu()

 

main()

 

 

 

Live Code Example 5.2

 

The program below wants to wish you a good night's sleep, but it contains a couple of errors. Fix the errors.

Expected Output
def main()

    print('Calling it a day...')

    sleep()

 

def sleep()

    print('Good night!')

    print('Sleep tight!')

   

# Call the main function.

main()

 

Answer:

def main():

    print('Calling it a day...')

    sleep()

   

 

def sleep():

    print('Good night!')

    print('Sleep tight!')

   

# Call the main function.

main()

 

 

 

 

 

Quiz 5.2

Question 1

Write the code to call the function named send_signal. There are no parameters for this function.

Answer:

send_signal()

 

 

 

Question 2

Assume that print_todays_date is a function that uses no parameters. Write a statement that calls (invokes) this function.

Answer:

print_todays_date()

 

 

 

Question 3

Write a definition of the function printDottedLine, which has no parameters. The function should print a single line of output consisting of 5 periods (".").

Answer:

def printDottedLine():

    print(".....")

 

 

 

Checkpoint 5.10

In Python, you can use the ________ function to cause a program to pause until the user presses the Enter key.

a. stop

b. pause

c. input

d. hibernate

Answer: c




Checkpoint 5.11

In top-down design, tasks are broken down into subtasks until no more subtasks can be identified.

a. True

b. False

Answer: True




 

Checkpoint 5.12

What is the last step in top-down design?

a. Order the tasks/

b. Combine the subtasks.

c. Break down the major tasks.

d. Code the subtasks.

Answer: d

 

 

 

Live Code Example 5.3

 


The program below steps through the day, but it's out of order. Rearrange the code.

Expected Output
Good morning!
Meditate on a new day
Make a list
Time for a break!
Taking a breather
Revisit the list
Laundry, grocery, bills...?
Study...
Calling it a day...
Good night!
Sleep tight!

 

# Call the main function.

main()

 

def main():

    print('Good morning!')

    wakeup()

    midday_break()

    evening_chores()

    print('Calling it a day...')

    sleep()

 

def evening_chores():

    print('Revisit the list')

    print('Laundry, grocery, bills...?')

    print('Study...')

 

def midday_break():

    print('Time for a break!')

    print('Taking a breather')

   

def sleep():

    print('Good night!')

    print('Sleep tight!')

 

def wakeup():

    print('Meditate on a new day')

    print('Make a list')

 

Answer:

 

def main():

    print('Good morning!')

    wakeup()

    midday_break()

    evening_chores()

    print('Calling it a day...')

    sleep()

   

def wakeup():

    print('Meditate on a new day')

    print('Make a list')

  

def midday_break():

    print('Time for a break!')

    print('Taking a breather')

   

def evening_chores():

    print('Revisit the list')

    print('Laundry, grocery, bills...?')

    print('Study...')

   

def sleep():

    print('Good night!')

    print('Sleep tight!')

   

# Call the main function.

main()



Checkpoint 5.13

A local variable is declared inside a function, and only statements in the same function can access it.

a. True

b. False

Answer: True

 

Checkpoint 5.14

A variable’s __________ specifies the part of a program in which a variable may be accessed.

a. value

b. scope

c. name

d. attribute

Answer: b

 



Checkpoint 5.15

A local variable in one function cannot have the same name as a local variable in a different function.

a. True

b. False

Answer: False

 

 

 

Live Code Example 5.4

 

In the program below, the user makes an order. Fill in the two commented lines with the missing code to display the expected output.

Expected Output
Hello, I would like to order
Enter your order:
fries
You have ordered fries

 

# Definition of the main function.

def main():

  order = 'Hello, I would like to order'

  # Print the order string above

  # Call the make_order function   

 

# Definition of the make_order function.

def make_order():

   order = input('Enter your order: ')

   print ('You have ordered', order)

 

# Call the main function.

main()

 

Answer:

# Definition of the main function.

def main():

  order = 'Hello, I would like to order'

  print(order)

  make_order()

 

# Definition of the make_order function.

def make_order():

   order = input('Enter your order: ')

   print ('You have ordered', order)

 

# Call the main function.

main()

 

 

 

Live Code Example 5.5


This program multiplies two numbers and stores them into a variable named 
product. Complete the missing code to display the expected output.

Expected Output
Enter an integer: 45
Enter another integer: 3
The result is 135

 

# multiply two integers and display the result in a function

def main():

    val_1 = int(input('Enter an integer: '))

    val_2 = int(input('Enter another integer: '))

    multiply(val_1, val_2)

   

def multiply(num_1, num_2):

    # Write a statement to calculate product

    print ('The result is', product)

 

main()

 

Answer:

# multiply two integers and display the result in a function

def main():

    val_1 = int(input('Enter an integer: '))

    val_2 = int(input('Enter another integer: '))

    multiply(val_1, val_2)

   

def multiply(num_1, num_2):

    product = num_1 * num_2

    print ('The result is', product)

 

main()

 

 

Checkpoint 5.16

The pieces of data that are passed into a function are called ________.

a. arguments

b. parameters

c. values

d. objects

Answer: a

 



Checkpoint 5.17

The variables that receive pieces of data in a function are called _________.

a. arguments

b. parameters

c. values

d. objects

Answer: b




Checkpoint 5.18

A parameter variable’s scope is the entire function in which the parameter is declared.

a. True

b. False

Answer: True



Checkpoint 5.19

When a parameter is changed, it changes the argument that was passed into the parameter as well.

a. True

b. False

Answer: False




Checkpoint 5.20

The following statements call a function named show_data. Which of the statements passes arguments by position, and which passes keyword arguments?

 

show_data(name='Kathryn', age=25)

show_data('Kathryn', 25)

 

a. The first statement passes by keyword argument and the second statement passes by position.

b. The second statement passes by keyword argument and the first statement passes by position.

Answer: b

 

 

 

Live Code Example 5.6

 

The program below gets the number of units and the cost of each unit from the user. Replace the comments that appear in lines 6 and 7 with a statement that calls the show_total_cost function. As arguments, pass the num_units variable into the units parameter and pass the unit_cost variable into the cost parameter.

 

Sample Expected Output

Enter the number of units: 10

Enter the cost of each unit: 5.00

Total Cost: 50.00

 

 1 def main():

 2     # Get the number of units and the unit cost.

 3     num_units = int(input('Enter the number of units: '))

 4     unit_cost = float(input('Enter the cost of each unit: '))

 5    

 6     # Call show_total_cost, passing num_units into the

 7     # units parameter and unit_cost into the cost parameter.

 8

 9 def show_total_cost(units, cost):

10     total_cost = units * cost

11     print('Total Cost:', format(total_cost, ',.2f'))

12

13 # Call the main function.

14 main()

 

ANSWER:

 1 def main():

 2     # Get the number of units and the unit cost.

 3     num_units = int(input('Enter the number of units: '))

 4     unit_cost = float(input('Enter the cost of each unit: '))

 5    

 6     # Display the total cost.

 7     show_total_cost(units=num_units, cost=unit_cost)

 8

 9 def show_total_cost(units, cost):

10     total_cost = units * cost

11     print('Total Cost:', format(total_cost, ',.2f'))

12

13 # Call the main function.

14 main()

 

 

 

Live Code Example 5.7


This program takes a student ID from the user and prints it. However, it will fail on runtime due to an error. Correct the error to display the expected output.

Expected Output
Enter your student_ID: abcd1234
abcd1234

 

def main():

    student_ID = input('Enter your student_ID: ')

    print_me(student_ID)

   

def print_me(ID):

   print(student_ID)

  

main()

 

Answer:

def main():

    student_ID = input('Enter your student_ID: ')

    print_me(student_ID)

   

def print_me(ID):

   print(ID)

  

main()

 

 

Quiz 5.5 (Scored)

 

Question 1
Assume that print_error_description is a function that accepts one integer argument.
Write a statement that invokes the
 print_error_description function, passing it the value 14.
Answer:
print_error_description(14)

Question 2
Write a statement that calls a function named send_two and passes the values 15.955 and 133 as arguments.

Answer:
send_two(15.955, 133)

Question 3
Write the definition of a function named printGrade that takes one argument. The function should print "Grade: " followed by the value of the argument.
Answer
:
def printGrade(grade):
    print('Grade:', grade)

 

 

Checkpoint 5.21

The scope of a global variable is the ________.

a. entire Python space

b. entire program

c. function in which the variable is declared

d. function in which the variable is first used

Answer: b

 



Checkpoint 5.22

Global variables make debugging easier

a. True

b. False

Answer: False




Checkpoint 5.23

A(n) ________ is a name that is available to every function in the program.

a. global constant

b. value

c. identifier

d. element

Answer: a

 



Checkpoint 5.24

If you do not declare a global variable with the global keyword inside a function, then you cannot change the variable’s assignment inside that function.

a. True

b. False

Answer: True

 

 

 

Live Code Example 5.8

 

This program calculates the surface area of a sphere. Fill in the missing line for the calculation inside the sphere_surface_area function. The formula is 4πr2, where π is pi and r is the sphere's radius.

Expected Output
Enter the sphere radius: 10

The surface area is 1256.64

 

 

Answer

PI = 3.14159     # Global constant

 

def sphere_surface_area(radius):

    area = 4 * PI * radius**2

    print('The surface area is', format(area, '.2f'))

 

def main():

    radius = float(input('Enter the sphere radius: '))

    sphere_surface_area(radius)   

main()

 

 

 

Live Code Example 5.9


This program verifies that a number falls within the range specified by 
MAX and MIN. Fill in the commented line with the missing code to display the expected output.

Expected Output
Enter a number: 11
The number 11 is not within a valid range

 

MAX = 10   # global constant

MIN = 0    # global constant

 

def max_min(num):

    # Check that the number is less than max and greater than min.

        print('The number', num, 'is not within a valid range')

    else:

        print('The number', num, 'is within a valid range')  

   

 

def main():

    check_num = int(input('Enter a number: '))

    max_min(check_num)

   

main()

Answer:

MAX = 10   # global constant

MIN = 0    # global constant

 

def max_min(num):

    if num > MAX or num < MIN:

        print('The number', num, 'is not within a valid range')

    else:

        print('The number', num, 'is within a valid range')  

   

 

def main():

    check_num = int(input('Enter a number: '))

    max_min(check_num)

   

main()

 

 

 

Checkpoint 5.25

A void function does not return a value.

Answer: True




Checkpoint 5.26

A prewritten function that performs some commonly needed task is called a _________.

a. lateral function

b. global function

c. system function

d. library function

Answer: d




Checkpoint 5.27

Library functions are like _________ because they accept input, perform some operation (that cannot be seen) using the input, and produce output.

a. open source code

b. black boxes

c. immutable code

d. white boxes

Answer: b

 



Checkpoint 5.28

What does the following statement do?

x = random.randint(1, 100)

 

a. It assigns 100 random integers in a list called x.

b. It assigns a random integer in the range of 1 through 100 to the variable x.

c. It assigns a random number of integers up to 100 in a list called x.

d. It assigns a random integer in the range of 2 through 99 to the variable x.

Answer: b




Checkpoint 5.29

What does the following statement do?

print(random.randint(1, 20))

 

It prints a random integer in the range of 1 through 20.

a. It stores 20 random integers in a list called x.

b. It stores a random integer in the range of 1 through 20 to the variable x.

c. It prints a random number of integers up to 20 in a list called x.

d. It prints a random integer in the range of 1 through 20.

Answer: d




Checkpoint 5.30

What does the following statement do?

print(random.randrange(10, 20))

 

a. It prints a random integer in the range of 10 through 19.

b. It prints a random integer in the range of 10 through 20.

c. It prints 10 random integers up to the value of 20.

d. It prints 20 random integers up to the value of 19.

Answer: a




Checkpoint 5.31

The statement below prints a random number in the range of ___________ up to, but not

including, ___________.

 

print(random.random())

 

a. 0.0; max

b. 0; infinity

c. 0.0; 1.0

d. 0; 100

Answer: c




 

Checkpoint 5.32

Which statement prints a random floating-point number in the range of 0.1 through 0.5?

a. print(random.float(0.1, 0.5))

b. print(random.rand(0.1, 0.5))

c. print(random.uniform(0.1, 0.5))

d. print(random.num(0.1, 0.5))

Answer: c




Checkpoint 5.33

When the random module is imported, what does it use as a seed value for random number generation?

a. the computer’s internal system time

b. the first value in the module

c. a global constant in the program 

d. a parameter of the module

Answer: a




Checkpoint 5.34

If the same seed value is always used for generating random numbers, the random number function

will always generate the same series of pseudorandom numbers.

a. True

b. False

Answer: True

 

 

 

Checkpoint 5.35

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 5.36

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

Quiz 5.7 (Scored)

 

Question 1

Assume that a function named add has been defined. The add function expects two integer arguments and returns their sum. Also assume that two variables, euro_sales and asia_sales, have already been assigned values.

Write a statement that calls the add function to compute the sum of euro_sales and asia_sales and that assigns this value to a variable named eurasia_sales.

Answer:

eurasia_sales = add(euro_sales,asia_sales)

 

 

 

 

 

Question 2

Assume that to_the_power_of is a function that expects two integer arguments and returns the value of the first argument raised to the power of the second argument.

Write a statement that calls to_the_power_of to compute the value of cube_side raised to the power of 3 and that assigns this value to cube_volume.

Answer:

cube_volume = to_the_power_of(cube_side,3)

 

 

 

Checkpoint 5.37

The purpose of the return statement in a function is to ________.

a. serve as an interim error-catching mechanism

b. return a value back to the entire program for global use

c. return a value back to the part of the program that called it

d. serve to maintain the scope of function variables

Answer: c




Checkpoint 5.38

Consider the following function definition:

def do_something(number):

    return number * 2

 

Given the function definition, what will the following statement display?

print(do_something(10))

a. 0

b. 2

c. 10

d. 20

Answer: d

 

 

 

Live Code Example 5.10

 

We revisit the surface area of a sphere in this program. In this program, the surface area is returned by a function named sphere_surface_area, which is called within the main function's print statement. Supply this print statement. Make sure to format the result rounded to two decimal points.

Expected Output
Enter the sphere radius: 10

The surface area is 1256.64

 

Answer

PI = 3.14159     # Global constant

 

def sphere_surface_area(radius):

    return 4 * PI * radius**2

 

def main():

    radius = float(input('Enter the sphere radius: '))

    print('The surface area is',

          format(sphere_surface_area(radius), '.2f'))

    

main()

 

 

 

Live Code Example 5.11

 

This program calculates and displays the square of an integer and displays it. The calculation takes place in the square function, and display is handled by a print statement in the main function. Supply this print statement. Make sure to format the result as in the expected output.

Expected Output
Enter an integer: 13
The result of 13 squared is 169

 

def square(num):

    return num ** 2

   

def main():

    to_square = int(input('Enter an integer: '))

    # Print out the squared number as indicated in the expected output.

 

main()

Answer:

 

def square(num):

    return num ** 2

   

def main():

    to_square = int(input('Enter an integer: '))

    print('The result of', to_square, 'squared is', square(to_square))

 

main()

 

 

Quiz 5.8 (Scored)

 

Question 1

Write the definition of a function named twice that receives an integer argument and returns an integer that is twice the value of the parameter.

Answer:

def twice(var):

    return var * 2

============================================================================== 8/29/2022 ============

The answer above is the correct answer but due to an error the code below scores correct while the code above does NOT !

if y > x:
    max = y
else:
    max = x
print(max)

 

Question 2

Write the definition of a function named max that has three integer parameters and returns the largest of the three parameters.

Answer:

def max(arg1, arg2, arg3):
    max = arg1
    if arg2 > max:

        max = arg2
    if arg3 > max:

        max = arg3
    return max

         

 

 

 

 

Question 3

Write the definition of a function named oneMore which receives an integer argument and returns an integer that is one more than the value of the argument.

Answer:

def oneMore(x):
    return x + 1

 

 

 

Question 4

Write the definition of a function named absoluteValue that receives an integer argument and returns the absolute value of that argument.

Answer:

def absoluteValue(x):
    if x < 0:
        x *= -1
    return x


 

 

 

Question 5

Define a function named signOf that receives an integer argument and returns the value 1 if the argument is positive, 0 if the argument is 0, or -1 if the argument is negative.

Answer:

def signOf(x):
    if x > 0:
        return 1
    elif x == 0:
        return 0
    else:
        return -1

 

 

 

Checkpoint 5.39

What import statement do you need to write in a program that uses the math module?

a)  import math

b) # import math

c) import math.py

d) import_math

Answer: a



 

Checkpoint 5.40

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.


Checkpoint 5.41

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Live Code Example 5.12

 

This program uses the power function in the math library on two numbers and stores the result in a variable named powered. Provide the line with the calculation.

Expected Output
Enter a number: 2.4
Enter a number: 4.5
The result of 2.4 raised to the power of 4.5 is 51.39851690685247

 

import math

 

def main():

 

    num_1 = float(input('Enter a number: '))

    num_2 = float(input('Enter a number: '))

 

    # Calculate num_1 to the power of num_2. 

 

    print('The result of', num_1, 'raised to the power of', num_2, 'is', powered)

 

main()

 

Answer:

# This program demonstrates the pow function.

import math

 

def main():

 

    num_1 = float(input('Enter a number: '))

    num_2 = float(input('Enter a number: '))

 

    powered = math.pow(num_1, num_2)

 

    print('The result of', num_1, 'raised to the power of', num_2, 'is', powered)

 

main()

 

 

 

Live Code Example 5.13


This program uses the hypotenuse function in the math library on two numbers and stores the result in a variable named 
hypotenuse. Provide the line with the calculation.

Expected Output
Enter a number: 7
Enter a number: 9
The hypotenuse of 7.0 and 9.0 is 11.40175425099138

 

import math

 

def main():

 

    num_1 = float(input('Enter a number: '))

    num_2 = float(input('Enter a number: '))

   

    # Calculate the hypotenuse of num_1 and num_2. 

   

    print('The hypotenuse of', num_1, 'and', num_2, 'is', hypotenuse)

 

main()

 

Answer:

import math

 

def main():

 

    num_1 = float(input('Enter a number: '))

    num_2 = float(input('Enter a number: '))

   

    hypotenuse = math.hypot(num_1, num_2)

 

    print('The hypotenuse of', num_1, 'and', num_2, 'is', hypotenuse)

 

main()

 

 

 

Checkpoint 5.42

A module’s file name should end in __________.

a. .py

b. .python

c. .code

d. .file

Answer: a




Checkpoint 5.43

A module’s name cannot be the same as a Python key word.

a. True

b. False

Answer: True




Checkpoint 5.44

A(n) __________ displays a list of the operations on the screen, and allows the user to select the operation that he or she wants the program to perform.

a. operating system

b. menu-driven program

c. user interface

d. command-line prompt

Answer: b




Checkpoint 5.45

Suppose you have coded a module named my_shapes.py that contains the square, circle, and line functions presented in the chapter. Write the import statement that would allow you to use this module in a program. Assume that turtle has already been imported as the first line in the program.

a)  import my_shapes

b)  # my_shapes.py 

c)  import *

d) # import my_shapes

Answer: a

 

 

 

Chapter 5: Programming Project 1

 

Question 1

Suppose you have a certain amount of money in a savings account that earns compound monthly interest, and you want to calculate the amount that you will have after a specific number of months. The formula is as follows:

f = p * (1 + i)^t

f is the future value of the account after the specified time period.
p is the present value of the account (the account's current balance).
i is the monthly interest rate.
t is the number of months.

Write a program that takes the account's present value (current balance), monthly interest rate, and the number of months that the money will be left in the account as three inputs from the user. The program should pass these values to a function that returns the future value of the account, after the specified number of months. The program should print the account's future value.

 

Look carefully at the following sample run of the program. In particular, notice the wording of the messages and the placement of spaces and colons. Your program's output must match this.

Sample Run (User input shown in bold)

Enter current bank balance:35.7
Enter interest rate:0

Enter the amount of time that passes:100

35.7

 

Answer:

def savings(present, interest, time):

    return present * (1 + interest)**time

 

def main():

    present = float(input('Enter current bank balance:'))

    interest = float(input('Enter interest rate:'))

    time = float(input('Enter the amount of time that passes:'))

    print(savings(present, interest, time))

 

main()

 

 

 

Chapter 6 Solutions

 

 

 

Checkpoint 6.1

An ___________ is a file to which a program writes data.

a. input file

b. output file

Answer: b

 

 

Checkpoint 6.2

An ___________ is a file from which a program reads data.

a. input file

b. output file

Answer: a

 

 

Checkpoint 6.3

The three steps that must be taken by a program when it uses a file are to __________ the file.

a. open, process, and close

b. read, execute, and write 

c. process, test, and close

d. read, write, and report

Answer: a

 



Checkpoint 6.4

Even if a text file contains numbers, those numbers are stored in the file as a series of characters.

a. True

b. False

Answer: True

 

 

Checkpoint 6.5

You can view the contents of a binary file with a text editor.

a. True

b. False

Answer: False

 

 

Checkpoint 6.6

When you work with a(n) _________ file, you access data from the beginning of the file to the end of the file.

a. sequential access

b. direct access

c. read-only

d. write-only

Answer: a

 

 

Checkpoint 6.7

When you work with a _________ file, you can jump directly to any piece of data in the file without reading the data that comes before it.

a. sequential access

b. direct access

c. read-only

d. write-only

Answer: b

 

 

Checkpoint 6.8

When writing a program that performs an operation on a file, you must work with the file’s name on the __________ and the name of a variable that references a ___________.

a. package; header

b. file object; disk

c. disk; file object

d. header; package

Answer: c

 

 

Checkpoint 6.9

Suppose a file already exists. If you try to open it as an output file (using the 'w' mode), the file’s contents will be erased.

a. True

b. False

Answer: True

 

 

Checkpoint 6.10

Opening a file creates a _________ between the file and the program, and a(n) _________ between the file and a file object.

a. key; connection

b. link; map

c. connection; association

d. association; key

Answer: c

 

 

Checkpoint 6.11

Closing a file does not disconnect the program from the file.

a. True

b. False

Answer: False

 

 

Checkpoint 6.12

When an input file is opened, its read position is initially set to _________.

a. a random location in the file

b. the first item in the file

c. the last item in the file

d. a specified location in the file

Answer: b

 

 

Checkpoint 6.13

If you want to write data to a file but do not want to erase the existing contents, open the file in _________ mode.

a. append

b. write

c. safe

d. add

Answer: a

 

 

 

Live Code Example 6.1

This program takes three floats and prints them to a file. The write statements are not coded correctly, however. Correct the errors to display/store the expected output.

Expected Output
Enter a number: 55.3
Enter another number: 78.45678
Enter another number: 3.4
Data written to testfile.txt

 

def main():

# Open a file for writing.

    testfile = open('testfile.txt', 'w')

 

   # Get three numbers from the user.

    num1 = float(input('Enter a number: '))

    num2 = float(input('Enter another number: '))

    num3 = float(input('Enter another number: '))

 

    # Write the numbers to the file.

    # Correct the errors in these three statements.

    testfile.write('Float #1: '+ num1 + '\n')

    testfile.write('Float #2: ' + num2 + '\n')

    testfile.write('Float #3: ' + num3 + '\n')

   

    # Close the file.

    testfile.close()

    print('Data written to testfile.txt')

 

# Call the main function.

main()

 

Answer:

def main():

# Open a file for writing.

    testfile = open('testfile.txt', 'w')

 

   # Get three numbers from the user.

    num1 = float(input('Enter a number: '))

    num2 = float(input('Enter another number: '))

    num3 = float(input('Enter another number: '))

 

    # Write the numbers to the file.

    testfile.write('Float #1: '+ str(num1) + '\n')

    testfile.write('Float #2: ' + str(num2) + '\n')

    testfile.write('Float #3: ' + str(num3) + '\n')

   

    # Close the file.

    testfile.close()

    print('Data written to testfile.txt')

 

# Call the main function.

main()

 

 


Quiz 6.1 (Scored)

 

Question 1

Write the code that calls the open function to open a file named hostdata.txt for reading.

Answer:

open('hostdata.txt', 'r')

 

 

 

Question 2

Write the code that calls the open function to open a file named yearsummary.txt in a way that erases any existing data in the file.

Answer:

open('yearsummary.txt', 'w')

 

 

 

Question 3

Write the code that calls the open function to open a file named  priceList.txt for writing.

Answer:

open('priceList.txt', 'w')

 

 

 

Question 4

Given four files named asiasales2009.txt, europesales2009.txt, africasales2009.txt, and latinamericasales2009.txt, define four file objects named asia, europe, africa, and latin, and use them, respectively, to open the four files for writing.

Answer:

asia = open('asiasales2009.txt', 'w')
europe = open('europesales2009.txt', 'w')
africa = open('africasales2009.txt', 'w')
latin = open('latinamericasales2009.txt', 'w')

 

 

 

Question 5

Given a file named execution.log write code that does the following:

·        Open the file

·        Append a new line of text that reads "Program Execution Successful" to the end of the file. (Be sure the text appears on a new line at the end of the file.)

·        Close the file

 

Answer:

f = open('execution.log', 'a')

f.write("\nProgram Execution Successful")
f.close()

 

 

Question 6

Assume that corpdata is a file object that has been used to read data from a file. Write the necessary statement to close the file.

Answer:

corpdata.close()

 

 

 

Checkpoint 6.14

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 6.15

The readline method returns a(n) _________ when it has attempted to read beyond the end of a file.

a. random string

b. warning message

c. error message

d. empty string

Answer: d

 

 

Checkpoint 6.16

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Live Code Example 6.2

This program takes three floats and prints them to a file again, and this time, prints the average of the three numbers as well. Add this calculation to display the expected output. Note that we are not truncating the average in this problem.

Expected Output
Enter a number: 6.5
Enter another number: 8.9
Enter another number: 22.3
Data written to testfile.txt

(In testfile.txt)
Float #1: 6.5
Float #2: 8.9
Float #3: 22.3
Average: 12.566666666666668

 

Answer:

# This program takes three floats, averages them, and prints to a file

 

def main():

   # Open a file for writing.

    testfile = open('testfile.txt', 'w')

 

   # Get three numbers from the user.

    num1 = float(input('Enter a number: '))

    num2 = float(input('Enter another number: '))

    num3 = float(input('Enter another number: '))

 

    # Write the numbers to the file.

    testfile.write('Float #1: '+ str(num1) + '\n')

    testfile.write('Float #2: ' + str(num2) + '\n')

    testfile.write('Float #3: ' + str(num3) + '\n')

    # Write the average of these numbers to the file.        

 

    # Close the file.

    testfile.close()

    print('Data written to testfile.txt')

 

# Call the main function.

main()

Answer:

# This program takes three floats, averages them, and prints to a file

 

def main():

   # Open a file for writing.

    testfile = open('testfile.txt', 'w')

 

   # Get three numbers from the user.

    num1 = float(input('Enter a number: '))

    num2 = float(input('Enter another number: '))

    num3 = float(input('Enter another number: '))

 

    # Write the numbers to the file.

    testfile.write('Float #1: '+ str(num1) + '\n')

    testfile.write('Float #2: ' + str(num2) + '\n')

    testfile.write('Float #3: ' + str(num3) + '\n')

    testfile.write('Average: ' + str((num1 + num2 + num3)/3))

 

    # Close the file.

    testfile.close()

    print('Data written to testfile.txt')

 

# Call the main function.

main()

 

 

 

Quiz 6.2 (Scored)

 

Question 1

A file named numbers.txt contains an unknown number of lines, each consisting of a single integer. Write some code that opens the file, computes the sum of all the integers it contains, and stores the sum in a variable name sum. Don't forget to close the file.

Answer:

numfile = open("numbers.txt","r");

sum = 0

number = numfile.readline()

while number != "":

    sum += int(number)

    number = numfile.readline()

numfile.close()

 

 

 

 

 

Question 2

A file named data1.txt contains an unknown number of lines, each consisting of a single integer. Write some code that creates a file named data2.txt and copies all the lines of data1.txt to data2.txt.

Answer:

infile = open("data1.txt","r");

outfile = open("data2.txt","w");

line = infile.readline()

while line != "":

    outfile.write(line)

    line = infile.readline()

infile.close()

outfile.close()

 

 

 

 

Question 3

A file named data.txt contains an unknown number of lines, each consisting of a single integer.

 

Write a program that creates the following three files:

 

·         dataplus.txt

·         dataminus.txt

·         zeros.txt

 

The program should read each line of the data.txt file and perform the following:

 

·         If the line contains a positive number, that number should be written to the dataplus.txt file.

·         If the line contains a negative number, that number should be written to the dataminus.txt file.

·         If the line contains the value 0, do not write the value to a file. Instead, keep a count of the number of times 0 is read from the data.txt file.

 

After all the lines have been read from the data.txt file, the program should write the count of zeros to the zeros.txt file.

 

Answer:

# Open the files.

infile = open('data.txt','r');

plus = open('dataplus.txt','w');

minus = open('dataminus.txt','w');

zeros = open('zeros.txt', 'w')

 

# Create a counter for the zeros.

zero_count = 0

 

# Process the input file.

line = infile.readline()

while line != '':

    if int(line) > 0:

        plus.write(line)

    elif int(line) < 0:

        minus.write(line)

    else:

        zero_count += 1

    line = infile.readline()

 

# Write the number of zeros to zeros.txt.

zeros.write(str(zero_count))

 

# Close the files.

infile.close()

plus.close()

minus.close()

zeros.close()

 

 

 

 

Checkpoint 6.17

A __________ is a complete set of data that describes one item, and a _________ is a single piece of data within a record.

a. field; cell

b. record; field

c. track; cell

d. cell; track

Answer: b

 

 

Checkpoint 6.18

Suppose you want to use a temporary file in a program that modifies a record in a sequential access file.  When you get to the record to be modified, you _________.

a. write its new, modified values to the temporary file

b. do not write its new, modified values to the temporary file

c. copy the temporary file into the original file

d. rename the temporary file as the original filename

Answer: a

 

 

 

Live Code Example 6.3

This program takes in user input on programming languages, their creators, and a corresponding IDE, and stores the information in records. Fill in the two commented lines with the missing code to create a record and display the expected output.

Expected Output
How many languages do you want to learn? 2
Enter data for programming language #1
Language: Python
Creator: vanRossum
IDE: IDLE

Enter data for programming language #2
Language: Java
Creator: Gosling
IDE: GCC

Programming language records written to pl.txt.
Python
vanRossum
IDLE
Java
Gosling
GCC

 

def main():

    # Get the number of languages you want to learn

    num_pl = int(input('How many languages do you want to learn?  '))

 

    # Open a file for writing.

    pl_file = open('pl.txt', 'w')

 

    # Get the language, the language creator, and a sample IDE's website.

    for count in range(1, num_pl + 1):

    # Get the data for an employee.

        print('Enter data for programming language #', count, sep='')

        pl_name = input('Language: ')

        pl_creator = input('Creator: ')

        pl_IDE = input('IDE: ')

 

        # Write the data as a record to the file.

        # Fill in the name and creator write statements below.

        pl_file.write(pl_IDE + '\n\n')

 

        # Display a blank line.

        print()

       

    # Close the file.

    pl_file.close()

    print('Programming language records written to pl.txt.')

 

#Call the main function.

main()

 

Answer:

def main():

    # Get the number of languages you want to learn

    num_pl = int(input('How many languages do you want to learn?  '))

 

    # Open a file for writing.

    pl_file = open('pl.txt', 'w')

 

    # Get the language, the language creator, and a sample IDE's website.

    for count in range(1, num_pl + 1):

    # Get the data for an employee.

        print('Enter data for programming language #', count, sep='')

        pl_name = input('Language: ')

        pl_creator = input('Creator: ')

        pl_IDE = input('IDE: ')

 

        # Write the data as a record to the file.

        pl_file.write(pl_name + '\n')

        pl_file.write(pl_creator + '\n')

        pl_file.write(pl_IDE + '\n\n')

 

        # Display a blank line.

        print()

       print('Programming language records written to pl.txt.')

 

#Call the main function.

main()    

    # Close the file.

    pl_file.close()



 

Checkpoint 6.19

An exception is an error that occurs _________.

a. while a program is running

b. before a program starts running

c. while a program is compiled

d. after a program executes

Answer: a

 

 

Checkpoint 6.20

If an exception is raised and the program does not handle it with a try/except statement, what happens?

a. The program continues as usual.

b. The program fixes the error.

c. The program runs but with a warning.

d. The program stops executing.

Answer: d

 

 

Checkpoint 6.21

What type of exception does a program raise when it tries to open a nonexistent file?

a. FileError

b. IOError

c. ValueError

d. OpenError

Answer: b

 

 

Checkpoint 6.22

What type of exception does a program raise when it uses the float function to convert a non-numeric string to a number?

a. NumericError

b. IOError

c. ValueError

d. OpenError

Answer: c

 

 

 

Live Code Example 6.4

This program averages three floats and prints the results. It also checks for and displays exceptions, for example, division by zero. Fill in the two commented lines with the correct exception handling statements.

Expected Output
How many numbers do you want to average?: 3
Enter a number: 4.5
Enter a number: 7.6
Enter a number: 9.8
Average: 14.33

 

def main():

    num_elements = 0

    total = 0

   

    # Add a try clause here.

       num_elements = (int(input('How many numbers do you want to average?: ')))

       for x in range(num_elements):

           num = float(input('Enter a number: '))

           total += total + num

 

       print('Average: ' + str(format(total/num_elements, '.2f')))

 

    # Add an except clause here.

        print(err)

 

# Call the main function.

main()

 

Answer:

def main():

    num_elements = 0

    total = 0

   

    try:

       num_elements = (int(input('How many numbers do you want to average?: ')))

       for x in range(num_elements):

           num = float(input('Enter a number: '))

           total += total + num

 

       print('Average: ' + str(format(total/num_elements, '.2f')))

 

    except Exception as err:

        print(err)

 

# Call the main function.

main()

 

 

 

Quiz 6.4 (Scored)

 

Question 1

Two variables, x and y, supposedly hold strings of digits. Write code that converts these to integers and assigns a variable z the sum of these two integers. Make sure that if either x or y has bad data (that is, not a string of digits), z will be assigned the value of -1.

Answer:

try:
    z = int(x) + int(y)
except ValueError:
    z = -1

 

Question 2

Two variables, num_boys and num_girls, hold the number of boys and girls that have registered for an elementary school. The variable budget holds the number of dollars that have been allocated to the school for the school year. Write code that prints out the per-student budget (dollar spent per student). If a division by zero error takes place, just print out the word "unavailable".

Answer:

try:

    print(budget / (num_boys + num_girls))

except ZeroDivisionError:

    print("unavailable")

 

 

 

Question 3

Three variables, x, y, and z, supposedly hold strings of digits, suitable for converting to integers. Write code that converts these three variables to integers and print the sum of these three integers. However, if any variable has a value that cannot be converted to an integer, print out, the string "bad value(s) in: " followed by the names of the variables that have bad values (separated by spaces, in alphabetically ascending order).

 

For example, if the values of x, y, and z were respectively "3", "9", "2" then the number 14 would be printed; but if the values were "abc", "15", "boo" then the output would be:

bad value(s) in: x z

Answer:

sum = 0

badvalues = ''

 

try:

    sum += int(x)

except ValueError:

    badvalues += ' x'

 

try:

    sum += int(y)

except ValueError:

    badvalues += ' y'

 

try:

    sum += int(z)

except ValueError:

    badvalues += ' z'

 

if badvalues=='':

    print(sum)

else:

    print('bad value(s) in:' + badvalues)

 

 

 

Programming Project 1

 

Assume that a file containing a series of integers is named numbers.txt. Write a program that calculates the average of all the numbers stored in the file and prints the average to the screen.

Sample Run
49.6

 

Answer:

file = open('numbers.txt', 'r')
adder = 0
counter = 0


for num in file:
    adder += int(num)
    counter += 1

file.close()
print(adder / counter)

 

 

 

Programming Project 2

 

The Springfork Amateur Golf Club has a tournament every weekend. The club president has asked you to write a program that will read each player's name and score as keyboard input, and then save these as records in a file named golf.txt.

First, the program should ask the user for the number of players. Then, it should ask the user for each name and score individually.

The file golf.txt should be structured so that there is a line with the player's name, followed by their score on the next line. Here is an example:

Emily
30
Mike
20
Jonathan
23

Look carefully at the following sample run of the program. In particular, notice the wording of the messages and the placement of spaces and colons. Your program's output must match this.


Sample Run (User input shown in bold)
Enter number of players:4
Enter name of player number 1:Jimmy
Enter score of player number 1:30
Enter name of player number 2:Carly
Enter score of player number 2:20
Enter name of player number 3:Marissa
Enter score of player number 3:55
Enter name of player number 4:Brett
Enter score of player number 4:23

 

Answer:

# Ask the user for the number of players.

num = int(input('Enter number of players:'))

# Open golf.txt for writing.
file = open('golf.txt', 'w')

# Ask the user for name and score of each player.
for i in range(1, num + 1):
    name = input('Enter name of player number ' + str(i) + ':')
    score = input('Enter score of player number ' + str(i) + ':')

    # Write to a file.
    file.write(name + '\n' + score + '\n')

# Close the file.
file.close()

 

 

 

Programming Project 3

 

Write a program that reads the records from the golf.txt file written in the previous programming project and prints them in the following format:

Name:Emily
Score:30

Name:Mike
Score:20

Name:Jonathan
Score:23

Look carefully at the following sample run of the program. In particular, notice the placement of spaces and colons. Your program's output must match this.


Sample Run

Name:Jimmy
Score:30

Name:Carly
Score:20

Name:Marissa
Score:55

Name:Brett
Score:23

 

Answer:

file = open('golf.txt', 'r')
name = True

for line in file:
    if name:
        print('Name:' + line, end='')
    else:
        print('Score:' + line)

    name = not name
   
file.close()

 

 

 

 

 

Chapter 7 Solutions

 

 

 

Checkpoint 7.1

A sequence contains exactly two items of data.

a. True

b. False

Answer: False

 

 

 

Checkpoint 7.2

The items that are in a sequence are stored one after the other.

a. True

b. False

Answer: True

 

 

 

Checkpoint 7.3

A Python list is immutable.

a. True

b. False

Answer: False

 

 

 

Checkpoint 7.4

Once a Python tuple is created, its contents cannot be changed.

a. True

b. False

Answer: True

 

 

 

Checkpoint 7.5

What will the following code display?

 

numbers = [1, 2, 3, 4, 5]

numbers[2] = 99

print(numbers)

 

a. [1, 2, 99, 4, 5]

b. [1, 99, 3, 4, 5]

c. [1, 99, 99, 99, 99]

d. [1, 99]

Answer: a

 

 

 

Checkpoint 7.6

What will the following code display?

 

numbers = list(range(3))

print(numbers)

 

a. [0, 0, 0]

b. [0, 1, 2]

c. [1, 2, 3]

d. [3]

Answer: b

 

 

 

Checkpoint 7.7

What will the following code display?

 

numbers = [10] * 5

print(numbers)

 

a. [5]

b. [10, 10, 10, 10]

c. [10, 10, 10, 10, 10]

d. [50]

Answer: c

 

 

 

Checkpoint 7.8

What will the following code display?

 

numbers = list(range(1, 10, 2))

for n in numbers:

    print(n)

 

a.

1

2

1

2

1

2

1

2

1

2

 

b.

1

2

 

c.

1

10

2

 

d.

1

3

5

7

9

Answer: d

 

 

 

Checkpoint 7.9

What will the following code display?

 

numbers = [1, 2, 3, 4, 5]

print(numbers[−2])

 

a.

1

2

 

b.

3

 

c.

4

 

d.

4

5

Answer: c

 

 

 

Checkpoint 7.10

What is the best way to find the number of elements in a list?

a. Call the numlist function.

b. Copy the list and print it.

c. Loop through the list with a count variable.

d. Use the len function.

Answer: d

 

 

 

Checkpoint 7.11

What will the following code display?

 

numbers1 = [1, 2, 3]

numbers2 = [10, 20, 30]

numbers3 = numbers1 + numbers2

print(numbers1)

print(numbers2)

print(numbers3)

 

a.

[1, 2, 3]

[10, 20, 30]

[6, 60]

b.

[1, 2, 3]

[10, 20, 30]

[66]

c.

[1, 2, 3]

[10, 20, 30]

[1, 2, 3, 10, 20, 30]

d.

[1, 2, 3]

[10, 20, 30]

[1, 2, 3] [10, 20, 30]

Answer: c

 

 

 

Checkpoint 7.12

What will the following code display?

 

numbers1 = [1, 2, 3]

numbers2 = [10, 20, 30]

numbers2 += numbers1

print(numbers1)

print(numbers2)

 

a.

[1, 2, 3]

[1, 2, 3, 10, 20, 30]

b.

[1, 2, 3]

[10, 20, 30, 1, 2, 3]

c.

[1, 2, 3]

[11, 22, 33]

d.

[1, 2, 3]

[60, 6]

Answer: b

 

 

 

Live Code Example 7.1

This program creates a list named numbers that includes numbers from 100 through 1000 at steps of 50. Type two statements into the interface below, the first to create the numbers list, and the second to print the list.

Expected Output
[100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000]

 

Answer:

numbers = list(range(100, 1050, 50))

print(numbers)

 

 

 

Live Code Example 7.2

This program is meant to display weekday abbreviations, but there is an error. Correct the error in the code.

Expected Output
Mon
Tues
Wed
Thurs
Fri

 

Answer:

weekdays = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri']

for counter in range(5):

    print(weekdays[counter + 1 ])

    counter += 1

 

 

 

Quiz 7.2 (Scored)

 

Question 1

Write a statement that defines plist as a list containing these elements (in order): 'spam', 'eggs', 'vikings' .

Answer:

plist = ['spam', 'eggs', 'vikings']

 

 

 

Question 2

Write statement that defines plist to be a list of the following ten elements: 10, 20, 30, ..., 100 in that order.

Answer:

plist = [10,20,30,40,50,60,70,80,90,100]

 

 

 

Question 3

Write a statement that defines plist to be an empty list.

Answer:

plist = []

 

 

 

Question 4

Assume that plist has been defined to be a list of 30 integers. Write a statement that adds 5 to its last element.

Answer:

plist[-1] += 5

 

 

 

Question 5

Given a variable plist, that refers to a non-empty list, write an expression that refers to the first element of the list.

Answer:

plist[0]

 

 

 

Question 6

Assume that a variable named plist refers to a list with 12 elements, each of which is an integer. Assume that the variable k refers to a value between 0 and 6. Write a statement that assigns 15 to the list element whose index is k.

Answer:

plist[k] = 15

 

 

 

Question 7

Assume that play_list refers to a non-empty list, and that all its elements are integers. Write a statement that assigns a new value to the first element of the list. The new value should be equal to twice the value of the last element of the list.

Answer:

play_list[0] = 2 * play_list[-1]

 

 

 

Question 8

Given that plist1 and plist2 both refer to lists, write a statement that defines plist3 as a new list that is the concatenation of plist1 and plist2. Do not modify plist1 or plist2.

Answer:

plist3 = plist1 + plist2

 

 

 

Question 9

Given a list named play_list, write an expression whose value is the length of play_list.

Answer:

len(play_list)

 

 

 

Checkpoint 7.13

What will the following code display?

 

numbers = [1, 2, 3, 4, 5]

my_list = numbers[1:3]

print(my_list)

 

a. [2, 3]

b. [1, 2, 3]

c. [1, 2]

d. [1, 3]

Answer: a

Checkpoint 7.14

What will the following code display?

 

numbers = [1, 2, 3, 4, 5]

my_list = numbers[:1]

print(my_list)

 

a. [2]

b. [1, 2, 3, 4, 5]

c. [5]

d. [1]

Answer: d

 

 

 

Checkpoint 7.15

What will the following code display?

 

numbers = [1, 2, 3, 4, 5]

my_list = numbers[:]

print(my_list)

 

a.[5]

b. [1, 5]

c. []

d. [1, 2, 3, 4, 5]

Answer: d

 

 

Checkpoint 7.16

What will the following code display?

 

numbers = [1, 2, 3, 4, 5]

my_list = numbers[−3:]

print(my_list)

 

a. [2]

b. [3]

c. [3, 4, 5]

d. [1, 2, 3]

Answer: c

 

 

 

Live Code Example 7.3

Complete the program below display the following output.

 

Expected Output
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[2, 4, 6, 8, 10]
[12, 14, 16, 18, 20]
[2] [20]

evens = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

print(evens)

# enter missing code

# enter missing code

# enter missing code

Answer:

evens = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

print(evens)

print(evens[:5])

print(evens[5:])

print(evens[:1], evens[9:])

 

 

 

Live Code Example 7.4

This program lists a series of even numbers and then selects the number 12 to display. Fill in the last statement with the missing code to display the expected output.

Expected Output
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[12]

evens = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

print(evens)

# Write the print statement to display '[12]'

 

Answer:

evens = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

print(evens)

print(evens[5:6:1])

 

 

 

Quiz 7.3 (Scored)

 

Question 1

Given that play_list has been defined to be a list, write an expression that evaluates to a new list containing the elements at index 0 through index 4 in play_list. Do not modify play_list.

Answer:

play_list[0:5]

 

 

 

Question 2

Given that and each refer to a non-negative integer and that play_list has been defined to be a list with at least j+1 elements, write an expression that evaluates to a new list containing all the elements from the one at index k through the one at index j of list play_list. Do not modify play_list.

Answer:

play_list[k:j+1]

 

 

 

Question 3

What will the following code display?

 

mylist = [1, 2, 3, 4, 5]

print(mylist[2:])

 

a) [3]

b) [3, 4, 5]

c) [2, 3, 4, 5]

d) [1, 2]

 

Answer:

[3, 4, 5]

 

 

 

Question 4

What will the following code display?

 

mylist = ['mercury', 'venus', 'earth', 'mars',

          'jupiter', 'staurn', 'uranus', 'neptune']

print(mylist[0::2])

 

Answer:

['mercury', 'earth', 'jupiter', 'uranus']

 

 

 

Question 5

Given that k refers to an integer that is non-negative and that plist1 has been defined to be a list with at least k+1 elements, write a statement that defines plist2 to be a new list that contains all the elements from index k of plist1 and beyond. Do not modify plist1.

Answer:

plist2 = plist1[k:]

 

 

 

Checkpoint 7.17

What will the following code display?

 

names = ['Jim', 'Jill', 'John', 'Jasmine']

if 'Jasmine' not in names:

     print('Cannot find Jasmine.')

else:

     print("Jasmine's family:")

     print(names)

 

a.

Cannot find Jasmine.

b.

Jasmine's family:

c.

Jasmine's family:

['Jim', 'Jill', 'John', 'Jasmine']

d.

['Jim', 'Jill', 'John', 'Jasmine']

Answer: c

 

 

 

Live Code Example 7.5

This program creates a list of five highest mountains and checks another well-known mountain, Kilimanjaro, against the list. Fill in the missing if statement to display the expected output.

Expected Output
Kilimanjaro is not on the top five list.
['Everest', 'K2', 'Kangchenjunga', 'Lhotse', 'Makalu']

 

top_five_mountains = ['Everest', 'K2', 'Kangchenjunga', 'Lhotse', 'Makalu']

# Fill in the missing if statement here.

    print('Kilimanjaro is not on the top five list.')

else:

    print('Kilimanjaro is one of the top five tallest mountains.')

print(top_five_mountains)

 

Answer:

top_five_mountains = ['Everest', 'K2', 'Kangchenjunga', 'Lhotse', 'Makalu']

if 'Kilimanjaro' not in top_five_mountains:

     print('Kilimanjaro is not on the top five list.')

else:

     print('Kilimanjaro is one of the top five tallest mountains.')

print(top_five_mountains)

 

 

 

Live Code Example 7.6

This program aks the user to enter a grocery item and checks it against a grocery code list. Fill in the missing if statement to display the expected output.

Expected Output
Enter an item: ice cream
The item ice cream was not found in the list.

 

def main():

# Create a list of grocery items.

    grocery_list = ['apples', 'peanut butter', 'eggs', 'spinach', 'coffee', 'avocado']

 

# Search for a grocery item.

    search = input('Enter an item: ')

 

# Determine whether the item is in the list.

    # Fill in the missing if statement

         print('The item', search, 'was found in the list.')

    else:

         print('The item', search, 'was not found in the list.')

 

# Call the main function.

main()

 

Answer:

def main():

# Create a list of grocery items.

    grocery_list = ['apples', 'peanut butter', 'eggs', 'spinach', 'coffee', 'avocado']

 

# Search for a grocery item.

    search = input('Enter an item: ')

 

# Determine whether the item is in the list.

    if search in grocery_list:

         print('The item', search, 'was found in the list.')

    else:

         print('The item', search, 'was not found in the list.')

 

# Call the main function.

main()

 

 

 

Quiz 7.4 (Scored)

 

Question 1

Given:

·         a variable current_members that refers to a list, and

·         a variable member_id that has been assigned a value.

Write some code that assigns True to the variable is_a_member if the value assigned to member_id can be found in the current_members list. Otherwise, assign False to is_a_member. In your code, use only the variables current_membersmember_id, and is_a_member.

Answer:

is_a_member = member_id in current_members

 

 

 

Checkpoint 7.18

The del method searches for and removes an element containing a specific value.

a. True

b. False

Answer: False

 

 

 

Checkpoint 7.19

What is the best way to find the lowest and highest values in a list?

a. Use the built-in min and max functions.

b. Write min and max functions.

c. Copy and print out the list.

d. Sort the list from lowest to highest.

Answer: a

 

 

 

Checkpoint 7.20

Assume the following statement appears in a program:

names = []

 

Which of the following statements should you use to add the string ‘Wendy’ to the

list at index 0?

a. names[0] = 'Wendy'

b. names.append('Wendy')

Answer: names.append('Wendy')

 

 

 

Checkpoint 7.21

The __________ method searches for an item in the list and returns the index of the first element containing that item.

a. index

b. key

c. find

d. first

Answer: a

 

 

 

Checkpoint 7.22

The __________ method reverses the order of the items in the list.

a. index

b. backtrack

c. sort

d. reverse

Answer: reverse

 

 

 

Checkpoint 7.23

The __________ method sorts the items in the list to appear in ascending order.

a. index

b. scramble

c. sort

d. ascend

Answer: c

 

Checkpoint 7.24

The __________ method inserts an item into the list at a specified index.

a. index

b. insert

c. replace

d. add

Answer: b

 

 

 

Live Code Example 7.7

This program creates a list of popular programming/scripting languages. Fill in the missing line for the first insert statement.

Expected Output
The list before the insert:
['Python', 'Java', 'R']
The list after the insert:
['Python', 'Java', 'c', 'R']
The list after another insert:
['Python', 'Java', 'c', 'R', 'Javascript']

# This program demonstrates the insert method.

 

def main():

    # Create a list with some programming languages.

    languages = ['Python', 'Java', 'R']

 

    # Display the list.

    print('The list before the insert:')

    print(languages)

 

    # Insert a new element 'c' here, after 'Java'.

   

    # Display the list again.

    print('The list after the insert:')

    print(languages)

 

    # Insert a new element.

    languages.insert(5, 'Javascript')

 

    # Display the list again.

    print('The list after another insert:')

    print(languages)

   

# Call the main function.

main()

 

Answer:

# This program demonstrates the insert method.

 

def main():

    # Create a list with some programming languages.

    languages = ['Python', 'Java', 'R']

 

    # Display the list.

    print('The list before the insert:')

    print(languages)

 

    # Insert a new element.

    languages.insert(2, 'c')

 

    # Display the list again.

    print('The list after the insert:')

    print(languages)

 

    # Insert a new element.

    languages.insert(5, 'Javascript')

 

    # Display the list again.

    print('The list after another insert:')

    print(languages)

   

# Call the main function.

main()

 

 

 

Quiz 7.5 (Scored)

 

Question 1

Given that a refers to a list, write the necessary code to reverse the elements of the list.

Answer:

a.reverse()

 

 

 

Question 2

Given that play_list has been defined to be a list, write a statement that sorts the list.

Answer:

play_list.sort()

 

 

 

Question 3

Given a variable named plist that refers to a list, write a statement that adds another element, 5 to the end of the list.

Answer:

plist.append(5)

 

 

 

Question 4

Given that k refers to a non-negative int and that alist has been defined to be a list with at least k+1 elements, write a statement that removes the element at index k.

Answer:

del alist[k]

 

 

 

Question 5

Given the lists, lst1 and lst2, create a new sorted list consisting of all the elements of lst1 that also appears in lst2. For example, if lst1 is [4, 3, 2, 6, 2] and lst2 is [1, 2, 4], then the new list would be [2, 2, 4]. Note that duplicate elements in lst1 that appear in lst2 are also duplicated in the new list. Assign the new list to the variable new_list, and don't forget to sort the new list.

Answer:

new_list = []
for i in lst1 :
    if i in lst2 :
        new_list.append(i)
new_list.sort()

 

 

 

Checkpoint 7.25

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Live Code Example 7.8

The following program creates three lists, list1, list2, and list3. Write a statement that creates a fourth list named list4 that contains the contents of list3 followed by the contents of list2 followed by the contents of list1.

 

Expected Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

 

Answer:

list1 = [9, 10, 11, 12]

list2 = [5, 6, 7, 8]

list3 = [1, 2, 3, 4]

list4 = list3 + list2 + list1

print(list4)

 

 

 

Checkpoint 7.26

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Quiz 7.7 (Scored)

 

Question 1

Given a variable temps that refers to a list, all of whose elements refer to values of type float, representing temperature data, compute the average temperature and assign it to a variable named avg_temp. Besides temps and avg_temp, you may use two other variables -- k and total.

Answer:

total = 0.0
for k in temps:
     total += k
avg_temp = total / len(temps)

 

 

 

Question 2

Given:

·         a variable named incompletes that refers to a list of student ids, and

·         a variable named student_id that has already been assigned a value

Write some code that counts the number of times the value of student_id appears in the incompletes list, and assigns this value to number_of_incompletes. You may use, if you wish, an additional variable, k.

You may use only kincompletesstudent_id, and number_of_incompletes.

Answer:

number_of_incompletes = 0
for k in incompletes:
    if student_id == k:
        number_of_incompletes += 1

 

 

 

Question 3

A list named parking_tickets has been defined to be the number of parking tickets given out by the city police each day since the beginning of the current year. (Thus, the first element of the list contains the number of tickets given on January 1; the last element contains the number of tickets given today.)

Write some code that assigns the largest value found in 
parking_tickets to a variable named most_tickets. You may, if you wish, use one additional variable, k.

Answer:

most_tickets = parking_tickets[0]
for k in parking_tickets:
    if k > most_tickets:
        most_tickets = k

 

 

 

Question 4

Write the definition of a function named sum_list that has one parameter, a list whose elements are of type int. The function returns the sum of the elements of the list as an int.

Answer:

def sum_list(list):
    sum = 0
    for i in list:
        sum += i
    return sum

 

 

 

Checkpoint 7.27

A two-dimensional list is created, as shown below. How many rows and how many columns are in the list?

 

numbers = [[1, 2], [10, 20], [100, 200], [1000, 2000]]

 

a. 4 rows and 2 columns

b. 2 rows and 4 columns

c. 2 rows and 4 columns

d. 4 rows and 4 columns

Answer: a

 

 

 

Checkpoint 7.28

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 7.29

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Live Code Example 7.9

This program creates a two dimensional list to store popular songs (the rows) and their artists (the columns). Type the code into the interface below and where indicated, fill in the two nested loop statements and the print statement to display the expected output.

Expected Output
Bohemian Rhapsody
Queen

Stairway to Heaven
Zeppelin

Imagine
Lennon

Hotel California
Eagles

Sounds of Silence
Simon and Garfunkel

 

import random

 

# Constants for rows and columns

ROWS = 5

COLS = 2

 

def main():

    # Create a two-dimensional list.

    top_songs = [['Bohemian Rhapsody', 'Queen'], ['Stairway to Heaven', 'Zeppelin'], ['Imagine', 'Lennon'],['Hotel California', 'Eagles'],['Sounds of Silence', 'Simon and Garfunkel']]

    # Write a for loop to iterate through the rows.

        # Write a for loop to iterate through the columns.

            # Display the songs and artists.

        print()

   

# Call the main function.

main()

 

Answer:

import random

 

# Constants for rows and columns

ROWS = 5

COLS = 2

 

def main():

    # Create a two-dimensional list.

    top_songs = [['Bohemian Rhapsody', 'Queen'], ['Stairway to Heaven', 'Zeppelin'], ['Imagine', 'Lennon'],['Hotel California', 'Eagles'],['Sounds of Silence', 'Simon and Garfunkel']]

    for r in range(ROWS):

        for c in range(COLS):

            print(top_songs[r][c])

        print()

   

# Call the main function.

main()

 

 

 

Checkpoint 7.30

Processing a tuple is slower than processing a list.

a. True

b. False

Answer: False

Checkpoint 7.31

Tuples are safer than lists.

a. True

b. False

Answer: True

 

 

 

Checkpoint 7.32

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 7.33

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Live Code Example 7.10

In this program, we take the same list of songs and artists and create a tuple from it. Fill in the two commented lines with the missing code to display the expected output.

Expected Output
[['Bohemian Rhapsody', 'Queen'], ['Stairway to Heaven', 'Zeppelin'], ['Imagine', 'Lennon'], ['Hotel California', 'Eagles'], ['Sounds of Silence', 'Simon and Garfunkel']]
(['Bohemian Rhapsody', 'Queen'], ['Stairway to Heaven', 'Zeppelin'], ['Imagine', 'Lennon'], ['Hotel California', 'Eagles'], ['Sounds of Silence', 'Simon and Garfunkel'])

 

# Constants for rows and columns

ROWS = 5

COLS = 2

 

top_songs = [['Bohemian Rhapsody', 'Queen'], ['Stairway to Heaven', 'Zeppelin'], ['Imagine', 'Lennon'],['Hotel California', 'Eagles'],['Sounds of Silence', 'Simon and Garfunkel']]

print (top_songs)

 

Answer:

# Constants for rows and columns

ROWS = 5

COLS = 2

 

top_songs = [['Bohemian Rhapsody', 'Queen'], ['Stairway to Heaven', 'Zeppelin'], ['Imagine', 'Lennon'],['Hotel California', 'Eagles'],['Sounds of Silence', 'Simon and Garfunkel']]

print (top_songs)

 

top_songs_tuple = tuple(top_songs)

print(top_songs_tuple)

 

 

 

Quiz 7.9 (Scored)

 

Question 1

Write a statement that assigns an empty tuple to a variable named t.

Answer:

t = ()

 

 

 

Question 2

Write a statement that assigns to the variable t  a tuple that contains the following elements: 42, 56, 7 .

Answer:

t = (42, 56, 7)

 

 

 

Question 3

Given that t refers to a tuple, write a statement that assigns the value of its first element to k.

Answer:

k = t[0]

 

 

 

Question 4

Assume a variable named t has been assigned a tuple whose elements are numbers. Write some statements that use a while loop to count the number of times the first element of the tuple appears in the rest of the tuple, and assign that number to a variable named repeats. Thus, if the tuple contains (1,6,5,7,1,3,4,1), then repeats would be assigned the value 2 because after the first "1" there are two more "1"s.

Answer:

repeats = 0

if len(t) != 0 :

    i = 1

    while i < len(t):

         if t[i] == t[0]:

             repeats += 1

         i += 1

 

 

 

Checkpoint 7.34

To create a graph with the plot function, you must pass two lists: one holding the X coordinates of the data points, and the other holding the Y coordinates.

a. True

b. False

Answer: True

 

 

 

Checkpoint 7.35

What sort of graph does the plot function produce?

a. pie chart

b. scatterplot

c. line graph

d. bar graph

Answer: c

 

 

 

Checkpoint 7.36

What functions do you use to add labels to the X and Y axes in a graph?

a. lx and ly

b. xaxe and yaxe

c. xcor and ycor

d. xlabel and ylabel

Answer: d

 

 

 

Checkpoint 7.37

You can change the lower and upper limits of the X and Y axes in a graph by calling the ________ functions.

a. xmax and ymax

b. xlim and ylim

c. xmin and ymax

d. ymin and xmax

Answer: b

 

 

 

Checkpoint 7.38

How do you customize the tick marks along the X and Y axes in a graph?

a. Call the ticks function, with two arguments.

b. Call the xticks and yticks functions, with four arguments.

c. Call the xticks and yticks functions, with two arguments.

d. Call the ticks function, with four arguments.

Answer: c

 

 

 

Checkpoint 7.39

To create a bar chart with the bar function, you simply pass the heights of each bar as arguments.

True

False

Answer: False

 

 

 

Checkpoint 7.40

Assume the following statement calls the bar function to construct a bar chart with four bars. What should be placed in the blank to create bars that are red, blue, red, and blue.

 

plt.bar(left_edges, heights, color=(________))

 

a. 'r', 'b', 'r', 'b'

b. red, blue, red, blue

c. 'red', 'blue', 'red', 'blue'

d. r, b, r, b

Answer: a

 

 

 

Checkpoint 7.41

The pie function calculates the sum of the values in the list to determine the whole.

a. True

b. False

Answer: True

 

 

 

Programming Project 1

If you have downloaded this book's source code, you will find the following files in the Chapter 07 folder:

• 
GirlNames.txt--This file contains a list of the 200 most popular names given to girls born in the United States from the year 2000 through 2009.
• 
BoyNames.txt--This file contains a list of the 200 most popular names given to boys born in the United States from the year 2000 through 2009.

Write a program that reads the contents of the two files into two separate lists. Then, the program should allow the user to input either a girl's name, a boy's name, or both, and tell the user whether the name(s) was/were popular between 2000 and 2009.

First, the program should prompt the user to choose a girl's name, a boy's name, or both by entering one of the following:
'girl', 'boy', or 'both'.

Once they have chosen, they should be able to input a name. If the name was a popular name, like Jacob or Sophia, the program should print
Jacob was a popular boy's name between 2000 and 2009."
or
Sophia was a popular girl's name between 2000 and 2009.

If the name was not a popular name, like Voldemort, the program should print
Voldemort was not a popular boy's name between 2000 and 2009.

If the user chooses to input both a girl and boy's name, ask for the boy's name, then the girl's name, and print two statements in the form mentioned above on two separate lines, with the statement about the boy's name coming first. For example, if the user inputs Voldemort and then Sophia, print

Voldemort was not a popular boy's name between 2000 and 2009.
Sophia was a popular girl's name between 2000 and 2009.

Look carefully at the following sample run of the program. In particular, notice the wording of the messages and the placement of spaces, colons, and punctuation. Your program's output must match this.


Sample Run
Enter 'boy', 'girl', or 'both':girl
Enter a girl's name:Emma
Emma was a popular girl's name between 2000 and 2009.

 

Note: To complete this programming project you need to download the book's sample source code from:

https://media.pearsoncmg.com/ph/esm/0media_ecs/gaddis-python/downloads/source-code.zip

 

Answer:

# To test your code, you'll have to get the proper

# GirlNames.txt and BoyName.txt files from the website

 

# Read both files into lists

file = open('BoyNames.txt', 'r')

boyNames = []

for line in file:

    boyNames.append(line[:-1]) # remove newline

file.close()

 

file = open('GirlNames.txt', 'r')

girlNames = []

for line in file:

    girlNames.append(line[:-1])

file.close()

 

# Ask the user whether they want to search a girl's name,

# a boy's name, or both

b = input("Enter 'boy', 'girl', or 'both':")

 

#Determine which parts of the code to use

isBoy = True

isGirl = True

 

if b == 'boy':

    isGirl = False

elif b == 'girl':

    isBoy = False

 

#Boy's name

if isBoy:

    name = input("Enter a boy's name:")

    if name in boyNames:

        print(name + " was a popular boy's name between 2000 and 2009.")

    else:

        print(name + " was not a popular boy's name between 2000 and 2009.")

       

 

#Girl's name

if isGirl:

    name = input("Enter a girl's name:")

    pop = False

 

    if name in girlNames:

        print(name + " was a popular girl's name between 2000 and 2009.")

    else:

        print(name + " was not a popular girl's name between 2000 and 2009.")

 

 

Programming Project 2

A Magic Square is a grid with 3 rows and 3 columns with the following properties:


• The grid contains every number from 1 to 9.
• The sum of each row, each column, and each diagonal all add up to the same number.

This is an example of a Magic Square:
4 9 2
3 5 7
8 1 6

In Python, you can simulate a 3x3 grid using a two-dimensional list. For example, the list corresponding to the grid above would be: 
[[4, 9, 2], [3, 5, 7], [8, 1, 6]]

Write a program that has a function that accepts a two-dimensional list as an argument and returns either
True or False to indicate whether the list is a Magic Square.

The program should test the function by calling it with the following two-dimensional lists as arguments and printing out the results each on a separate line:

[[4, 9, 2], [3, 5, 7], [8, 1, 6]]
[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[4, 9, 2], [3, 5, 5], [8, 1, 6]]

Sample Run
True
True
False
False

 

Answer:

def isMagicSquare(square):
    # [[a, b, c], [d, e, f], [g, h, i]]
   
    #   a  b  c
    #   d  e  f
    #   g  h  i

    # Test:
    # - contains numbers 1 through 9
    # - the sum of every row, column, and diagonal is the same

    # Test whether the numbers 1 through 9 are present.
    # Remove numbers from this list if they are in the square.
    # If there are no numbers left at the end, the square
    # has every number from 1-9.
    nineList = [1, 2, 3, 4, 5, 6, 7, 8, 9]

    for i in range(0, 3):
        for j in range(0, 3):
            for k in nineList:
                if square[i][j] == k:
                    nineList.remove(k)

   
    if nineList!=[]:
        return False

    # Test the sum of the rows, columns, and diagonals.
    a = square[0][0]
    b = square[0][1]
    c = square[0][2]
    d = square[1][0]
    e = square[1][1]
    f = square[1][2]
    g = square[2][0]
    h = square[2][1]
    i = square[2][2]
   
    row0 = a + b + c
    row1 = d + e + f
    row2 = g + h + i

    if row0 != row1 or row1 != row2 or row0 != row2:
        return False

    col0 = a + d + g
    col1 = b + e + h
    col2 = c + f + i

    if col0 != col1 or row1 != col2 or col0 != col2:
        return False

    diag1 = a + e + i
    diag2 = c + e + g

    if diag1 != diag2:
        return False

    if diag1 != row1 != col1:
        return False

    return True

# main function
def main():
    square1 = [[4, 9, 2],[3,5,7],[8,1,6]]
    square2 = [[2, 7, 6], [9, 5, 1], [4, 3, 8]]
    square3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    square4 = [[4, 9, 2], [3, 5, 5], [8, 1, 6]]

    print(isMagicSquare(square1))
    print(isMagicSquare(square2))
    print(isMagicSquare(square3))
    print(isMagicSquare(square4))

 

# Call the main function.

main()

 

 

 

Chapter 8 Solutions

 

 

 

Checkpoint 8.1

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 8.2

What is the index of the first character in a string?

a. 0

b. 1

c. any specified index

Answer: a

 

 

 

Checkpoint 8.3

If a string has 10 characters, what is the index of the last character?

a. 9

b. 10

c. 11

Answer: a

 

 

 

Checkpoint 8.4

An IndexError exception will occur if you try to use an index that is out of range for a particular string.

a. True

b. False

Answer: True

 

 

 

Checkpoint 8.5

Which function will return the length of a string?

a. length

b. len

c. stringlens

Answer: len

 

 

 

Checkpoint 8.6

There is something wrong with this code:

animal = 'Tiger'

animal[0] = 'L'

 

Namely, strings are _________, so the expression _________ cannot appear on the left side of an assignment operator.

a. mutable; animal

b. mutable; animal[0]

c. immutable; animal[0]

d. immutable; animal

Answer: c

 

 

 

Live Code Example 8.1

This haiku is a variant of one of the GNU haiku error messages page (https://www.gnu.org/fun/jokes/error-haiku.html). We've provided the first line in code below, stored in the string variable haiku. Concatenate the two remaining lines to display the expected output.

Expected Output
yesterday it worked
today it is not working
coding is like that

 

haiku = 'yesterday it worked\n'

# Add the second line of the haiku to the string.

# Add the third line of the haiku to the string.

# Print the haiku.

 

Answer:

haiku = 'yesterday it worked\n'

haiku += 'today it is not working\n'

haiku += 'coding is like that\n'

print(haiku)

 

 

 

 

 

Live Code Example 8.2
The program below intends to print a string using a loop, but there is an error. Correct the error to display the expected output.

Expected Output
PyCharm

 

IDE = 'PyCharm'

index = 0

while index < 8:

    print(IDE[index], end = '')

    index += 1

print()

 

Answer:

IDE = 'PyCharm'

index = 0

while index < 7:

    print(IDE[index], end = '')

    index += 1

print()

 

 

 

Live Code Example 8.3

The program below intends to print a string using a loop, and this time, it uses the len function to avoid the potential error in the prior exercise. Use the len function with a while loop to display the expected output.

Expected Output
PyCharm

 

IDE = 'PyCharm'

index = 0

# Write a while loop using len function to print the IDE string

    print(IDE[index], end = '')

    index += 1

 

Answer:

IDE = 'PyCharm'

index = 0

while index < len(IDE):

    print(IDE[index], end = '')

    index += 1

 

 

 

Quiz 8.1 (Scored)

 

Question 1

Write an expression whose value is the character at index 3 of string s.

 

Answer:

s[3]

 

 

 

Question 2

Write an expression whose value is the last character in string s.

 

Answer 1:

s[-1]

Answer 2:
s[6]

 

 

 

Question 3

Write an expression that is the concatenation of the strings "Hello" and "World".

 

Answer:

"Hello" + "World"

 

 

 

Question 4

Write an expression that is the concatenation of two strings s1 and s2.

 

Answer:

s1 + s2

 

 

 

Question 5

Write an expression whose value is the concatenation of the three strigs name1name2, and name3, separated by commas. So if name1name2, and name3, were (respectively) "Neville", "Dean", and "Seamus", your expression's value would be "Neville,Dean,Seamus".

 

Answer:

name1 + "," + name2 + "," + name3

 

 

Checkpoint 8.7

What will the following code display?

 

mystring = 'abcdefg'

print(mystring[2:5])

 

a. cf

b. cdef

c. bcde

d. cde

Answer: d

 

 

 

Checkpoint 8.8

What will the following code display?

 

mystring = 'abcdefg'

print(mystring[3:])

 

a. c

b. d

c. defg

d. abcd

Answer: c

 

 

 

Checkpoint 8.9

What will the following code display?

mystring = 'abcdefg'

print(mystring[:3])

 

a. abc

b. c

c. d

d. defg

Answer: a

 

 

 

Checkpoint 8.10

What will the following code display?

 

mystring = 'abcdefg'

print(mystring[:])

 

a. empty string

b. abcdefg

c. a

d. g

Answer: b

 

 

 

Live Code Example 8.4

This program uses string splicing to extract the last four digits of a credit card number and to display the card's expiration date in the format specified. However, the display is not correct. Correct the errors to match the expected output.

Expected Output
Enter your credit card number: 1212343456567878
Enter the expiration date with two digits for the month and two digits for the year, as in 0921: 0123
The last four digits of your number are 7878
The card expiration date is 01/202

 

card_num = input('Enter your credit card number: ')

exp_date = input('Enter the expiration date with two digits for the month and two digits for the year, as in 0921: ')

 

print('The last four digits of your number are ' + card_num[4:])

print('The card expiration date is ' + exp_date[2:4] + '/20' + exp_date[:-2])

 

Answer:

card_num = input('Enter your credit card number: ')

exp_date = input('Enter the expiration date with two digits for the month and two digits for the year, as in 0921: ')

 

print('The last four digits of your number are ' + card_num[-4:])

print('The card expiration date is ' + exp_date[0:2] + '/20' + exp_date[-2:])

 

 

 

Live Code Example 8.5

This program takes a specific time from user input and displays it in a specified format. The code does not match the expected output as of now. Correct the errors to display the expected output.

Sample Expected Output
Enter the time in the format hours:minutes:seconds, as in 16:30:42: 16:30:42
You entered 16 hours, 30 minutes, and 42 seconds

 

time = input('Enter the time in the format hours:minutes:seconds, as in 16:30:42: ')

print('You entered ' + time[2:] + ' hours ' + time[2:4] + ' minutes ' + time[0:2] + ' seconds ')

 

Answer:

time = input('Enter the time in the format hours:minutes:seconds, as in 16:30:42: ')

print('You entered ' + time[0:2] + ' hours, ' + time[3:5] + ' minutes, and ' + time[-2:] + ' seconds ')

 

 

Quiz 8.2 (Scored)

 

Question 1

Write an expression whose value is the string that consists of the first four characters of string s.

 

Answer:

s[0:4]

 

Question 2

Assume that name is a variable of type string that has been assigned a value. Write an expression whose value is a string containing the first character of the value of name. So if the value of name were "Smith" the expression's value would be "S".

 

Answer:

name[0:1]

 

Question 3

Write an expression whose value is the string consisting of all the characters (starting with the sixth) of string s.

 

Answer:

s[5:]

 

Question 4

Write an expression whose value is the string that consists of the second through fifth characters of string s.

 

Answer:

s[1:5]

 

 

 

 

 

Checkpoint 8.11

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 8.12

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 8.13

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 8.14

What is the output of the following code?

 

ch = 'a'

ch2 = ch.upper()

print(ch, ch2)

 

a. A a

b. A A

c. a a

d. a A

Answer: d

 

 

 

 

 

 

Checkpoint 8.15

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 8.16

What will the following code display?

var = '$'

print(var.upper())

 

a. $

b. #

c. 0

d. 4

Answer: a

 

Checkpoint 8.17

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 8.18

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Checkpoint 8.19

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Live Code Example 8.6

Linus Torvaldes, the creator of Linux, is responsible for the quote below.

Talk is cheap. Show me the code.

We've used it to search for a string, '
code', and then display it in uppercase. It's not quite right, though. Correct the errors to display the expected output.

Expected Output
The word CODE was found.

 

quote = 'Talk is cheap. Show me the code.'

if 'code' in quote:

    print('The word ' + quote[:4].upper + ' was found.')

else:

    print('The word ' + quote[:4].upper + ' was not found.')

 

Answer:

quote = 'Talk is cheap. Show me the code.'

if 'code' in quote:

    print('The word ' + quote[-5:-1].upper() + ' was found.')

else:

    print('The word ' + quote[-5:-1].upper() + ' was not found.')

 

 

 

Live Code Example 8.7

In this program, we'll reference the same quote, but use the find function to locate the index of the beginning of the desired substring. Write the missing line, which will store the index for the first letter of the string 'code' in the variable index.

Expected Output
The word CODE was found at index 27

 

quote = 'Talk is cheap. Show me the code.'

# Fill in the missing code to find the index here.

if index != -1:

    print('The word ' + quote[-4:].upper() + ' was found at index', index)

else:

    print('The word ' + quote[-4:].upper() + ' was not found at index', index)

 

Answer:

quote = 'Talk is cheap. Show me the code.'

index = quote.find('code')

if index != -1:

    print('The word ' + quote[-5:-1].upper() + ' was found at index', index)

else:

    print('The word ' + quote[-5:-1].upper() + ' was not found at index', index)

 

 

 

 

 

Live Code Example 8.8

Website addresses frequently omit the "https://" portion of their URL. In this program, we replace the "www" with "http://www" as good practice. Fill this line, which will use the string's replace function to store the new string in a variable new_url, and then display the expected output.

Expected Output
www.python.org/
https://www.python.org/

 

url = 'www.python.org/'

print(url)

# Create a new string named new_url with 'https://' preceding 'www'.

print(new_url)

 

Answer:

url = 'www.python.org/'

print(url)

new_url = url.replace('www', 'https://www')

print(new_url)

 

 

 

Quiz 8.3 (Scored)

 

Question 1

Write an expression that evaluates to True if string s starts with "p".

 

Answer:

s.startswith("p")

 

 

 

Question 2

Write an expression whose value is True if all the letters in string s are uppercase.

 

Answer 1:

s.isupper()

 

Answer 2:

s.isupper()

 

 

 

 

Question 3

Write an expression that returns True if string s ends with "ism".

 

Answer:

s.endswith("ism")

 

Question 4

Write an expression whose value is True if all the letters in string s are all lowercase.

 

 

 

Answer:

s.islower()

 

Question 5

Assume the variable first is assigned a string that is a person's first name, and the variable last is assigned a string that is a person's last name.

 

Write an expression whose value is a string that is the person's full name in the form "Last, First". So, if first is assigned "alan" and last is assigned  "turing", then your expression's value would be "Turing,Alan". (Note the capitalization! Note: no spaces!) And if first and last were "Florean" and "fortescue" respectively, then your expression's value would be "Fortescue,Florean".

 

Answer:

last[0].upper() + last[1:] + "," + first[0].upper() + first[1:]

 

 

 

Chapter 8: Programming Project 1 (Scored)

 

Question 1

Many companies use telephone numbers like 555-GET-FOOD so the number is easier for their customers to remember. On a standard telephone, the alphabetic letters are mapped to numbers in the following fashion:

A, B, C: 2
D, E, F: 3
G, H, I: 4
J, K, L: 5
M, N, O: 6
P, Q, R, S: 7
T, U, V: 8
W, X, Y, Z: 9

Write a program that asks the user to enter a 10-character telephone number in the format XXX-XXX-XXXX. The application should display the telephone number with any alphabetic characters that appeared in the original translated to their numeric equivalent.

 

Look carefully at the following sample run of the program. In particular, notice the wording of the prompt and the placement of spaces and punctuation. Your program's output must match this.


Sample Run (User input shown in bold)

Enter a phone number to be translated:555-GET-FOOD
555-438-3663

 

Answer:

 

def replace(num):

    if num == 'A' or num == 'B' or num == 'C':

        return '2'

    elif num == 'D' or num == 'E' or num == 'F':

        return '3'

    elif num == 'G' or num == 'H' or num == 'I':

        return '4'

    elif num == 'J' or num == 'K' or num == 'L':

        return '5'

    elif num == 'M' or num == 'N' or num == 'O':

        return '6'

    elif num == 'P' or num == 'Q' or num == 'R' or num == 'S':

        return '7'

    elif num == 'T' or num == 'U' or num == 'V':

        return '8'

    elif num == 'W' or num == 'X' or num == 'Y' or num == 'Z':

        return '9'

    else:

        return num

 

def main():

    phoneNumber = input('Enter a phone number to be translated:')

 

    for i in range(0, len(phoneNumber)):

        phoneNumber = phoneNumber[:i]+replace(phoneNumber[i])+phoneNumber[i+1:]

       

    print(phoneNumber)

 

# Call the main function.

main()

 

 

 

 

 

Chapter 8: Programming Project 2 (Scored)

 

Question 1

Write a program with a function that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized. The program should let the user enter a string and then pass it to the function, printing out the modified string.

 

Look carefully at the following sample run of the program. In particular, notice the wording of the prompt and the placement of spaces and punctuation. Your program's output must match this.


Sample Run (User input shown in bold)
Enter sentence to be capitalized:hello. my name is Joe. what is your name?
Hello. My name is Joe. What is your name?

 

Answer:

 

def capitalize(sentence):

    for i in range(0, len(sentence)):

        if i == 0:

            sentence = sentence[i].upper() + sentence[1:]

        elif sentence[i] == "." and i != len(sentence)-1:

            sentence = sentence[:i+2] + sentence[i+2].upper() + sentence[i+3:]

    return sentence

 

def main():

    sentence = input('Enter sentence to be capitalized:')

    print(capitalize(sentence))

 

# Call the main function.

main()

 

 

 

 

Chapter 9 Solutions

 

 

 

Checkpoint 9.1

An element in a dictionary has two parts. What are they called?

a. key and def

b. id and link

c. id and key

d. key and value

Answer: d

 

 

 

Checkpoint 9.2

Which part of a dictionary element must be immutable?

a. the key

b. the value

Answer: a

 

 

 

Checkpoint 9.3

Suppose 'start' : 1472 is an element in a dictionary.

_________ is the key, and _________ is the value.

a. 'start'; 1472

b. 1472; 'start'

c. ‘1472’; start

d. 'tart; ‘1472’

Answer: a

 

 

 

Checkpoint 9.4

Suppose a dictionary named employee has been created, and an assignment has been made as follows.

employee['id'] = 54321

 

Which key-value pair has been stored in the dictionary?

a. 'employee' : 54321

b. 'id' : employee

c. 'id' : 54321

d. employee : 54321

Answer: c

 

 

Checkpoint 9.5

What will the following code display?

 

stuff = {1 : 'aaa', 2 : 'bbb', 3 : 'ccc'}

print(stuff[3])

 

a. aaabbbccc

b. c

c. bbbccc

d. ccc

Answer: d

 

 

 

Checkpoint 9.6

To determine whether a key-value pair exists in a dictionary, use the __________ operator.

a. pair

b. in

c. find

d. exists

Answer: b

 

Checkpoint 9.7

Suppose a dictionary named inventory exists. The statement below will delete the element that has the key 654.

 

del inventory[654]

 

a. True

b. False

Answer: True

 

 

 

Checkpoint 9.8

What will the following code display?

 

stuff = {1 : 'aaa', 2 : 'bbb', 3 : 'ccc'}

print(len(stuff))

 

a. 0

b. 1

c. 2

d. 3

Answer: d

 

 

Checkpoint 9.9

What will the following code display?

 

stuff = {1 : 'aaa', 2 : 'bbb', 3 : 'ccc'}

for k in stuff:

    print(k)

 

a.

1

2

3

b.

ccc

c.

aaa

bbb

ccc

d.

3

Answer: a

 

 

 

Checkpoint 9.10

The pop method returns a randomly selected key-value pair, as a tuple,

and removes that key-value pair from the dictionary.

a. True

b. False

Answer: False

 

 

 

Checkpoint 9.11

The items method returns all a dictionary’s keys and their associated values as a __________.

a. sequence of tuples

b. sorted list

c. set of two lists

d. key map

Answer: a

 

 

 

Checkpoint 9.12

The keys method returns __________.

a. one value in a dictionary

b. all the values in a dictionary

c. one key at a specified index

d. all the keys in a dictionary

Answer: d

 

 

 

Checkpoint 9.13

The ________ method return all the values in the dictionary as a sequence of tuples.

a. values

b. keys

c. map

d. index    

Answer: a

 

 

 

 

Checkpoint 9.14

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

 

Quiz 9.1 (Scored)

 

Question 1

Write a statement that assigns the variable d a dictionary that contains one element. The element's key should be the string 'answer' and the element's value should be the integer 42.

 

Answer:

d = {'answer': 42}

 

 

 

Question 2

Assume that d refers to a dictionary. Write an expression that retrieves from the dictionary the value that is associated with the key 'answer'.

 

Answer:

d['answer']

 

Question 3

Assume that d refers to a dictionary. Write a statement that assigns the value 'Python' to the key 'Monty'.

 

Answer:

d['Monty'] = 'Python'

 

 

 

Question 4

Assume there is a variable, album_artists, that refers to a dictionary that maps albums to performing artists. Write a statement that inserts the key/value pair: 'Live It Out' / 'Metric'.

 

Answer:

album_artists['Live It Out'] = 'Metric'

 

 

 

Question 5

Assume the variable us_cabinet refers to a dictionary that maps department names to department heads. Write a statement that assigns the value 'Mukasey' to the key 'Justice Department'.

 

Answer:

us_cabinet['Justice Department'] = 'Mukasey'

 

 

 

Question 6

Assume the variable planet_distances refers to a dictionary that maps planet names to planetary distances from the sun. Write a statement that deletes the element with the key 'Pluto'.

 

Answer:

del planet_distances['Pluto']

 

 

 

Question 7

Assume three dictionaries are assigned to the variables, canadian_capitalsmexican_capitals, and us_capitals. These dictionaries map provinces or states to their respective capitals. Write code that creates a new dictionary that combines these three dictionaries, and associate it with a variabl named nafta_capitals.

 

Answer:

nafta_capitals = {}

for key in us_capitals :

    nafta_capitals[key] = us_capitals[key]

for key in canadian_capitals :

    nafta_capitals[key] = canadian_capitals[key]

for key in mexican_capitals :

    nafta_capitals[key] = mexican_capitals[key]

 

Question 8

Given a dictionary d, create a new dictionary that reverses the keys and values of d. Thus, the keys of d become the values of the new dictionary and the values of d become the keys of the new dictionary. You may assume d contains no duplicate values (that is, no two keys map to the same values.) Associate the new dictionary with the variable inverse.

 

Answer:

inverse = {}

for key in d.keys() :

    val = d[key]

    inverse[val] = key

 

 

 

Question 9

Given the dictionary, d, find the largest key in the dictionary and assign its value to the variable val_of_max. For example, given the dictionary {5:3, 4:1, 12:2}, the value 2 would be assigned to val_of_max. Assume d is not empty.

 

 

Answer:

maxKey = list(d.keys())[0]

for k in d.keys() :

    if k > maxKey :

         maxKey = k

val_of_max = d[maxKey]

 

 

 

Question 10

Create a dictionary that maps the first n counting numbers to their squares. Assign the dictionary to the variable squares.

 

Answer 1:

squares = {}

for i in range(1, n+1) :

    squares[i] = i * i

 

Answer 2:

squares = dict([(i, i*i) for i in range(1, n+1)])

 

 

 

 

Question 11

Assume you have two lists named list1 and list2 that are of the same length. Create a dictionary in which the elements of list1 are the keys and the elements of list2 are the values. For example, the dictionary will have:

·         an element in which list1[0] is the key and list2[0] is the value,

·         an element in which list1[1] is the key and list2[1] is the value,

·         and so on.

 

Answer 1:

dict1 = {}

for i in range(len(list1)) :

    dict1[list1[i]] = list2[i]

 

Answer 2:

 

Checkpoint 9.15

The elements of a set are ordered.

a. True

b. False

Answer: False

 

 

 

Checkpoint 9.16

A set does not allow you to store duplicate elements.

a. True

b. False

Answer: True

 

 

 

Checkpoint 9.17

You can create an empty set with the built-in _________ function.

a. create

b. set

c. init

d. build

Answer: b

 

 

 

Checkpoint 9.18

After the following statement executes, think about what elements will be stored in the

myset set.

myset = set('Jupiter')

 

True or False: The set will contain these elements: 'J', 'u', 'p', 'i', 't', 'e', and 'r'.

a. True

b. False

Answer: True

 

 

 

Checkpoint 9.19

After the following statement executes, what elements will be stored in the myset set?

myset = set(25)

 

a. The set will contain all 25 elements.

b. The set will contain one element: 25.

c. The set will contain the value at the 25th indexed location.

Answer: b

 

 

 

Checkpoint 9.20

After the following statement executes, what elements might be stored in the myset set?

 

myset = set('www xxx yyy zzz')

 

a. ‘z’, ‘x’, ‘y’, ‘w’

b.'ww’,  ‘xx’, ‘yy’,  ‘zz'

c. 'www xxx yyy zzz'

d. ‘zyxw’, ‘zyxw’, ‘zyxw’

Answer: a

 

 

 

Checkpoint 9.21

After the following statement executes, what elements will be stored in the myset set?

 

myset = set([1, 2, 2, 3, 4, 4, 4])

 

a. The set will contain these elements (in no particular order): 1, 22, 3, and 444.

b. The set will contain these elements in this order: 1, 2, 3, and 4.

c. The set will contain these elements (in no particular order): 1, 2, 3, and 4.

d. The set will contain these elements in this order: 1, 22, 3, and 444.

Answer: c

 

Checkpoint 9.22

After the following statement executes, what element might be stored in the myset set?

 

myset = set(['www', 'xxx', 'yyy', 'zzz'])

 

a. ‘x’

b. ‘zz’

c. ‘yyy’

d. ‘xyz’

Answer: c

 

 

 

Checkpoint 9.23

How do you determine the number of elements in a set?

 

a. You sort the set  and then run a nodup function.

b. You use the built-in len function within the set.

c. You pass the set as an argument to the len function.

d. You pass the elements of the set to the len function.

Answer: c

 

 

 

Checkpoint 9.24

After the following statement executes, what elements will be stored in the myset set?

 

myset = set([10, 9, 8])

myset.update([1, 2, 3])

 

a. The set will contain these elements (in no particular order): 10, 9, 8, 1, 2, and 3.

b. The set will contain these elements (in no particular order): 1, 2, and 3.

Answer: a

 

 

 

Checkpoint 9.25

If a specified element to delete is not in a set, the remove method raises a KeyError exception, but the discard method will not raise such an exception.

a. True

b. False

Answer: True

 

 

 

Checkpoint 9.26

After the following code executes, what elements will be members of set3?

 

set1 = set([10, 20, 30])

set2 = set([100, 200, 300])

set3 = set1.union(set2)

 

a. {10, 20, 30, 100, 200, 300}

b. {}

c. {10, 20, 30}

d. {100, 200, 300}

Answer: a

 

 

 

Checkpoint 9.27

After the following code executes, what elements will be members of set3?

 

set1 = set([1, 2, 3, 4])

set2 = set([3, 4, 5, 6])

set3 = set1.intersection(set2)

 

a. {1, 2, 3, 4, 5, 6}

b. {}

c. {1, 2, 5, 6}

d. {3, 4}

Answer: d

 

 

 

Checkpoint 9.28

After the following code executes, what elements will be members of set3?

 

set1 = set([1, 2, 3, 4])

set2 = set([3, 4, 5, 6])

set3 = set1.difference(set2)

 

a.{1, 2, 3, 4}

b. {5, 6}

c. {1, 2}

d. {3, 4, 5, 6}

Answer: c

 

 

 

 

Checkpoint 9.29

After the following code executes, what elements will be members of set3?

 

set1 = set([1, 2, 3, 4])

set2 = set([3, 4, 5, 6])

set3 = set2.difference(set1)

 

a.{1, 2, 3, 4}

b. {5, 6}

c. {1, 2}

d. . {3, 4, 5, 6}

Answer: b

 

 

 

Checkpoint 9.30

After the following code executes, what elements will be members of set3?

 

set1 = set(['a', 'b', 'c'])

set2 = set(['b', 'c', 'd'])

set3 = set1.symmetric_difference(set2)

 

a. {‘d’}

b. {'a'}

c. {'b', 'c'}

d. {'a', 'd'}

Answer: d

 

 

 

Checkpoint 9.31

Consider the following code:

 

set1 = set([1, 2, 3, 4])

set2 = set([2, 3])

 

Which set is a superset and which is a subset?

 

a. set1 is a subset of set2, and set2 is a superset of set1.

b. set2 is a subset of set1, and set1 is a superset of set2.

c. Both set1 and set2 are supersets.

d. Both set1 and set2 are subsets.

Answer: b

 

 

 

 

 

Checkpoint 9.32

Every embedded activity in Revel is designed to support and deepen student learning. However, this Checkpoint item did not deliver the intended learning experience and has therefore been removed. A revised version of this Checkpoint may appear in the next product release.

 

Quiz 9.2 (Scored)

 

Question 1

Write a statement that assigns an empty set to the variable s.

 

Answer:

s = set()

 

 

 

Question 2

Write a statement that assigns s to a set that contains the following elements: 23, 42, -11, 89.

 

Answer:

s = set([23,42,-11,89])

 

 

 

Question 3

Given that s refers to a set, write a statement that adds integer 42 to the set.

 

Answer:

s.add(42)

 

 

 

Question 4

Given that s refers to a set, write a statement that removes integer 5 from the set.

 

Answer:

s.remove(5)

 

 

 

Question 5

Given that s refers to a set, write a statement that attempts to remove integer 11 from the set, but will do nothing if 11 is not in the set.

 

Answer:

s.discard(11)

 

 

 

Question 6

Assume the variable line refers to a string. Write code that creates a set of all the vowels in line. Assign the set to the variable vowels.

 

Answer:

vowels = set()

for c in line :

    if "aeiou".find(c) >= 0 :

         vowels.add(c)

 

vowels = set(c for c in line if "aeiou".find(c) >= 0)

 

 

 

Question 7

Remove the smallest element from the set, s. Assume the set is not empty.

 

Answer:

min = None

for e in s :

    if min == None or e < min :

        min = e

s.remove(min)

 

Question 8

Assume the variable s has been assigned a value, and the variable the_set refers to a set. Write an expression that whose value is True if the value that is referenced by s is in the_set.

 

Answer:

s in the_set

 

 

 

Checkpoint 9.33

Object serialization is the process of converting the object to a stream of ________ that can be saved to

a file for later retrieval.

a. symbols

b. characters

c. bytes

d. keys

Answer: c

 

 

 

Checkpoint 9.34

When you open a file for the purpose of saving a pickled object to it, what file access mode would you use?

a. 'wb'

b. 'rb'

c. 'gb'

d. 'eb'

Answer: a

 

 

 

 

Checkpoint 9.35

When you open a file for the purpose of retrieving a pickled object from it, what file access mode would you use?

a. 'wb'

b. 'rb'

c. 'gb'

d. 'eb'

Answer: b

 

 

 

Checkpoint 9.36

You need to import the pickle module if you want to pickle objects.

a. True

b. False

Answer: True

 

 

 

Checkpoint 9.37

What function can you call to pickle an object?

a. pickle.get

b. pickle.init

c. pickle.load

d. pickle.dump

Answer: d

 

 

 

Checkpoint 9.38

What function can you call to retrieve and unpickle an object?

a. pickle.get

b. pickle.init

c. pickle.load

d. pickle.dump

Answer: c

 

 

 

Chapter 9: Programming Project 1

 

Write a program that creates a directory containing course numbers and the room numbers of the rooms where the courses meet. The dictionary should have the following key-value pairs:

Course Number (key)

Room Number (value)

CS101

3004

CS102

4501

CS103

6755

NT110

1244

CM241

1411

 

The program should also create a dictionary containing course numbers and the names of the instructors that teach each course. The dictionary should have the following key-value pairs:

Course Number (key)

Instructor (value)

CS101

Haynes

CS102

Alvarado

CS103

Rich

NT110

Burke

CM241

Lee


The program should also create a dictionary containing course numbers and the meeting times of each course. The dictionary should have the following key-value pairs:

Course Number (key)

Meeting Time (value)

CS101

8:00am

CS102

9:00am

CS103

10:00am

NT110

11:00am

CM241

1:00pm


The program should let the user enter a course number, and then it should display
the course's room number, instructor, and meeting time.

 

Look carefully at the following sample run of the program. In particular, notice the wording of the messages and the placement of spaces, colons, and punctuation. Your program's output must match this.


Sample Run (User input shown in bold)
Enter a class name:CS101
Class: CS101
Room: 3004
Instructor: Haynes
Time: 8:00am

 

Answer:

roomNumber = {'CS101':'3004', 'CS102':'4501', 'CS103':'6755', 'NT110':'1244', 'CM241':'1411'}

instructor = {'CS101':'Haynes', 'CS102':'Alvarado', 'CS103':'Rich', 'NT110':'Burke', 'CM241':'Lee'}

meetingTime = {'CS101':'8:00am', 'CS102':'9:00am', 'CS103':'10:00am', 'NT110':'11:00am', 'CM241':'1:00pm'}

 

className = input("Enter a class name:")

 

print("Class: " + className)

print("Room: " + roomNumber[className])

print("Instructor: " + instructor[className])

print("Time: " + meetingTime[className])

 

 

 

 

 

 

 

Chapter 9: Programming Project 2

[This is a replacement MPL Exercise. ID: 345893-00446, in course #85277]

Write a function named count_vowels that accepts two arguments: a string and an empty dictionary. The function should count the number of times each vowel (the letters a, e, i, o, and u) appears in the string, and use the dictionary to store those counts. When the function ends, the dictionary should have exactly 5 elements. In each element, the key will be a vowel (lowercase) and the value will be the number of times the vowel appears in the string. 

For example, if the string argument is 'Now is the time', the function will store the following elements in the dictionary:

·         'a': 0

·         'e': 2

·         'i': 2

·         'o': 1

·         'u': 0 

The function should not return a value.

 

Answer:

def count_vowels(text, vowels):

    # Create the elements for the vowels.

    vowels['a'] = 0

    vowels['e'] = 0

    vowels['i'] = 0

    vowels['o'] = 0

    vowels['u'] = 0

 

    # Iterate over each character as lowercase.

    for ch in text.lower():

        # Is this character a vowel?

        if ch =='a' or ch == 'e' or ch == 'i' or \

           ch == 'o' or ch == 'u':

           vowels[ch] += 1

 

 

 

 

Chapter 10 Solutions

 

 

Checkpoint 10.1

An object is a software entity that contains ________.

a. only data

b. only procedures

c. both data and procedures

d. neither data or procedures

Answer: c

 

 

 

Checkpoint 10.2

The combining of data and code into a single object is known as ___________.

a. encapsulation

b. identification

c. labeling

d. typing

Answer: a

 

 

 

Checkpoint 10.3

When an object's internal data is hidden from outside code and access to that data is restricted to the object’s methods, the data can be _________.

a. copied and modified  remotely

b. shared across freely across objects

c. protected from accidental corruption

d. inaccessible to even the object’s methods

Answer: c

 

 

 

Checkpoint 10.4

Public methods cannot be accessed by entities outside an object.

a. True

b. False

Answer: False

 

 

 

Checkpoint 10.5

You hear someone make the following comment: “A blueprint is a design for a house. A carpenter can use the blueprint to build the house. If the carpenter wishes, he or she can build several identical houses from the same blueprint.” Think of this as a metaphor for classes and objects. Does the blueprint represent a class, or does it represent an object?

 

a. The metaphor of a blueprint represents a class.

b. The metaphor of a blueprint represents an object.

Answer: a

 

 

 

 

Checkpoint 10.6

In this chapter, we use the metaphor of a cookie cutter and cookies that are made from the cookie cutter to describe classes and objects. In this metaphor, are objects the cookie cutter, or the cookies?

a. Objects are the cookie cutters.

b. Objects are the cookies.

Answer: b

 

 

 

Checkpoint 10.7

What is the main purpose of the _ _init_ _ method?

a. Initiate communication with other methods.

b. Start a driver program for the method.

c. Schedule code execution testing.

d. Initialize an object’s data attributes.

Answer: d

 

 

 

Checkpoint 10.8

When a method is called, Python automatically makes its ________ parameter reference the specific object that the method is supposed to operate on.

a. my

b. this

c. self

d. object

Answer: c

 

 

 

Checkpoint 10.9

In a Python class, you can hide an attribute from code outside the class by starting the attribute’s name with __________.

a. an ampersand (&)

b. an exclamation point (!)

c. two comment tags (##)

d. two underscores (_ _)

Answer: d

 

 

 

Checkpoint 10.10

What is the purpose of the _ _str_ _ method?

a. It returns a string representation of the object.

b. It converts a string into an object equivalent.

c. It designates a string key for the object.

d. It allocates space for any object lists. 

Answer: a

 

 

 

Checkpoint 10.11

You call the _ _str_ _ method by passing the object to the built-in ________ method

a. string

b. str

c. convert

d. con

Answer: b

 

 

 

Live Code Example 10.1

This program creates a class called Techie with three attributes. The main function instantiates a Techie, but the declaration statement contains an error. Correct the error to display the expected ouput.

Expected Output
Alexis Martinez
Web Application Programmer

 

class Techie:

  def __init__(self, first_name, last_name, job_title):

    self.first = first_name

    self.last = last_name

    self.title = job_title

   

  # create a function to return the Person's first name    

  def get_first(self):

    return self.first

   

  # create a function to return the Person's last name    

  def get_last(self):

    return self.last

   

  # create a function to return the Person's profession    

  def get_title(self):

    return self.title

 

def main():

    # Correct the statement below.

    techie = Techie(self, 'Alexis', 'Martinez', 'Web Application Programmer')

    print(techie.get_first(), '', end ='')

    print(techie.get_last())

    print(techie.get_title())

 

Answer:

class Techie:

  def __init__(self, first_name, last_name, job_title):

    self.first = first_name

    self.last = last_name

    self.title = job_title

   

  # create a function to return the Person's first name    

  def get_first(self):

    return self.first

   

  # create a function to return the Person's last name    

  def get_last(self):

    return self.last

   

  # create a function to return the Person's profession    

  def get_title(self):

    return self.title

 

def main():

    techie = Techie('Alexis', 'Martinez', 'Web Application Programmer')

    print(techie.get_first(), '', end ='')

    print(techie.get_last())

    print(techie.get_title())

   

main()

 

 

 

 

 

Quiz 10.2 (Scored)

 

Question 1

Write the definition of a class named WeatherForecast that has the following methods:

• An 
__init__ method that initializes the following attribute variables:
An attribute variable named 
skies should be assigned an empty string.
An attribute variable named 
high should be assigned the value 0.
An attribute variable named 
low should be assigned the value 0.

• A method named 
set_skies that accepts an argument that should be assigned to the attribute variable skies.

• A method named 
set_high that accepts an argument that should be assigned to the attribute variable high.

• A method named 
set_low that accepts an argument that should be assigned to the attribute variable low.

• A method named 
get_skies that accepts no arguments, and returns the value of the skies attribute.

• A method named 
get_high that accepts no arguments, and returns the value of the high attribute.

• A method named 
get_low that accepts no arguments, and returns the value of the low attribute.

 

Answer:

class WeatherForecast:

    def __init__(self):

        self.skies = ''

        self.high = 0

        self.low = 0

 

    def set_skies(self, skies):

        self.skies = skies

 

    def set_high(self, high):

        self.high = high

 

    def set_low(self, low):

        self.low = low

 

    def get_skies(self):

        return self.skies

 

    def get_high(self):

        return self.high

 

    def get_low(self):

        return self.low

 

 

Question 2

 

Write the definition of a class Player that has the following methods:

·         An  __init__ method that initializes the following attribute variables:

o    An attribute variable named name, initialized to the empty string.

o    An attribute variable named score, initialized to the value 0.

·         A method named set_name that accepts one argument that is assigned to the attribute variable name.

·         A method named set_score that accepts one argument that is assigned to the attribute variable score.

·         A method named get_name that accepts no arguments, and returns the value of the attribute variable name.

·         A method named get_score that accepts no arguments, and returns the value of the attribute variable score.

 

Answer:

class Player:

    def __init__(self):

       self.name = ''

       self.score = 0

 

    def set_score(self, score):

        self.score = score

 

    def set_name(self, name):

        self.name = name

 

    def get_score(self):

        return self.score

       

    def get_name(self):

        return self.name

 

 

Question 3

Suppose there is a class named AirConditioner. The class supports the following behaviors:

 

·         turning the air conditioner on

·         turning the air conditioner off

The class has a method named turn_on that turns the air conditioner on, and a method named turn_off that turns the air conditioner off. Both methods accept no arguments and return no value.

 

There is a variable named my_ac that refers to an AirConditioner object. Write a statement that calls the correct method to turn the air conditioner on.

 

Answer:

my_ac.turn_on()

 

 

 

Question 4

Suppose there is a class named AirConditioner. The class supports the following behaviors:

 

·         turning the air conditioner on

·         turning the air conditioner off

The class has a method named turn_on that turns the air conditioner on, and a method named turn_off that turns the air conditioner off. Both methods accept no arguments and return no value.

 

There is a variable named my_ac that refers to an AirConditioner object. Write a statement that calls the correct method to turn the air conditioner off.

 

Answer:

my_ac.turn_off()

 

 

 

Question 5

Suppose there is a class named AirConditioner. The class supports the following behaviors:

 

·         turning the air conditioner on

·         turning the air conditioner off

·         setting the desired temperature

 

 

The class has a method named turn_on that turns the air conditioner on, and a method named turn_off that turns the air conditioner off. Both methods accept no arguments and return no value. The class also has a method named set_temp, which accepts the desired temperature as an int argument and returns no value.

 

There is a variable named my_ac that refers to an AirConditioner object. Write a statement that calls the correct method to set the air conditioner to 72 degrees.

 

Answer:

my_ac.set_temp(72)

 

 

 

Question 6

Suppose there is a class named AirConditioner. The class supports the following behaviors:

 

·         turning the air conditioner on

·         turning the air conditioner off

The class has a method named turn_on that turns the air conditioner on, and a method named turn_off that turns the air conditioner off. Both methods accept no arguments and return no value.

 

Write a statement that creates a new AirConditioner object, assigning it to a variable named office_a_c. Then, write another statement that uses the new object to turn on the air conditioner.

 

Answer:

office_a_c = AirConditioner()
office_a_c.turn_on()

 

 

 

Checkpoint 10.12

A(n) ________ attribute belongs to a specific instance of a class.

a. class

b. instance

c. global

d. child

Answer: b

 

 

 

 

Checkpoint 10.13

A program creates 10 instances of the Coin class. How many _ _sideup

attributes exist in memory?

a. 0

b. 1

c. 10

Answer: c

 

 

 

Checkpoint 10.14

A method that returns a value from a class’s attribute but does not change it is known as a(n) ________ method. A method that stores a value in a data attribute or changes the value of a data attribute in some other way is known as a(n) _________ method.

a. accessor; mutator

b. mutator; accessor

Answer: a

 

 

 

Live Code Example 10.2


This program creates a list of 
Techie objects. Most of the code has been provided to you. Your job is to create each techie instance and add it to the techie_list. Type the code into the interface below and fill in the two commented lines with the missing code to display the expected output.

Expected Output
Enter data for two persons.
Enter the first name: Alexis
Enter the last name: Martinez
Enter the job title: Web Application Programmer

Enter the first name: Harris
Enter the last name: LeBlanc
Enter the job title: Pen Tester

Alexis Martinez
Web Application Programmer

Harris LeBlanc
Pen Tester

 

class Techie:

  def __init__(self, first_name, last_name, job_title):

    self.first = first_name

    self.last = last_name

    self.title = job_title

   

  # create a function to return the Person's first name    

  def get_first(self):

    return self.first

   

  # create a function to return the Person's last name    

  def get_last(self):

    return self.last

   

  # create a function to return the Person's profession    

  def get_title(self):

    return self.title

 

def main():

    techie_list = []

    print('Enter data for two persons.')

    for count in range(1, 3):

        fname = input('Enter the first name: ')

        lname = input('Enter the last name: ')

        job = input('Enter the job title: ')

        print()

       

        # Instantiate a techie object of type Techie

        # Add the techie object to the techie_list   

              

    for techie in techie_list:

        print(techie.get_first(), '', end ='')

        print(techie.get_last())

        print(techie.get_title())

        print()

       

main()

 

Answer:

class Techie:

  def __init__(self, first_name, last_name, job_title):

    self.first = first_name

    self.last = last_name

    self.title = job_title

   

  # create a function to return the Person's first name    

  def get_first(self):

    return self.first

   

  # create a function to return the Person's last name    

  def get_last(self):

    return self.last

   

  # create a function to return the Person's profession    

  def get_title(self):

    return self.title

 

def main():

    techie_list = []

    print('Enter data for two persons.')

    for count in range(1, 3):

        fname = input('Enter the first name: ')

        lname = input('Enter the last name: ')

        job = input('Enter the job title: ')

        print()

       

        techie = Techie(fname, lname, job)

        techie_list.append(techie)

       

    for techie in techie_list:

        print(techie.get_first(), '', end ='')

        print(techie.get_last())

        print(techie.get_title())

        print()

       

main()

 

 

 

Quiz 10.3 (Scored)

 

Question 1

Suppose there is a class named Alarm. The Alarm class has the following two attribute variables:

 

·         An attribute variable named code which is assigned a string containing the code that deactivates the alarm

·         An attribute variable named armed which is set to True if the alarm is activated, or False if the alarm is not activated.

The Alarm class has a method named disarm that accepts one argument: a string containing a deactivation code. It the argument matches the value of the code attribute variable, the disarm  method changes the value of the armed attribute variable to False.

 

Assume a variable named myAlarm refers to an Alarm object. Write a statement that calls the disarm method, passing the code '93478' as an argument.

 

Answer:

myAlarm.disarm('93478')

 

 

 

Question 2

Suppose there is a class named Alarm. The Alarm class has the following two attribute variables:

 

·         An attribute variable named code which is assigned a string containing the code that deactivates the alarm

·         An attribute variable named armed which is set to True if the alarm is activated, or False if the alarm is not activated.

 


The
Alarm class has a method named changeCode that accepts two string arguments, the first containing the current code, and the second containing the new code. If the first argument matches the current code correctly, the value of code is changed to that of the new code.

 

Assume a variable named myAlarm refers to an Alarm object whose current code is "3456". Write a statement that calls the changeCode  method, changing the code to "7921".

 

Answer:

myAlarm.changeCode('3456', '7921')

 

 

 

Question 3

Write a class named Calculator that has the following:

·         a method named add that takes two arguments that are assumed to be numbers, and returns their sum

·         a method named subtract that takes two arguments that are assumed to be numbers, and returns their difference (subtract the second from the first)

·         a method named multiply that takes two arguments that are assumed to be numbers, and returns their product

·         a method named divide that takes two arguments that are assumed to be numbers, and returns the value of the first divided by the second. If the second number is a zero, do not divide, and return "You can't divide by zero!"

 

Answer:

class Calculator:

    def add(self, num1, num2):

         return num1 + num2

 

    def subtract(self, num1, num2):

         return num1 - num2

 

    def multiply(self, num1, num2):

         return num1 * num2

 

    def divide(self, num1, num2):

         if num2 == 0:

             return "You can't divide by zero!"

         else:

             return num1 / num2

 

 

 

Checkpoint 10.15

The typical UML diagram for a class has three sections. Indicate the correct section in the statements below.

 

The ________ section holds a list of the class’s fields.

The ________ section holds a list of the class’s methods.

The ________ section is where you write the name of the class.

 

a. top; middle; bottom

b. middle; bottom; top

c. bottom; top; middle

d. top; bottom; middle

Answer: b

 

 

 

Checkpoint 10.16

A problem _________ is a written description of the real-world objects, parties, and major events

related to the problem.

a. solution

b. proposal

c. category

d. domain

Answer: d

 

 

 

Checkpoint 10.17

If you do not thoroughly understand the nature of a problem, you should have an expert write the problem domain description for you.

a. True

b. False

Answer: True

 

 

 

Checkpoint 10.18

What is the first step in identifying the potential classes in a problem domain description?

a. List items that represent simple values that can be stored in variables.

b. Filter items that represent objects instead of classes.

c. Refine the list to eliminate duplicates.

d. Identify the nouns and pronouns in the problem domain description.

Answer: d

 

 

 

Checkpoint 10.19

A class’s responsibilities include the things that the class is responsible for _________ and the actions that the class is responsible for _________.

a. propagating; analyzing

b. knowing; doing

c. planning; revising

d. managing; implementing

Answer: b

 

 

 

Checkpoint 10.20

A class’s actions must be explicitly mentioned in the problem domain description.

a. True

b. False

Answer: False

 

 

 

Live Code Example 10.3

The program creates two Movie objects that are randomly assigned the attribute 'drama' or 'comedy'. To determine a preference for movie_01 or movie_02, the movie_01 object calls the find_alternate function with movie_02 as an argument. Fill in the last half of the find_alternate function.

Expected Output
The first movie is a comedy
The second movie is a drama

 

import random

 

class Movie:

    def __init__(self):

        if random.randint(0, 1) == 0:

           self.genre = 'drama'

        else:

           self.genre = 'comedy'

 

    #The alternate function displays both movie options

    def find_alternate(mov_01, mov_02):

        if mov_01.genre == 'drama':

            print('The first movie is a drama')

        else:

            print('The first movie is a comedy')

        

       # Add similar mov_02 code here

      

def main():

        # Create two Movie objects

        movie_01 = Movie()

        movie_02 = Movie()

 

        # Pass the second Movie object as an argument to the alternate function

        movie_01.find_alternate(movie_02)

       

# Call the main function.

main()

 

Answer:

import random

 

class Movie:

    def __init__(self):

        if random.randint(0, 1) == 0:

           self.genre = 'drama'

        else:

           self.genre = 'comedy'

 

    #The alternate function displays both movie options

    def find_alternate(mov_01, mov_02):

        if mov_01.genre == 'drama':

            print('The first movie is a drama')

        else:

            print('The first movie is a comedy')

        

        if mov_02.genre == 'drama':

            print('The second movie is a drama')

        else:

            print('The second movie is a comedy')

 

 

def main():

        # Create two Movie objects

        movie_01 = Movie()

        movie_02 = Movie()

 

        # Pass the second Movie object as an argument to the alternate function

        movie_01.find_alternate(movie_02)

       

# Call the main function.

main()

 

 

 

Chapter 10: Programming Project 1 (Scored)

 

 

Write a class named Car that uses the following data attributes:

 

·        An attribute variable named __year_model that holds the car's year model

·        An attribute variable named __make that holds the make of the car

·        An attribute variable named __speed that holds the car's current speed

 

The class should have the following methods:

An __init__ method that accepts the car’s year model and make as arguments. These values should be assigned to the object’s __year_model and __make data attributes. It should also assign 0 to the __speed data attribute.

A method named accelerate that adds 5 to the __speed data attribute each time it is called.


A method named brake that subtracts 5 from the __speed data attribute each time it is called.


A method named get_speed that returns the current speed

After you have written the class, write code that creates a 
Car object and then calls the accelerate method five times. After each call to the accelerate method, get the current speed of the car and display it. Then call the brake method five times. After each call to the brake method, get the current speed of the car and display it.

 

The following sample run shows an example of how your program's output should appear.

 

Sample Run
5
10
15
20
25
20
15
10
5
0

 

Answer:

class Car:

 

    def __init__(self, ym, m):

        self.__year_model = ym

        self.__make = m

        self.__speed = 0

   

   

    def accelerate(self):

        self.__speed += 5

 

    def brake(self):

        self.__speed -= 5

 

    def get_speed(self):

        return self.__speed

   

car = Car(1965, 'Ford Anglia')

 

for i in range(0, 5):

    car.accelerate()

    print(car.get_speed())

 

for i in range(0, 5):

    car.brake()

    print(car.get_speed())

 

 

 

Chapter 10: Programming Project 2 (Scored)

 

Question 1

Write a class named Employee that holds the following data about an employee in attributes:

·         Name

·         ID Number

·         Department

·         Job title

Once you have written the class, write a program that creates three Employee objects to hold the following data:

Name

ID Number

Department

Job Title

Susan Meyers

47899

Accounting

Vice President

Mark Jones

39119

IT

Programmer

Joy Rogers

81774

Manufacturing

Engineer


The program should store this data in three 
Employee objects and then print the data for each employee as shown exactly in the following sample run:

Sample Run
Name: Susan Meyers
ID Number: 47899

Department: Accounting

Job Title:·Vice President

Name: Mark Jones
ID Number: 39119

Department: IT

Job Title: Programmer


Name: Joy Rogers
I
ID Number: 81774

Department: Manufacturing

Job Title: Engineer

 

Answer:

class Employee:

    def __init__(self):

        self.name = ''

        self.idNumber = ''

        self.department = ''

        self.jobTitle = ''

   

    def set_name(self, name):

        self.name = name

   

    def set_idNumber(self, id):

        self.idNumber = id

   

    def set_department(self, dept):

        self.department = dept

   

    def set_jobTitle(self, title):

        self.jobTitle = title

   

    def get_name(self):

        return self.name

 

    def get_idNumber(self):

        return self.idNumber

   

    def get_department(self):

        return self.department

   

    def get_jobTitle(self):

        return self.jobTitle

 

susanMeyers = Employee()

susanMeyers.set_name('Susan Meyers')

susanMeyers.set_idNumber('47899')

susanMeyers.set_department('Accounting')

susanMeyers.set_jobTitle('Vice President')

 

markJones = Employee()

markJones.set_name('Mark Jones')

markJones.set_idNumber('39119')

markJones.set_department('IT')

markJones.set_jobTitle('Programmer')

 

joyRogers = Employee()

joyRogers.set_name('Joy Rogers')

joyRogers.set_idNumber('81774')

joyRogers.set_department('Manufacturing')

joyRogers.set_jobTitle('Engineer')

 

emp = [susanMeyers, markJones, joyRogers]

 

for employee in emp:

    print('Name: ' + employee.get_name())

    print('ID Number: ' + employee.get_idNumber())

    print('Department: ' + employee.get_department())

    print('Job Title: ' + employee.get_jobTitle())

    print()

 

 

 

 

 

Chapter 11 Solutions

 

 

 

Checkpoint 11.1

A superclass is a ________ class, and a subclass is a ________class.

a. general; specialized

b. specialized; general

Answer: a

 

 

 

Checkpoint 11.2

When one object is a specialized version of another object, the specialized object ________ version of the general object.

a. has a

b. is a

Answer:  b

 

 

 

Checkpoint 11.3

A subclass inherits all of its superclass’s attributes.

a. True

b. False

Answer: True

 

 

 

Checkpoint 11.4

Look at the following code, what is the name of the superclass? What is the name of the subclass?

class Canary(Bird):

a. Canary is the superclass, and Bird is the subclass.

b. Bird is the superclass, and Canary is the subclass.

Answer: b

 

 

 

Live Code Example 11.1

This program takes the Techie class from Chapter 10 and creates a subclass, Employee. The Employee class inherits the attributes of Techie, and adds an employee ID. Your job is to supply the accessor function for this attribute, that is, the get_empID function. Type the code into the interface below and fill in this function below the commented line. Test your program against the expected output.

Expected Output
Alexis Martinez
Web Application Programmer

Alexis Martinez
Web Application Programmer
10010110

 

class Techie:

    def __init__(self, first_name, last_name, job_title):

        self.first = first_name

        self.last = last_name

        self.title = job_title

   

   

  # create a function to return the Person's first name    

    def get_first(self):

        return self.first

   

  # create a function to return the Person's last name    

    def get_last(self):

        return self.last

   

  # create a function to return the Person's profession     

    def get_title(self):

        return self.title

 

class Employee(Techie):

 

    def __init__(self, first_name, last_name, job_title, emp_ID):

        Techie.__init__(self, first_name, last_name, job_title)

        self.__empID = emp_ID

 

    # Create a get_empID function here that returns the employee ID.

       

def main():

    techie = Techie('Alexis', 'Martinez', 'Web Application Programmer')

    print(techie.get_first(), '', end ='')

    print(techie.get_last())

    print(techie.get_title())

   

    employee = Employee('Alexis', 'Martinez', 'Web Application Programmer', '10010110')

    print(employee.get_first(), '', end ='')

    print(employee.get_last())

    print(employee.get_title())

    print(employee.get_empID())

   

main()  

 

Answer:

class Techie:

    def __init__(self, first_name, last_name, job_title):

        self.first = first_name

        self.last = last_name

        self.title = job_title

   

   

  # create a function to return the Person's first name    

    def get_first(self):

        return self.first

   

  # create a function to return the Person's last name    

    def get_last(self):

        return self.last

   

  # create a function to return the Person's profession    

    def get_title(self):

        return self.title

 

class Employee(Techie):

 

    def __init__(self, first_name, last_name, job_title, emp_ID):

        Techie.__init__(self, first_name, last_name, job_title)

        self.__empID = emp_ID

 

    def get_empID(self):

        return self.__empID

   

def main():

    techie = Techie('Alexis', 'Martinez', 'Web Application Programmer')

    print(techie.get_first(), '', end ='')

    print(techie.get_last())

    print(techie.get_title())

   

    employee = Employee('Alexis', 'Martinez', 'Web Application Programmer', '10010110')

    print(employee.get_first(), '', end ='')

    print(employee.get_last())

    print(employee.get_title())

    print(employee.get_empID())

   

main() 

 

 

 

Checkpoint 11.5

 

Look at the following class definitions:

class Vegetable:

    def _ _init_ _(self, vegtype):

        self._ _vegtype = vegtype

    def message(self):

        print("I'm a vegetable.")

class Potato(Vegetable):

    def _ _init_ _(self):

        Vegetable._ _init_ _(self, 'potato')

    def message(self):

        print("I'm a potato.")

 

Given these class definitions, what will the following statements display?

v = Vegetable('veggie')

p = Potato()

v.message()

p.message()

 

a.

I’m a vegetable.

b.

I’m a potato.

c.

I’m a vegetable.

I’m a potato.

Answer: c

 

 

 

Live Code Example 11.2

This program outlines a hierarchy of musical instruments. Instrument is the superclass, and Guitar and DrumSet are its subclasses. Each subclass contains a polymorphic make_sound method.

Your job is to supply the initializer for the 
DrumSet class, using the Guitar class as a model. Add the initializer code where indicated, and test it against the expected output.

Expected Output
Here are some instruments and the types of sounds they make.

I am a Guitar
Strumming Strings

I am a Drum Set
Bang, Bang!

 

# The Instrument class represents a generic musical instrument.

class Instrument:

 

# The __init__ method accepts an argument for the name of the instrument.

    def __init__(self, name):

        self.__name = name

 

# The show_name method displays the instrument name.

    def show_name(self):

        print('I am a', self.__name)

 

# The make_sound method describes the instrument's sound.

    def make_sound(self):

        print('Lalalala')

 

# The Guitar class is a subclass of the Instrument class.

class Guitar(Instrument):

 

# The __init__ method calls the superclass's

# __init__ method passing 'Guitar' as the species.

 

    def __init__(self):

        Instrument.__init__(self, 'Guitar')

 

# The make_sound method overrides the superclass's

# make_sound method.

    def make_sound(self):

        print('Strumming Strings')

       

       

class Drum_Set(Instrument):

 

# The __init__ method calls the superclass's

# __init__ method passing 'Drum_Set'.

# Create the init method here.

 

# The make_sound method overrides the superclass's

# make_sound method.

    def make_sound(self):

        print('Bang, Bang!')       

       

def main():

    # Create Guitar and a Drums objects.

    guitar = Guitar()

    drums = Drum_Set()

  

    # Display information about each one.

    print('Here are some instruments and the types of sounds they make.')

    print()

    show_sounds(guitar)

    print()

    show_sounds(drums)

   

 # The show_sounds function accepts an object

 # as an argument, and calls its show_name

 # and make_sound methods.

 

def show_sounds(instrument_type):

    instrument_type.show_name()

    instrument_type.make_sound()

 

# Call the main function.

main()

 

Answer:

# The Instrument class represents a generic musical instrument.

class Instrument:

 

# The __init__ method accepts an argument for the name of the instrument.

    def __init__(self, name):

        self.__name = name

 

# The show_name method displays the instrument name.

    def show_name(self):

        print('I am a', self.__name)

 

# The make_sound method describes the instrument's sound.

    def make_sound(self):

        print('Lalalala')

 

# The Guitar class is a subclass of the Instrument class.

class Guitar(Instrument):

 

# The __init__ method calls the superclass's

# __init__ method passing 'Guitar' as the species.

 

    def __init__(self):

        Instrument.__init__(self, 'Guitar')

 

# The make_sound method overrides the superclass's

# make_sound method.

    def make_sound(self):

        print('Strumming Strings')

       

       

class Drum_Set(Instrument):

 

# The __init__ method calls the superclass's

# __init__ method passing 'Drum_Set' as the species.

    def __init__(self):

        Instrument.__init__(self, 'Drum Set')

 

# The make_sound method overrides the superclass's

# make_sound method.

    def make_sound(self):

        print('Bang, Bang!')       

       

def main():

    # Create Guitar and a Drums objects.

    guitar = Guitar()

    drums = Drum_Set()

  

    # Display information about each one.

    print('Here are some instruments and the types of sounds they make.')

    print()

    show_sounds(guitar)

    print()

    show_sounds(drums)

   

 # The show_sounds function accepts an object

 # as an argument, and calls its show_name

 # and make_sound methods.

 

def show_sounds(instrument_type):

    instrument_type.show_name()

    instrument_type.make_sound()

 

# Call the main function.

main()

 

 

 

Chapter 12 Solutions

 



Checkpoint 12.1

A function that ________ is known as a recursive function.

a. stores itself

b. calls itself

c. calls another function

d. stores another function

Answer: b

 

 

Checkpoint 12.2

A recursive function must have some way to control the number of times it repeats to  avoid a(n) ________.

a. exception

b. syntax error

c. infinite loop

d. warning

Answer: c

 

 

Checkpoint 12.3

The number of times that a function calls itself is known as the ________ of recursion.

a. depth

b. nature

c. problem

d. magnitude

Answer: a

 

 

 

Quiz 12.1 (Scored)

 

Question 1

Write a function named printStars. The function should accept an integer argument. If the argument is a positive number, the function should print that number of asterisks. Otherwise the function should do nothing. The function does not return a value.

 

Thus, if printStars(8) is called, ******** will be printed (8 asterisks).

 

The function must not use a loop of any kind to accomplish its job. Instead, it should examine its argument and simply return if the argument is not positive. If the parameter is positive, it should:

·         print a single asterisk (and no other characters)

·         then recursively call itself to print the remaining asterisks

 

Answer:

def printStars(num):

    if num > 0:

         print("*", end="")

         printStars(num-1)

 

 

 

Question 2

Assume a function named printStars has already been defined. The function can be passed an argument that is a non-negative integer value. The function prints the given number of asterisks.

Write another function named 
printTriangle that receives an argument n, holding a non-negative integer value and prints a triangle of asterisks as follows: first a line of n asterisks, followed by a line of n-1 asterisks, and then a line of n-2 asterisks, and so on.

For example, if the function receives the argument 5, it would print:


*****
****
***
**
*

The function must not use a loop of any kind to accomplish its job. The function should call the
printStars function to accomplish the task of printing a single line.

 

Answer:

def printTriangle(n):

    printStars(n)

    if n > 1:

        print()

        printTriangle(n-1)

 

 

 

Checkpoint 12.4

A recursive algorithm has more overhead than an iterative algorithm because it required multiple method calls.

True

False

Answer: True

 

 

Checkpoint 12.5

A base case can be solved without recursion.

a. True

b. False

Answer: True

 

 

Checkpoint 12.6

A recursive algorithm stops calling itself when it ________.

a. meets a benchmark  

b. is told to do so

c. reaches the base case

Answer: c

 



Checkpoint 12.7

In direct recursion, method A calls method B, which in turn calls method A.

a. True

b. False

Answer: False

 

 

 

Live Code Example 12.1

This program is a recursive version of a power function. It is not working correctly, however. Correct the errors to display the expected output.

Expected Output
Enter base: 6
Enter exponential value: 4
Result: 1296

 

def power(base,exp):

    if(exp == 1):

        return(base)

    if(exp > 1):

        return(base * power(exp - 1))

       

def main():       

    base=int(input('Enter base: '))

    exp=int(input('Enter exponential value: '))

    print('Result:',power(base, exp))

 

main()

 

Answer:

def power(base,exp):

    if(exp == 1):

        return(base)

    if(exp != 1):

        return(base * power(base, exp - 1))

        

def main():       

    base=int(input('Enter base: '))

    exp=int(input('Enter exponential value: '))

    print('Result:',power(base, exp))

 

main()

 

 

 

Quiz 12.2 (Scored)

 

Question 1

Write a function named fact that accepts one argument, and integer value. The function should recursively calculate the factorial value of its argument.

 

Answer:

def fact(n):

    if n == 0 or n == 1:

        return 1

    else:

        return n * fact(n-1)



 

Checkpoint 12.8

Recursive function calls are more efficient than loops.

a. True

b. False

Answer: False

 

 

Checkpoint 12.9

The majority of repetitive programming tasks are best done with loops.

a. True

b. False

Answer: True

 

 

Checkpoint 12.10

If a recursive solution is evident for a particular problem, it may be a good choice if it does not slow system performance significantly.

a. True

b. False

Answer: True

 

 

 

Live Code Example 12.2

This program sums a list of integers recursively. You will supply the recursive case. Fill in the commented line with the missing code to display the expected output.

Expected Output
78

 

def sum(list):

   if len(list) == 1:

      return list[0]

   else:

      # Fill in the recursive case here.

     

 

def main():

   print(sum([1, 3, 4, 9, 22, 39]))

 

main()

 

Answer:

def sum(list):

   if len(list) == 1:

      return list[0]

   else:

      return list[0] + sum(list[1:])

 

def main():

   print(sum([1, 3, 4, 9, 22, 39]))

 

main()

 

 

 

Quiz 12.3 (Scored)

 

Question 1

Write a recursive function named len that accepts a string argument and returns the number of characters in the string.

 

The function must use recursion to count the number of characters in the string. Do not use a loop or a built-in function.


Answer:

def len(string):

    if string == '':

        return 0

    else:

        return 1 + len(string[1:])

 

 

 

Question 2

Write a recursive function named reverse that accepts a string argument and returns the original string with its characters reversed. For example, calling reverse('goodbye') would return 'eybdoog'.

 

The function must use recursion to reverse the characters in the string. Do not use a loop.

 

Answer:

def reverse(string):

    if len(string) == 0 or len(string) == 1:

        return string

    else:

        return string[len(string)-1] + reverse(string[:-1])

 

 

 

Chapter 12: Programming Project 1 (Scored)

 

The sum of the elements in a tuple can be recursively calculated as follows:

 

·         The sum of the elements in a tuple of size 0 is 0

·         Otherwise, the sum is the value of the first element added to the sum of the rest of the elements

 

Write a function named sum that accepts a tuple as an argument and returns the sum of the elements in the tuple.

 

Answer:

def sum(tup):

    if len(tup) == 0:

        return 0

    else:

        return tup[0] + sum(tup[1:])

 

 

 

Chapter 12: Programming Project 2 (Scored)

 

A 'tuple palindrome' is tuple, which, when its elements are reversed, remains the same.

Write a recursive function named isPalindrome that accepts a tuple and returns whether the tuple is a palindrome.


A tuple is a palindrome if:

·         the tuple is empty or contains one element

·         the first and last elements of the tuple are the same, and the rest of the tuple is a palindrome

 

Answer:

def isPalindrome(tup):

    if len(tup) == 0 or len(tup) == 1:

        return True

    else:

        if tup[0] == tup[-1]:

            return isPalindrome(tup[1:-1])

        else:

            return False

 

 

 

 

Chapter 13 Solutions

 



Checkpoint 13.1

A user interface is the part of a computer and its operating system with which the user interacts.

a. True

b. False

Answer: True



 

Checkpoint 13.2

A command line interface typically displays a(n)________, and the user types a command, which is then executed.

a. signal

b. instruction

c. prompt

d. menu

Answer: c

 

 

Checkpoint 13.3

When the user runs a program in a text-based environment, such as the command line, what determines the order in which things happen?

a. the program

b. the file scheduler

c. the device controller

d. the GUI

Answer: a

 

 

Checkpoint 13.4

An event-driven program responds to events that take place, such as the user clicking a button.

a. True

b. False

Answer: True

 



Checkpoint 13.5

What area displays one line of text or an image?

a. Label

b. Entry

c. Button

d. Frame

Answer: a

 



Checkpoint 13.6

Where can the user type a single line of input from the keyboard?

a. Label

b. Entry

c. Button

d. Frame

Answer: b

 



Checkpoint 13.7

To create a root widget, you create an instance of the tkinter module’s ________ class.

a. self

b. initloop

c. mainloop

d. Tk

Answer: d

 

 

Checkpoint 13.8

The tkinter module’s ________ function runs like an infinite loop until you close the main window.

a. main

b. initloop

c. init

d. mainloop

Answer: d

 



Checkpoint 13.9

A Label’s ________ method arranges a widget in its proper position, and it makes the widget visible when the main window is displayed.

a. pack

b. display

c. access

d. isvisible

Answer: a

 

 

Checkpoint 13.10

If you create two Label widgets and call their pack methods with no arguments, how will the Label widgets be arranged inside their parent widget?

a. The parent will allocate privileges first. 

b. One will be stacked on top of the other.

c. They will sit next to each other.

Answer: b

 



Checkpoint 13.11

What argument would you pass to a widget’s pack method to specify that it should be positioned as far left as possible inside the parent widget?

a. widget().left

b. parent.left

c.'left' = side

d. side='left'

Answer: d

 



Checkpoint 13.12

A Frame is a container.

a. True

b. False

Answer: True

 



Checkpoint 13.13

Frames are most useful for organizing and arranging groups of ________.

a. text in a textbox

b. widgets in a window

c. images interlayered

d. processes by schedule

Answer: b

 



Checkpoint 13.14

GUI programs usually have a Quit button that closes the program when the user clicks it.

a. True

b. False

Answer: True



 

Checkpoint 13.15

To create a Quit button in a Python program, you simply create a Button widget that calls the root  widget’s ________ method as a callback function.

a. destroy

b. archive

c. terminate

d. kickoff

Answer: a

 



 

Checkpoint 13.16

You can use an Entry widget’s ________ method to retrieve the data that the user has typed into the widget.

a. set

b. get

c. place

d. enter

Answer: b

 

 

Checkpoint 13.17

When you retrieve a value from an Entry widget, it is of type ________.

a. character

b. integer

c. float

d. string

Answer: string

 



Checkpoint 13.18

Values in the StringVar object are not displayed in the Label widget by default.

a. True

b. False

Answer: False

 



Checkpoint 13.19

You want the user to be able to select only one item from a group of items. Which type of component would you use for the items, radio buttons or check buttons?

a. check buttons

b. radio buttons

Answer: b

 

 

Checkpoint 13.20

You want the user to be able to select any number of items from a group of items. Which type of component would you use for the items, radio buttons or check buttons?

a. check buttons

b. radio buttons

Answer: a

 

 

Checkpoint 13.21

When you create a group of Radiobuttons, you associate them all with the same ________.

a. IntVar object with a unique integer value for each Radiobutton

b. integer value and a general IntVar object

Answer: a

 

 

Checkpoint 13.22

When a Checkbutton is selected, its associated IntVar object will hold the value 0.

a. True

b. False

Answer: False

 



Checkpoint 13.23

With the Canvas widget, the point (0, 0) is in the center of the window.

a. True

b. False

Answer: False

 



Checkpoint 13.24

Using the Canvas widget’s screen coordinate system with a window that is 640 pixels wide by 480 pixels high, what are the coordinates of the pixel in the lower-right corner?

a. (640, 480)

b. (639, 479)

c. (479, 139)

d. (480, 640)

Answer: b

 

 

Checkpoint 13.25

What Canvas widget method would you use to draw a closed six-sided shape?

a. draw_ellipse

b. draw_arc

c. create_oval

d. create_polygon

Answer: d

 

 

Checkpoint 13.26

With the Canvas widget, the Y coordinates ________ as you move down the screen. In turtle graphics, the Y coordinates ________ as you move down the screen.

a. decrease; increase

b. increase; decrease

Answer: b