100% satisfaction guarantee Immediately available after payment Both online and in PDF No strings attached 4.2 TrustPilot
logo-home
Exam (elaborations)

Solution Manual & Answer Guide for Fundamentals of Python, First Programs, 3rd Edition By Kenneth Lambert (All Chapters included 1-13 ) 100% A+ & Verified

Rating
5.0
(1)
Sold
2
Pages
164
Grade
A+
Uploaded on
19-06-2025
Written in
2024/2025

Solutions for Fundamentals of Python, First Programs, 3rd Edition Lambert (All Chapters included) 100% A+ & Verified Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction 1 Solution and Answer Guide For All Chapters LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS, 3E, CY24, 9780357881019; CHAPTER 1, INTRODUCTION TABLE OF CONTENTS Exercise Solutions ....................................................................................................................................... 1 Exercise 1.1............................................................................................................................................... 1 Exercise 1.2............................................................................................................................................... 2 Exercise 1.3............................................................................................................................................... 3 Review Questions Answers......................................................................................................................... 4 Programming Exercises Solutions............................................................................................................. 8 Debugging Exercises Solutions .................................................................................................................. 8 EXERCISE SOLUTIONS EXERCISE 1.1 1. List three common types of computing agents. Solution: Human beings, desktop computers, cell phones 2. Write an algorithm that describes the second part of the process of making change (counting out the coins and bills). Solution: There are various ways to do this, but here is one: Repeat Select the largest unit of money that is less than or equal to the remaining change Subtract this unit from the remaining change Until the remaining change is 0 The collection of units selected represent the change 3. Write an algorithm that describes a common task, such as baking a cake. Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction 2 Solution: There are various ways to do this, but here is one: Preheat an oven to 375 degrees Add 1 cup of water and 1 egg to a mixing bowl Beat the liquid mixture in the bowl until the ingredients are blended Add the contents of a boxed cake mix to the mixing bowl Beat the mixture in the bowl until the ingredients are blended Pour the contents of the mixing bowl into a lightly greased cake pan Bake the cake in the oven for 45 minutes 4. Describe an instruction that is not well defined and thus could not be included as a step in an algorithm. Give an example of such an instruction. Solution: Attempting to divide a number by 0 5. In what sense is a laptop computer a general-purpose problem-solving machine? Solution: A laptop computer is a general-purpose problem-solving machine because it is programmable and can solve any problem for which there is an algorithm. 6. List four devices that use computers and describe the information that they process. (Hint: Think of the inputs and outputs of the devices.) Solution: Digital camera—images, music player—sound, cell phone—text, ATM—numbers EXERCISE 1.2 1. List two examples of input devices and two examples of output devices. Solution: Input devices—keyboard and mouse, output devices—monitor and speakers 2. What does the central processing unit (CPU) do? Solution: The CPU fetches, decodes, and executes instructions. 3. How is information represented in hardware memory? Solution: Information is represented using binary notation, which in hardware is a pattern of voltage levels. Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction 3 4. What is the difference between a terminal-based interface and a graphical user interface? Solution: A terminal-based interface supports only the input and output of text with a keyboard and monitor. A graphical user interface supports the output of images and the manipulation of them with a pointing device, the mouse. 5. What role do translators play in the programming process? Solution: A translator converts a program written in a high-level language (human readable and writable) to an equivalent program in a low-level language (machine readable and executable). EXERCISE 1.3 1. Describe what happens when the programmer enters the string "Greetings!" in the Python shell. Solution: Python reads the string "Greetings!", evaluates it, and displays this string (including single quotes) in the shell. 2. Write a line of code that prompts the user for their name and saves the user’s input in a variable called name. Solution: name = input("Enter your name: ") 3. What is a Python script? Solution: A Python script is a complete Python program that can be run from a computer’s operating system. 4. Explain what goes on behind the scenes when your computer runs a Python program. Solution: If the program has not already been translated, Python’s compiler translates it to byte code. The Python virtual machine then executes this code. Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction 4 REVIEW QUESTIONS ANSWERS 1. Which of the following is an example of an algorithm? a. A dictionary b. A recipe c. A shopping list d. The spelling checker of a word processor Answer: b Feedback: a. Incorrect. A dictionary is a data structure. b. Correct. A recipe is a set of instructions that describes a process that halts with a solution to a problem. c. Incorrect. A shopping list is a data structure. d. Incorrect. A word processor is a program that consists of instructions and data. 2. Which of the following contains information? a. An audio CD b. A refrigerator c. An automobile d. A stereo speaker Answer: a Feedback: a. Correct. The information on an audio CD represents sound. b. Incorrect. A refrigerator contains just food, if it’s not empty. c. Incorrect. An automobile contains a steering wheel, engine, exhaust pipe, and so on. d. Incorrect. A stereo speaker contains a magnetic coil, wires, and so on. 3. Which of the following is a general-purpose computing device? a. A smartphone b. A portable music player c. A microwave oven d. A programmable thermostat Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction 5 Answer: a Feedback: a. Correct. A smartphone is capable of running any program. b. Incorrect. A portable music player is dedicated to the specialized tasks of playing digital music. c. Incorrect. A microwave is dedicated to the task of heating food. d. Incorrect. A programmable thermostat is dedicated to the specialized tasks of climate control. 4. Which of the following is an input device? a. Speaker b. Microphone c. Printer d. Display screen Answer: b Feedback: a. Incorrect. A speaker is a device for the output of sound. b. Correct. A microphone is a device for the input of sound. c. Incorrect. A printer is a device for the output of words or graphics on paper. d. Incorrect. A display screen is a device for the output of images and text. 5. Which of the following are output devices? a. A digital camera b. A keyboard c. A flatbed scanner d. A monitor Answer: d Feedback: a. Incorrect. A digital camera is a device for the input of images. b. Incorrect. A keyboard is a device for the input of characters and commands via keystrokes. c. Incorrect. A flatbed scanner is a device for the input of images from paper. d. Correct. A monitor is a device for the visual display or output of words and graphics. Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction 6 6. What is the purpose of the CPU? a. Store information b. Receive inputs from the human user c. Decode and execute instructions d. Send output to the human user Answer: c Feedback: a. Incorrect. The purpose of memory is to store information. b. Incorrect. The purpose of input devices, such as a keyboard, is to receive input from the human user. c. Correct. The CPU contains circuitry that decodes and executes instructions. d. Incorrect. The purpose of output devices, such as a monitor, is to send output to the human user. 7. Which of the following translates and executes instructions in a programming language? a. A compiler b. A text editor c. A loader d. An interpreter Answer: d Feedback: a. Incorrect. A compiler translates instructions in a source program to instructions in byte code or machine code. b. Incorrect. A text editor allows a programmer to edit and save source code for a program. c. Incorrect. A loader transfers instructions and data from external memory to random access memory at program startup. d. Correct. An interpreter both translates (compiles) and executes (runs) instructions in a programming language. Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction 7 8. Which of the following outputs data in a Python program? a. The input function b. The assignment statement c. The print function d. The main function Answer: c a. Incorrect. The input statement receives data from a file or at the keyboard and makes these data available to a running program. b. Incorrect. The assignment statement binds a variable to a value. c. Correct. The print statement sends data from a running program to a an output device, such as a monitor or a speaker. d. Incorrect. The main function organizes a program at the top level into a sequence of instructions. 9. What is IDLE used to do? a. Edit Python programs b. Save Python programs to files c. Run Python programs d. All of the other answers Answer: d Feedback: a. Correct. IDLE can be used for all three tasks. b. Correct. IDLE can be used to compile and run programs, too. c. Correct. IDLE can be used to edit and run programs, too. d. Correct.t IDLE can be used to edit and compile programs, too. 10. What is the set of rules for forming sentences in a language called? a. Semantics b. Pragmatics Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction 8 c. Syntax d. Logic Answer: c Feedback: a. Incorrect. Semantics is the set of rules for interpreting the meaning of sentences in a language. b. Incorrect. Pragmatics is the set rules that describe the types of uses to which sentences in a language can be put. c. Correct. Semantics is the set of rules for forming sentences in a language. d. Incorrect. Logic is the set of rules for determining valid or invalid arguments in a language. PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 1. Write a Python program in a file named that prints (displays) your name, address, and telephone number. (LO: 1.1) Solution: See posted on the Instructor Companion Site. 2. Open an IDLE window and enter the program from Figure 1-7 that computes the area of a rectangle. Save the program to a file named and load it into the shell by pressing the F5 key and correct any errors that occur. Test the program with different inputs by running it at least three times. (LO: 1.1) Solution: See posted on the Instructor Companion Site. 3. Write a program in a file named to compute the area of a triangle. Issue the appropriate prompts for the triangle’s base and height. Then, use the formula .5 * base * height to compute the area. Test the program from an IDLE window. (LO: 1.1) Solution: See posted on the Instructor Companion Site. Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction 9 4. Write and test a program in a file named that computes the area of a circle. This program should request a number representing a radius as input from the user. It should use the formula 3.14 * radius ** 2 to compute the area and then output this result suitably labeled. (LO: 1.1) Solution: See posted on the Instructor Companion Site. 5. A cuboid is a solid figure bounded by six rectangular faces. Its dimensions are its height, width, and depth. Write a Python program in a file named that computes and prints the volume of a cuboid, given its height, width, and depth as inputs. The volume is just the product of these three inputs. The output should be labeled as ―cubic units.‖ Solution: See posted on the Instructor Companion Site. DEBUGGING EXERCISES SOLUTIONS 1. Consider the following interaction at the Python shell: >>> first = input("Enter the first integer: ") Enter the first number: 23 >>> second = input("Enter the second integer: ") Enter the second number: 44 >>> print("The sum is", first + second) The sum of the two integers is 2344 The expected output is 67, but the output of this computation is 2344. Explain what causes this error and describe how to correct it. Solution The program prints the value 2344 when given the inputs 23 and 44. The output is the result of applying the + operator to the two the input strings ―23‖ and ―44‖ to produce the resulting string ―2344‖. To produce the arithmetic sum of the integers 23 and 44, one should convert the input strings ―23‖ and ―44‖ to integer values, using the type conversion function int. The revised statements Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions 10 first = int(input("Enter the first integer: ")) second = int(input("Enter the second integer: ")) accomplish this. Then the + operator will perform an arithmetic sum on the two integers, producing the expected integer value of 67. Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS, 3E, CY24, 9780357881019; CHAPTER 2, SOFTWARE DEVELOPMENT, DATA TYPES, AND EXPRESSIONS TABLE OF CONTENTS Exercise Solutions..................................................................................................................................... 10 Exercise 2.1............................................................................................................................................. 10 Exercise 2.2............................................................................................................................................. 11 Exercise 2.3............................................................................................................................................. 12 Exercise 2.4............................................................................................................................................. 13 Review Questions Answers....................................................................................................................... 14 Programming Exercises Solutions........................................................................................................... 18 Debugging Exercise Solution.................................................................................................................... 20 EXERCISE SOLUTIONS EXERCISE 2.1 7. List four phases of the software development process and explain what they accomplish. Solution: Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions 11 Analysis describes what a system does in terms of its input, outputs, and functions from a user’s perspective. Design describes how a system accomplishes its tasks. Coding produces the software for the system. Testing examines whether or not the software does what it is supposed to do. 8. Jack says that he will not bother with analysis and design but proceed directly to coding his programs. Why is that not a good idea? Solution: Analysis and design provide detailed blueprints for coding a system. Without these blueprints, it may be difficult to determine whether the system will do what it is supposed to do, and it may be difficult to minimize errors in the code and structure it in a way that eases maintenance. EXERCISE 2.2 6. Let the variable x be "dog" and the variable y be "cat". Write the values returned by the following operations: a. x + y b. "the " + x + " chases the " + y c. x * 4. Solution: a. "dogcat" b. "the dog chases the cat" c. "dogdogdogdog" 7. Write a string that contains your name and address on separate lines using embedded newline characters. Then write the same string literal without the newline characters. Solution: "Ken LambertnComputer SciencenWashington and Lee" """Ken Lambert Computer Science Washington and Lee""" 8. How does one include an apostrophe as a character within a string literal? Solution: An apostrophe can be included in a string that is enclosed within double quotes. 9. What happens when the print function prints a string literal with embedded newline characters? Solution: When the Python interpreter encounters a newline character while printing a string, the cursor moves to the next line of output before the rest of the characters are displayed. 10. Which of the following are valid variable names? Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions 12 a. length b. _width c. firstBase d. 2MoreToGo e. halt! Solution: a, b, and c EXERCISE 2.3 5. Which data type would most appropriately be used to represent the following data values? a. The number of months in a year b. The area of a circle c. The current minimum wage d. The approximate age of the universe (12,000,000,000 years) e. Your name Solution: a. int b. float c. float d. int e. string 6. Explain the differences between the data types int and float. Solution: int is the type of integers or whole numbers, whereas float is the type of numbers that include a whole part (digits to the left of a decimal point) and a fractional part (digits to the right of the decimal point). 7. Write the values of the following floating-point numbers in Python’s scientific notation: a. 355.76 b. 0.007832 Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions 13 c. 4.3212 Solution: a. 3.5576e2 b. 7.832e-3 c. 4.3212e0 8. Consult Table 2-5 to write the ASCII values of the characters '$' and '&'. Solution: 36 and 38. EXERCISE 2.4 1. Let x = 8 and y = 2. Write the values of the following expressions: a. x + y * 3 b. (x + y) * 3 c. x ** y d. x % y e. x / 12.0 f. x // 6 Solution: a. 14 b. 30 c. 64 d. 0 e. 0. f. 1 2. Let x = 4.66. Write the values of the following expressions: a. round(x) b. int(x) Solution: Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions 14 a. 5.0 b. 4 3. How does a Python programmer round a float value to the nearest int value? Solution: Pass the number to the round function. 4. How does a Python programmer concatenate a numeric value to a string value? Solution: Pass the number as an argument the str function and use the result returned with the string and the + operator. 5. Assume that the variable x has the value 55. Use an assignment statement to increment the value of x by 1. Solution: x = x + 1 REVIEW QUESTIONS ANSWERS 11. What does a programmer do during the analysis phase of software development? a. Codes the program in a particular programming language b. Writes the algorithms for solving a problem c. Decides what the program will do and determines its user interface d. Tests the program to verify its correctness Answer: c Feedback: e. Incorrect. Coding occurs after design. f. Inorrect. Algorithms are written during design. g. Correct. This is a set of instructions that describes a process that halts with a solution to a problem. h. Incorrect. Testing occurs after coding. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions 15 12. What must a programmer use to test a program? a. All possible sets of legitimate inputs b. All possible sets of inputs c. A single set of legitimate inputs d. A reasonable set of legitimate inputs Answer: d Feedback: e. Incorrect. There may be an infinite number of sets of possible legitimate inputs. f. Incorrect. Some inputs may not be legitimate, and only legitimate ones are candidates for testing. g. incorrect. The program might fail on a legitimate input that is not tested. h. Correct. A reasonable set of legitimate inputs is finite and includes those likely to produce correct results. 13. What must you use to create a multiline string? e. A single pair of double quotation marks f. A single pair of single quotation marks g. A single pair of three consecutive double quotation marks h. Embedded newline characters Answer: c, d Feedback: e. Inorrect. This creates a string, but no newlines are specified. f. Incorrect. This creates a string, but no newlines are specified. g. Correct. This will create a multiline string if the string’s text is on multiple lines in the source programs. h. Correct. An embedded newline character causes a newline to print on the monitor. 14. What is used to begin an end-of-line comment? a. / symbol b. # symbol c. % symbol d. * symbol Answer: b Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions 16 Feedback: e. Incorrect. The / symbol serves as an arithmetic division operator or as a line separator in source code. f. Correct. The # symbol begins an end-of-line comment. g. Incorrect. The % operator serves as the arithmetic remainder operator. h. Incorrect. The * symbol serves as the arithmetic multiplication operator. 15. Which of the following lists of operators is ordered by decreasing precedence? e. +, *, ** f. *, /, % g. **, *, + h. +, - Answer: c Feedback: e. Incorrect. These operators are ordered by increasing precedence. f. Incorrect. These operators have the same precedence. g. Correct. These operators are ordered by decreasing precedence. h. Incorrect. These operators have the same precedence. 16. The expression 2 ** 3 ** 2 evaluates to which of the following values? e. 64 f. 512 g. 8 h. 12 Answer: b Feedback: e. Incorrect. This assumes that ** is left-associative. f. Correct. ** is right-associative, which means that 3 ** 2 is evaluated before the result, 9 is used as the exponent for 2 ** 9. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions 17 g. Incorrect. This is the result of 2 * 3 + 2. h. Incorrect. This is the result of 2 * 3 * 2. 17. The expression round(23.67) evaluates to which of the following values? e. 23 f. 23.7 g. 24.0 h. 24 Answer: d Feedback: e. Incorrect. This would be the result of using the int function, which truncates the argument. f. Incorrect. round with a single argument returns an int. g. Incorrect. round with a single argument returns an int. h. Correct. round rounds its single argument to the nearest whole number. In this case, it rounds up because the argument is greater than 23.5. 18. Assume that the variable name has the value 33. What is the value of name after the assignment name = name * 2 executes? e. 35 f. 33 g. 66 Answer: c e. Incorrect. 35 is 33 + 2. f. Incorrect. A total distractor. g. Correct. 66 is double 33. h. Incorrect. 1089 is 33 ** 2. 19. Write an import statement that imports just the functions sqrt and log from the math module. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions 18 Answer: from math import sqrt, log Feedback: Items can be imported from a module by listing them. 20. What are the purposes of the dir function and the help function? Answer: The dir function returns a list of the named resources (functions and variables) in its argument, which is a module. The help function displays all of the documentation for its argument, which can be a module or an item within a module. PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 6. The tax calculator program of the case study outputs a floating-point number that might show more than two digits of precision. Use the round function to modify the program in the file to display at most two digits of precision in the output number. (LO: 2.4) Solution: See posted on the Instructor Companion Site. 7. You can calculate the surface area of a cube if you know the length of an edge. Write a program in the file that takes the length of an edge (an integer) as input and prints the cube’s surface area as output. (LO: 2.4) Solution: See posted on the Instructor Companion Site. 8. Five Star Retro Video rents VHS tapes and DVDs to the same connoisseurs who like to buy LP record albums. The store rents new videos for $3.00 a night and oldies for $2.00 a night. Write a program in the Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions 19 file that the clerks at Five Star Retro Video can use to calculate the total charge for a customer’s video rentals. The program should prompt the user for the number of each type of video and output the total cost. (LO: 2.3, 2.4) Solution: See posted on the Instructor Companion Site. 9. Write a program in the file that takes the radius of a sphere (a floating-point number) as input and then outputs the sphere’s diameter, circumference, surface area, and volume. (LO: 2.3, 2.4, 2.5) Solution: See posted on the Instructor Companion Site. 10. An object’s momentum is its mass multiplied by its velocity. Write a program in the file that accepts an object’s mass (in kilograms) and velocity (in meters per second) as inputs and then outputs its momentum. (LO: 2.3, 2.4) Solution: See posted on the Instructor Companion Site. 11. The kinetic energy of a moving object is given by the formula KE = (1/ 2)mv2 where m is the object’s mass and v is its velocity. Modify the program you created in Programming Exercise 5 so that it prints the object’s kinetic energy as well as its momentum. (LO: 2.3, 2.4) Solution: See posted on the Instructor Companion Site. 12. Write a program in the file that takes as input a number of years and calculates and prints the number of minutes in that period of time. (LO: 2.4) Solution: See posted on the Instructor Companion Site. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions 20 13. Light travels at 3 * 108 meters per second. A light-year is the distance a light beam travels in one year. Write a program in the file that expects a number of years as input and calculates and displays the value of the distance traveled in meters. (LO: 2.4) Solution: See posted on the Instructor Companion Site. 14. Write a program in the file that takes as input a number of kilometers and prints the corresponding number of nautical miles. Use the following approximations:  A kilometer represents 1/10,000 of the distance between the North Pole and the equator.  There are 90 degrees, containing 60 minutes of arc each, between the North Pole and the equator.  A nautical mile is 1 minute of an arc. (LO: 2.4) Solution: See posted on the Instructor Companion Site. 10. An employee’s total weekly pay equals the hourly wage multiplied by the total number of regular hours plus any overtime pay. Overtime pay equals the total overtime hours multiplied by 1.5 times the hourly wage. Write a program in the file that takes as inputs the hourly wage, total regular hours, and total overtime hours and displays an employee’s total weekly pay. (LO: 2.3, 2.4) Solution: See posted on the Instructor Companion Site. DEBUGGING EXERCISE SOLUTION Jill has written a program that computes the sales tax on the purchase of an item, given the price of the item (a floating-point number) and the percent tax rate (an integer). The output of the program is the purchase price, the tax, and the total amount to be paid. Here is her code: purchasePrice = float(input("Enter the purchase price as $: ")) taxRate = int(input("Enter the tax rate as %: ")) tax = purchasePrice * taxRate Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 21 website, in whole or in part. totalOwed = purchasePrice + tax print("Purchase price: ", purchasePrice) print("Tax: ", tax) print("Total owed: ", totalOwed) When she tested his program with a purchase price of $5.50 and a sales tax of 5%, Jill observed the following unexpected output: Enter the purchase price as $: 5.50 Enter the tax rate as %: 5 Purchase price: 5.5 Tax: 27.5 Total owed: 33.0 Describe the error, explain why it happened, and suggest a correction. Solution The code accepts an integer percent as input for the tax rate, but it does not divide this value by 100 to produce the correct floating-point form to use in the computation of the sales tax. To correct the problem, the program must reset taxRate to taxRate / 100 after the input. Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS, 3E, CY24, 9780357881019; CHAPTER 3, LOOPS AND SELECTION STATEMENTS TABLE OF CONTENTS Exercise Solutions..................................................................................................................................... 22 Exercise 3.1............................................................................................................................................. 22 Exercise 3.2............................................................................................................................................. 23 Exercise 3.3............................................................................................................................................. 24 Exercise 3.4............................................................................................................................................. 26 Review Questions Answers....................................................................................................................... 27 Programming Exercises Solutions........................................................................................................... 33 Debugging Exercise Solution.................................................................................................................... 37 Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 22 website, in whole or in part. EXERCISE SOLUTIONS EXERCISE 3.1 9. Write the outputs of the following loops: a. for count in range(5): print(count + 1, end = " ") b. for count in range(1, 4): print(count, end = " ") c. for count in range(1, 6, 2): print(count, end = " ") d. for count in range(6, 1, -1): print(count, end = " ") Solution: a. b. 1 2 3 c. 1 3 5 d. . 10. Write a loop that prints your name 100 times. Each output should begin on a new line. Solution: for count in range(100): print("cat") 11. Explain the role of the variable in the header of a for loop. Solution: On each pass through the loop, the header’s variable is automatically assigned the next value in a sequence. The sequence of values is determined by the other information in the header. 12. Write a loop that prints the first 128 ASCII values followed by the corresponding characters (see the section on characters in Chapter 2). Be aware that most of the ASCII values in the range ―0..31‖ belong to special control characters with no standard print representation, so you might see strange symbols in the output for these values. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 23 website, in whole or in part. Solution: for ascii in range(128): print(ascii, chr(ascii)) 13. Assume that the variable testString refers to a string. Write a loop that prints each character in this string, followed by its ASCII value. Solution: for ch in testString: print(ch, ord(ch)) EXERCISE 3.2 11. Assume that the variable amount refers to 24.325. Write the outputs of the following statements: a. print("Your salary is $%0.2f" % amount) b. print("The area is %0.1f" % amount) c. print("%7f" % amount) Solution: a. Your salary is $24.32 b. The area is 24.3 c. 24.325000 12. Write a code segment that displays the values of the integers x, y, and z on a single line, such that each value is right-justified with a field width of 6. Solution: print("%6d%6d%6d" % (x, y, z)) 13. Write a format operation that builds a string for the float variable amount that has exactly two digits of precision and a field width of zero. Solution: "%0.2f" % amount 14. Write a loop that outputs the numbers in a list named salaries. The outputs should be formatted in a column that is right-justified, with a field width of 12 and a precision of 2. Solution: for number in salaries: print("%12.2f" % number) Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 24 website, in whole or in part. EXERCISE 3.3 1. Assume that x is 3 and y is 5. Write the values of the following expressions: a. x == y b. x > y - 3 c. x <= y - 2 d. x == y or x > 2 e. x != 6 and y > 10 f. x > 0 and x < 100 Solution: a. False b. True c. True d. True e. False f. True 2. Assume that x refers to an integer. Write a code segment that prints the integer’s absolute value without using Python’s abs function. Solution: if x < 0: print(-x) else: print(x) 3. Write a loop that counts the number of space characters in a string. Recall that the space character is represented as ' '. Solution: count = 0 for ch in theString: if ch == " ": count += 1 print(count) 4. Assume that the variables x and y refer to strings. Write a code segment that prints these strings in alphabetical order. You should assume that they are not equal. Solution: if x < y: print(x, y) Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 25 website, in whole or in part. else: print(y, x) 5. Explain how to check for an invalid input number and prevent it being used in a program. You may assume that the user enters a number. Solution: After the input is received, it is compared to the lower and upper bounds of the range of valid numbers. If the number is less than or equal to the upper bound and greater than or equal to the lower bound, it is used in the computation. Otherwise, the program moves to the next statement after the selection statement. 6. Construct truth tables for the following Boolean expressions: a. not (A or B) b. not A and not B Solution: a. A B not (A or B) True True False True False False False True False False False True b. A B not A and not B True True False True False False False True False False False True 7. Explain the role of the trailing else part of an extended if statement. Solution: The trailing else part of an extended if statement includes the default action that is performed if none of the conditions that occur earlier in the statement are true. 8. The variables x and y refer to numbers. Write a code segment that prompts the user for an arithmetic operator and prints the value obtained by applying that operator to x and y. Solution: op = input("Enter an arithmetic operator: ") if op == "+": print(x + y) elif op == "-": print(x - y) elif op == "*": print(x * y) elif op == "/": print(x / y) Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 26 website, in whole or in part. else: print(x % y) 9. Does the Boolean expression count > 0 and total // count > 0 contain a potential error? If not, why not? Solution: No, the statement does not contain an error, which to a casual reader might look like an attempt to divide a number by zero. The first comparison detects when the number is zero, and then short-circuit evaluation of the and operation prevents the second comparison from being executed. EXERCISE 3.4 1. Translate the following for loops to equivalent while loops: a. for count in range(100): print(count) b. for count in range(1, 101): print(count) c. for count in range(100, 0, -1): print(count) Solution: a. count = 0 while count < 100: print(count) count += 1 b. count = 1 while count <= 100: print(count) count += 1 c. count = 100 while count > 0: print(count) count -= 1 6. The factorial of an integer N is the product of the integers between 1 and N, inclusive. Write a while loop that computes the factorial of a given integer N. Solution: product = 1 count = 1 while count <= n: product *= count count += 1 Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 27 website, in whole or in part. 7. The log2 of a given number N is given by M in the equation N = 2M. Using integer arithmetic, the value of M is approximately equal to the number of times N can be evenly divided by 2 until it becomes 0. Write a loop that computes this approximation of the log2 of a given number N. You can check your code by importing the function and evaluating the expression round((N, 2)) (note that the function returns a floating-point value). Solution: logbase2 = 0 while n > 0: n //= 2 logbase2 += 1 logbase2 -= 1 8. Describe the purpose of the break statement and the type of problem for which it is well suited. Solution: The break statement exits the enclosing loop statement. The break statement can be used when a loop must execute at least one pass. In that case, a break statement is embedded in an if statement that tests for the truth of a termination condition for the loop. This if statement usually occurs in the middle or at the end of the loop’s body. 9. What is the maximum number of guesses necessary to guess correctly a given number between the numbers N and M? Solution: log2(M - N + 1) 10. What happens when the programmer forgets to update the loop control variable in a while loop? Solution: The loop might not halt. REVIEW QUESTIONS ANSWERS 21. How many times does a loop with the header for count in range (10): execute the statements in its body? e. 9 times f. 10 times g. 11 times h. 12 times Answer: b Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 28 website, in whole or in part. Feedback: i. Incorrect. Off by 1 (too few). j. Correct. The single argument to range specifies the number of iterations. k. Incorrect. Off by 1 (too many). l. Incorrect. Off by 2 (too many). 22. A for loop is convenient for a. making choices in a program. b. running a set of statements a predictable number of times. c. counting through a sequence of numbers. d. describing conditional iteration. Answer: b, c Feedback: i. Incorrect. The if/else statement is used to make choices. j. Correct. The for loop’s header can specify the number of iterations. k. Correct. The for loop’s header includes a variable that is bound to each integer in a range of integers, and this variable can be referenced in the body of the loop. l. incorrect. The while loop is used for conditional iteration. 23. What is the output of the loop for count in range(5): print(count, end = " ")? i. j. 1 2 3 4 k. l. 5 Answer: c Feedback: i. Inorrect. When range has a single argument, its sequence of integers begins with 0, not 1. j. Incorrect. range counts through the number of integers specified by its single argument (5), and there are only 4 of these in this answer. k. Correct. range counts through the integers from 0 through its single argument minus 1 (4 in this case). l. Incorrect. range counts through the number of integers specified by its single argument (5), and there are 6 of these in this answer. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 29 website, in whole or in part. 24. When the function range receives two arguments, what does the second argument specify? a. The last value of a sequence of integers b. The last value of a sequence of integers plus 1 c. The last value of a sequence of integers minus 1 d. The step value for the loop Answer: b Feedback: i. Incorrect. This would be off by 1 (too many). j. Correct. range with two arguments visits integers from the first argument through the last argument minus 1, so that argument equals this integer plus 1. k. Incorrect. This would be off by 1 (too few). l. Incorrect. range would need three arguments to specify a step value (the third argument). 25. Consider the following code segment: x = 5 y = 4 if x > y: print(y) else: print(x) What value does this code segment print? a. 4 b. 5 c. 9 d. 20 Answer: a Feedback: i. Correct. x (5) is greater than y (4), so y (4) is printed. j. Incorrect. x (5) is not less than or equal to y (4), so x (5) is not printed. k. Incorrect. x (5) is not the sum of 4 and 5. l. Incorrect. x (5) is not the product of 4 and 5. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 30 website, in whole or in part. 26. A Boolean expression using the and operator returns True when i. both operands are true j. one operand is true k. neither operand is true l. one operand is false Answer: a Feedback: i. Correct. The and operator returns True only when both of its operands are true. j. Incorrect. The and operator returns False when only one of its operands is true. k. Incorrect. The and operator returns False when neither of its operands is true. l. Incorrect. The and operator returns False when one of its operands is false 27. By default, the while loop is a(n) i. entry-controlled loop j. exit-controlled loop k. count-controlled loop l. loop that iterates a definite, preestablished number of times Answer: a Feedback: i. Correct. The while loop’s continuation condition is tested at the top of the loop. If this condition is false, the statements within the loop are not executed. j. Incorrect. When the final statement in the while loop’s body is executed, control is returned to the condition at the top of the loop. k. Incorrect. Sometimes, but not always. l. Incorrect. Sometimes, but not always. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 31 website, in whole or in part. 28. Consider the following code segment: count = 5 while count > 1: print(count, end = " ") count -= 1 What is the output produced by this code? a. b. 2 3 4 5 c. d. 5 4 3 2 Answer: d Feedback: i. Incorrect. The loop counts down, as shown by the use of the > operator in its continuation condition and the decrement of the loop control variable. j. Incorrect. The loop counts down, as shown by the use of the > operator in its continuation condition and the decrement of the loop control variable. k. Incorrect. The loop does not include 1 in the output, because the continuation condition is false when the loop control variable equals 1. l. Correct. The loop counts down from 5 to 2 and prints these values, but does not print 1, which halts the loop. 29. Consider the following code segment, which is intended to print the integers 1 through 10: count = 1 while count <= 10: print(count, end = " ") Which of the following describes the error in this code? a. The loop is off by 1 b. The loop control variable is not properly initialized. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 32 website, in whole or in part. c. The comparison points the wrong way. d. The loop is infinite. Answer: d Feedback: a. Incorrect. It appears that the loop will visit all of the numbers from 1 to 10. b. Incorrect. The loop control variable is properly initialized for the sequence 1 through 10. c. Incorrect. It appears that the loop is set up to halt when count becomes 11. d. Correct. The loop does not update the loop control variable by incrementing it, so its value will always be 1, so it will never reach 11, so the continuation condition, count <= 10, will always be true. 30. Consider the following code segment: theSum = 0.0 while True: number = input("Enter a number: ") if number == "": break theSum += float(number) How many iterations does this loop perform? a. None b. At least one c. Zero or more d. Ten Answer: b Feedback: a. Incorrect. The loop’s continuation condition, True, causes the loop to execute at least once. b. Correct. The loop executes until the user enters the empty string (presses just the return key) as input. Because the loop’s continuation condition is always true, at least one input must occur. c. Incorrect. Because the loop’s continuation condition is always true, at least one input must occur. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 33 website, in whole or in part. d. Incorrect. The loop might take10 inputs, but this might not always be the case. The loop takes one or more inputs until the user just presses the return key. PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 15. Write a program in the file that accepts the lengths of three sides of a triangle as inputs. The program output should indicate whether or not the triangle is an equilateral triangle. (LO: 3.3) Solution: See posted on the Instructor Companion Site. 16. Write a program in the file that accepts the lengths of three sides of a triangle as inputs. The program output should indicate whether or not the triangle is a right triangle. Recall from the Pythagorean theorem that in a right triangle, the square of one side equals the sum of the squares of the other two sides. (LO: 3.3) Solution: See posted on the Instructor Companion Site. 17. Modify the guessing-game program of Section 3.5 in the file so that the user thinks of a number that the computer must guess. The computer must make no more than the minimum number of guesses, and it must prevent the user from cheating by entering misleading hints. (Hint: Use the function to compute the minimum number of guesses needed after the lower and upper bounds are entered.) (LO: 3.3, 3.4) Solution: See posted on the Instructor Companion Site. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 34 website, in whole or in part. 18. A standard science experiment is to drop a ball and see how high it bounces. Once the ―bounciness‖ of the ball has been determined, the ratio gives a bounciness index. For example, if a ball dropped from a height of 10 feet bounces 6 feet high, the index is 0.6, and the total distance traveled by the ball is 16 feet after one bounce. If the ball were to continue bouncing, the distance after two bounces would be 10 ft + 6 ft + 6 ft + 3.6 ft = 25.6 ft. Note that the distance traveled for each successive bounce is the distance to the floor plus 0.6 of that distance as the ball comes back up. Write a program in the file that lets the user enter the initial height from which the ball is dropped and the number of times the ball is allowed to continue bouncing. Output should be the total distance traveled by the ball. (LO: 3.1) Solution: See posted on the Instructor Companion Site. 19. A local biologist needs a program to predict population growth. The inputs would be the initial number of organisms, the rate of growth (a real number greater than 0), the number of hours it takes to achieve this rate, and a number of hours during which the population grows. For example, one might start with a population of 500 organisms, a growth rate of 2, and a growth period to achieve this rate of 6 hours. Assuming that none of the organisms die, this would imply that this population would double in size every 6 hours. Thus, after allowing 6 hours for growth, we would have 1000 organisms, and after 12 hours, we would have 2000 organisms. Write a program in the file that takes these inputs and displays a prediction of the total population. (LO: 3.1) Solution: See posted on the Instructor Companion Site. 20. The German mathematician Gottfried Leibniz developed the following method to approximate the value of π: π/4 = 1 - 1/3 + 1/5 - 1/7 + . . . Write a program in the file that allows the user to specify the number of iterations used in this approximation and that displays the resulting value. (LO: 3.1) Solution: See posted on the Instructor Companion Site. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 35 website, in whole or in part. 21. Teachers in most school districts are paid on a schedule that provides a salary based on their number of years of teaching experience. For example, a beginning teacher in the Lexington School District might be paid $30,000 the first year. For each year of experience after this first year, up to 10 years, the teacher receives a 2% increase over the preceding value. Write a program in the file that displays a salary schedule, in tabular format, for teachers in a school district. The inputs are the starting salary, the percentage increase, and the number of years in the schedule. Each row in the schedule should contain the year number and the salary for that year. (LO: 3.1, 3.2) Solution: See posted on the Instructor Companion Site. 22. The greatest common divisor of two positive integers, A and B, is the largest number that can be evenly divided into both of them. Euclid’s algorithm can be used to find the greatest common divisor (GCD) of two positive integers. You can use this algorithm in the following manner: a. Compute the remainder of dividing the larger number by the smaller number. b. Replace the larger number with the smaller number and the smaller number with the remainder. c. Repeat this process until the smaller number is zero. d. The larger number at this point is the GCD of A and B. Write a program in the file that lets the user enter two integers and then prints each step in the process of using the Euclidean algorithm to find their GCD. (LO: 3.4) Solution: See posted on the Instructor Companion Site. 23. Write a program in the file that receives a series of numbers from the user and allows the user to press the enter key to indicate that he or she is finished providing inputs. After the user presses the enter key, the program should print the sum of the numbers and their average. (LO: 3.3, 3.4) Solution: See posted on the Instructor Companion Site. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 36 website, in whole or in part. 11. The credit plan at TidBit Computer Store specifies a 10% down payment and an annual interest rate of 12%. Monthly payments are 5% of the listed purchase price, minus the down payment. Write a program in the file that takes the purchase price as input. The program should display a table, with appropriate headers, of a payment schedule for the lifetime of the loan. Each row of the table should contain the following items:  the month number (beginning with 1)  the current total balance owed  the interest owed for that month  the amount of principal owed for that month  the payment for that month  the balance remaining after payment The amount of interest for a month is equal to balance * rate / 12. The amount of principal for a month is equal to the monthly payment minus the interest owed. (LO: 3.2, 3.3, 3.4) Solution: See posted on the Instructor Companion Site. 12. In the game of Lucky Sevens, the player rolls a pair of dice. If the dots add up to 7, the player wins $4; otherwise, the player loses $1. Suppose that, to entice the gullible, a casino tells players that there are lots of ways to win: (1, 6), (2, 5), and so on. A little mathematical analysis reveals that there are not enough ways to win to make the game worthwhile; however, because many people’s eyes glaze over at the first mention of mathematics, your challenge is to write a program in the file that demonstrates the futility of playing the game. Your program should take as input the amount of money that the player wants to put into the pot, and play the game until the pot is empty. At that point, the program should print the number of rolls it took to break the player, as well as maximum amount of money in the pot. (LO: 3.3, 3.4) Solution: See posted on the Instructor Companion Site. Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 37 website, in whole or in part. DEBUGGING EXERCISE SOLUTION Jack has written a program that computes and prints the average of 10 test scores. The program prompts the user for each input score. Here is the code for this program: count = 1 while count < 10: score = int(input("Enter test score number " + str(count) + ": ") total = total + score count = count + 1 average = total / count print("The average test score is", average) This program contains an error. State what type of error this is, describe how it is detected, and explain how to correct it. Solution When the program is run, the user is prompted for 9 inputs instead of the expected 10. This is a logic error. It is also a classic case of an off-by-one error, where the input loop performs one less iteration than expected. The cause of this is that the programmer has used the < operator instead of the <= operator to express the loop continuation condition. To guarantee that the loop iterates from 1 through 10, the programmer should replace the < operator with the <= operator in the loop header. Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS, 3E, CY24, 9780357881019; CHAPTER 4, STRINGS AND TEXT FILES TABLE OF CONTENTS Exercise Solutions..................................................................................................................................... 38 Exercise 4.1............................................................................................................................................. 38 Exercise 4.2............................................................................................................................................. 39 Exercise 4.3............................................................................................................................................. 39 Exercise 4.4............................................................................................................................................. 40 Review Questions Answers....................................................................................................................... 43 Programming Exercises Solutions........................................................................................................... 47 Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 38 website, in whole or in part. Debugging Exercise Solution.................................................................................................................... 50 EXERCISE SOLUTIONS EXERCISE 4.1 14. Assume that the variable data refers to the string "". Write the values of the following expressions: a. data[2] b. data[-1] c. len(data) d. data[0:8] Solution: a. 'p' b. 'e' c. 13 d. 'myprogra' 15. Assume that the variable data refers to the string "". Write the expressions that perform the following tasks: a. Extract the substring "gram" from data. b. Remove the extension ".exe" from data. c. Extract the character at the middle position from data. Solution: a. data[5:9] b. data[0:9] c. data[int(len(data) / 2)] 16. Assume that the variable myString refers to a string. Write a code segment that uses a loop to print the characters of the string in reverse order. Solution: for index in range(len(myString) - 1, -1, -1): print(myString[index], end = '') Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 39 website, in whole or in part. 17. Assume that the variable myString refers to a string and the variable reversedString refers to an empty string. Write a loop that adds the characters from myString to reversedString in reverse order. Solution: for ch in myString: reversedString = ch + reversedString EXERCISE 4.2 15. Write the encrypted text of each of the following words using a Caesar cipher with a distance value of +3: a. Python b. hacker c. wow Solution: a. sbwkrq b. kdfnhu c. zrz 16. Consult the Table of ASCII values in Chapter 2 and suggest how you would modify the encryption and decryption scripts in this section to work with strings containing all of the printable characters. Solution: The ASCII value for the letter ―z‖ would be replaced by the ASCII value 127 (the last character in the set), and the ASCII value for the letter ―a‖ would be replaced by the ASCII value 0 (the first character in the set). 17. You are given a string that was encoded by a Caesar cipher with an unknown distance value. The text can contain any of the printable ASCII characters. Suggest an algorithm for cracking this code. Solution: The decryption algorithm would be run with the encrypted text and each possible distance value (ranging from –127 through 127, excluding 0), and the results inspected for the plain text. The distance value that gives the plain text is then used to decrypt other encoded messages. EXERCISE 4.3 9. Translate each of the following numbers to decimal numbers: a. 110012 b. 1000002 c. 111112 Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 40 website, in whole or in part. Solution: f. 25 g. 32 h. 31 10. Translate each of the following numbers to binary numbers:a. 47110 b. 12710 c. 6410 Solution: a. 101111 b. 1111111 c. 1000000 11. Translate each of the following numbers to binary numbers:a. 4718 b. 1278 c. 648 Solution: a. 100111 b. 1010111 c. 110100 12. Translate each of the following numbers to decimal numbers:a. 4718 b. 1278 c. 648 Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 41 website, in whole or in part. Solution: a. 39 b. 87 c. 52 13. Translate each of the following numbers to decimal numbers:a. 4716 b. 2716 c. AA16 Solution: a. 71 b. 295 c. 170 EXERCISE 4.4 2. Assume that the variable data refers to the string "Python rules!". Use a string method from Table 4-2 to perform the following tasks: a. Obtain a list of the words in the string. b. Convert the string to uppercase. c. Locate the position of the string "rules". d. Replace the exclamation point with a question mark. Solution: d. () e. () f. ("rules") g. ce("!", "?") 11. Using the value of data from Exercise 1, write the values of the following expressions: c. ith('i') Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible 42 website, in whole or in part. d. "totally ".join((x)) Solution: c. False d. "Python totally rules! " EXERCISE 4.5 1. Write a code segment that opens a file named for input and prints the number of lines in the file. Solution: count = 0 inputFile = open("", 'r') for line in inputFile: count += 1 print("There are", count, "lines.") 2. Write a code segment that opens a file for input and prints the number of four-letter words in the file. Solution: count = 0 inputFile = open("", 'r') for line in inputFile: wordlist = () for word in wordlist: if len(word) == 4: count += 1 print("There are", count, "lines.") 3. Assume that a file contains integers separated by newlines. Write a code segment that opens the file and prints the average value of the integers. Solution: count = 0 sum = 0 inputFile = open("", 'r') for line in inputFile: sum += int(()) count += 1 if count == 0: averag

Show more Read less
Institution
Module











Whoops! We can’t load your doc right now. Try again or contact support.

Connected book

Written for

Module

Document information

Uploaded on
June 19, 2025
Number of pages
164
Written in
2024/2025
Type
Exam (elaborations)
Contains
Questions & answers

Subjects

Content preview

Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction




Solution and Answer Guide For All
Chapters
LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS, 3E, CY24, 9780357881019; CHAPTER 1,
INTRODUCTION


TABLE OF CONTENTS
Exercise Solutions ....................................................................................................................................... 1
Exercise 1.1 ............................................................................................................................................... 1
Exercise 1.2 ............................................................................................................................................... 2
Exercise 1.3 ............................................................................................................................................... 3
Review Questions Answers......................................................................................................................... 4
Programming Exercises Solutions ............................................................................................................. 8
Debugging Exercises Solutions .................................................................................................................. 8




EXERCISE SOLUTIONS

EXERCISE 1.1
1. List three common types of computing agents.

Solution:

Human beings, desktop computers, cell phones

2. Write an algorithm that describes the second part of the process of making change (counting out the coins
and bills).

Solution:

There are various ways to do this, but here is one:

Repeat
Select the largest unit of money that is less than or equal to the remaining change
Subtract this unit from the remaining change
Until the remaining change is 0
The collection of units selected represent the change


3. Write an algorithm that describes a common task, such as baking a cake.




1

,Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction


Solution:

There are various ways to do this, but here is one:

Preheat an oven to 375 degrees
Add 1 cup of water and 1 egg to a mixing bowl
Beat the liquid mixture in the bowl until the ingredients are blended
Add the contents of a boxed cake mix to the mixing bowl
Beat the mixture in the bowl until the ingredients are blended
Pour the contents of the mixing bowl into a lightly greased cake pan
Bake the cake in the oven for 45 minutes


4. Describe an instruction that is not well defined and thus could not be included as a step in an algorithm.
Give an example of such an instruction.

Solution:

Attempting to divide a number by 0

5. In what sense is a laptop computer a general-purpose problem-solving machine?

Solution:

A laptop computer is a general-purpose problem-solving machine because it is programmable and can
solve any problem for which there is an algorithm.


6. List four devices that use computers and describe the information that they process. (Hint: Think of the
inputs and outputs of the devices.)

Solution:
Digital camera—images, music player—sound, cell phone—text, ATM—numbers



EXERCISE 1.2
1. List two examples of input devices and two examples of output devices.

Solution:
Input devices—keyboard and mouse, output devices—monitor and speakers


2. What does the central processing unit (CPU) do?

Solution:
The CPU fetches, decodes, and executes instructions.


3. How is information represented in hardware memory?

Solution:
Information is represented using binary notation, which in hardware is a pattern of voltage levels.



2

,Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction


4. What is the difference between a terminal-based interface and a graphical user interface?

Solution:
A terminal-based interface supports only the input and output of text with a keyboard and monitor. A
graphical user interface supports the output of images and the manipulation of them with a pointing device,
the mouse.


5. What role do translators play in the programming process?

Solution:
A translator converts a program written in a high-level language (human readable and writable) to an
equivalent program in a low-level language (machine readable and executable).


EXERCISE 1.3
1. Describe what happens when the programmer enters the string "Greetings!" in the Python shell.

Solution:

Python reads the string "Greetings!", evaluates it, and displays this string (including single quotes)
in the shell.


2. Write a line of code that prompts the user for their name and saves the user’s input in a variable called
name.

Solution:
name = input("Enter your name: ")


3. What is a Python script?

Solution:

A Python script is a complete Python program that can be run from a computer’s operating system.

4. Explain what goes on behind the scenes when your computer runs a Python program.

Solution:

If the program has not already been translated, Python’s compiler translates it to byte code. The Python
virtual machine then executes this code.




3

, Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction



REVIEW QUESTIONS ANSWERS
1. Which of the following is an example of an algorithm?

a. A dictionary

b. A recipe

c. A shopping list

d. The spelling checker of a word processor

Answer: b

Feedback:
a. Incorrect. A dictionary is a data structure.
b. Correct. A recipe is a set of instructions that describes a process that halts with a solution to a problem.
c. Incorrect. A shopping list is a data structure.
d. Incorrect. A word processor is a program that consists of instructions and data.



2. Which of the following contains information?

a. An audio CD

b. A refrigerator

c. An automobile

d. A stereo speaker

Answer: a

Feedback:

a. Correct. The information on an audio CD represents sound.
b. Incorrect. A refrigerator contains just food, if it’s not empty.
c. Incorrect. An automobile contains a steering wheel, engine, exhaust pipe, and so on.
d. Incorrect. A stereo speaker contains a magnetic coil, wires, and so on.



3. Which of the following is a general-purpose computing device?

a. A smartphone

b. A portable music player

c. A microwave oven

d. A programmable thermostat



4
£10.05
Get access to the full document:

100% satisfaction guarantee
Immediately available after payment
Both online and in PDF
No strings attached


Also available in package deal

Reviews from verified buyers

Showing all reviews
2 months ago

2 months ago

Thank you for the positive review. If you're Looking for Any Study Materials (exams, test bank, ATI, Hesi etc.) Contact me , we’re looking forward to hear from you soon! & HAVE A GREAT DAY!!!!!!

5.0

1 reviews

5
1
4
0
3
0
2
0
1
0
Trustworthy reviews on Stuvia

All reviews are made by real Stuvia users after verified purchases.

Get to know the seller

Seller avatar
Reputation scores are based on the amount of documents a seller has sold for a fee and the reviews they have received for those documents. There are three levels: Bronze, Silver and Gold. The better the reputation, the more your can rely on the quality of the sellers work.
TestsBanks University of Greenwich (London)
Follow You need to be logged in order to follow users or courses
Sold
866
Member since
4 year
Number of followers
180
Documents
2252
Last sold
16 hours ago
Accounting, Finance, Statistics, Computer Science, Nursing, Chemistry, Biology & More — A+ Test Banks, Study Guides & Solutions

Welcome to TestsBanks! Best Educational Resources for Student I offer test banks, study guides, and solution manuals for all subjects — including specialized test banks and solution manuals for business books. My materials have already supported countless students in achieving higher grades, and I want them to be the guide that makes your academic journey easier too. I’m passionate, approachable, and always focused on quality — because I believe every student deserves the chance to excel. THANKS ALOT!!

Read more Read less
4.1

131 reviews

5
79
4
19
3
12
2
6
1
15

Recently viewed by you

Why students choose Stuvia

Created by fellow students, verified by reviews

Quality you can trust: written by students who passed their exams and reviewed by others who've used these revision notes.

Didn't get what you expected? Choose another document

No problem! You can straightaway pick a different document that better suits what you're after.

Pay as you like, start learning straight away

No subscription, no commitments. Pay the way you're used to via credit card and download your PDF document instantly.

Student with book image

“Bought, downloaded, and smashed it. It really can be that simple.”

Alisha Student

Frequently asked questions