Solution Manual & Test Bank for Python For Everyone, 3rd Edition

Page 1

Solution Manual & Test Bank for Python For Everyone, 3rd Edition

richard@qwconsultancy.com

1|Pa ge


1. A computer program is a sequence of: 1. ones and zeroes. 2. instructions and decisions. 3. primary and secondary storage. 4. processors and compilers. Section 1.1 Computer Programs Title What is a computer program? type mc section 1.1 Computer Programs id testbank-py-1-ch01-01 2. Computers are machines that: 1. are imprecise and slow. 2. design computer programs. 3. execute programs. 4. carry out a very narrow range of tasks. Section 1.1 Computer Programs Title What is a computer? type mc section 1.1 Computer Programs id testbank-py-1-ch01-02 3. Which of the following refers to a collection of programs that a computer executes? 1. Compiler 2. Software 3. Instructions 4. Source Code Section 1.1 Computer Programs Title What term refers to a collection of programs? type mc from testbank-py-1-ch01-03 section 1.1 Computer Programs id testbank-py-2-ch01-03 4. Which of the follow statements is most correct? 1. Computer programs are comprised of a large number of simple instructions. 2. Computer programs are comprised of a large number of sophisticated instructions. 3. Computer programs are comprised of a small number of simple instructions. 4. Computer programs are comprised of a small number of sophisticated instructions. Section


4. 1.1 Computer Programs Title What are computer programs comprised of? type mc section 1.1 Computer Programs id testbank-py-1-ch01-51 5. Which parts of the computer store program code? 1. CPU 2. Secondary storage 3. Monitor 4. Keyboard Section 1.2 The Anatomy of a Computer Title Which parts of the computer store program code? type mc section 1.2 The Anatomy of a Computer id testbank-py-1-ch01-04 6. Which of the following items is NOT considered hardware: 1. a keyboard. 2. a speaker. 3. a program. 4. a microphone. Section 1.2 The Anatomy of a Computer Title What is considered hardware type mc section 1.2 The Anatomy of a Computer id testbank-py-1-ch01-05 7. The Central Processing Unit is primarily responsible for: 1. ensuring data persists when electrical power is turned off. 2. enabling a human user to interact with the computer. 3. interconnecting computers that are separated by distance. 4. performing program control and data processing. Section 1.2 The Anatomy of a Computer Title What is a CPU? type mc section 1.2 The Anatomy of a Computer


7. id testbank-py-1-ch01-06 8. Computers store both data and programs not currently running in: 1. Primary storage. 2. Central processing unit. 3. Secondary storage. 4. Transistors. Section 1.2 The Anatomy of a Computer Title Where are programs and data stored? type mc section 1.2 The Anatomy of a Computer id testbank-py-1-ch01-07 9. Which of the following hardware devices is NOT considered an input device? 1. Keyboard 2. Monitor 3. Mouse 4. Microphone Section 1.2 The Anatomy of a Computer Title What is considered input hardware? type mc section 1.2 The Anatomy of a Computer id testbank-py-1-ch01-08 10. Which of the following hardware devices is NOT considered an output device? 1. Speaker 2. Monitor 3. Printer 4. Microphone Section 1.2 The Anatomy of a Computer Title What is considered output hardware? type mc section 1.2 The Anatomy of a Computer id testbank-py-1-ch01-09 11. When the computer begins to run a program, 1. the program is moved from secondary storage to memory. 2. the program is moved from secondary storage to the network controller. 3. the program is moved from the CPU to memory.


11.

4. the program is moved from the CPU to secondary storage. Section 1.2 The Anatomy of a Computer Title What happens when a program begins to run? type mc from testbank-py-1-ch01-10 section 1.2 The Anatomy of a Computer id testbank-py-2-ch01-10

12. What part of the computer carries out arithmetic operations, such as addition, subtraction, multiplication and division? 1. CPU 2. Network 3. Primary storage 4. Secondary storage Section 1.2 The Anatomy of a Computer Title What part of the computer performs arithmetic? type mc from testbank-py-1-ch01-11 section 1.2 The Anatomy of a Computer id testbank-py-2-ch01-11 13. In order to run Python programs, the computer needs to have software called a(n)? 1. debugger 2. interpreter 3. windows 4. assembler Section 1.3 The Python Programming Language Title Software needed to run Python on a computer? type mc section 1.3 The Python Programming Language id testbank-py-1-ch01-46 14. High-level programming languages were created to: 1. Allow programmers to describe the solution to a problem one CPU instruction at a time 2. Make programming less error-prone and less tedious 3. Maximize the running time of programs 4. Translate CPU instructions into high-level instructions Section 1.3 The Python Programming Language


14. Title Why were high-level programming languages created? type mc from testbank-py-1-ch01-12 section 1.3 The Python Programming Language id testbank-py-2-ch01-12 15. What are two of the most important benefits of the Python language? 1. Advanced mathematical equations and fast programs 2. Ease of use and fast programs 3. Ease of use and portability 4. Fast programs and smaller programs Section 1.3 The Python Programming Language Title What are the benefits of Python? type mc from testbank-py-1-ch01-13 section 1.3 The Python Programming Language id testbank-py-2-ch01-13 16. Which of the following is not a benefit of the Python programming language compared to other popular programming languages like Java, C and C++? 1. Python encourages experimentation and rapid turn around 2. Python has a cleaner syntax 3. Python is easier to use 4. Python programs run more quickly Section 1.3 The Python Programming Language Title What are the benefits of Python compared to other programming languages? type mc section 1.3 The Python Programming Language id testbank-py-1-ch01-52 17. What is wrong with the following code snippet: num1 = 10 num2 = 20 num3 = 30 total = Num1 + Num2 + Num3 1. Nothing, the variable total will be the sum of the three numbers 2. Python is case sensitive so Num1, Num2, and Num3 are undefined 3. total must be initialized to zero first


17.

4. The numbers should be 10.0, 20.0 and 30.0 Section 1.4 Becoming Familiar with Your Programming Environment Title What is wrong with the following code snippet? type mc section 1.4 Becoming Familiar with Your Programming Environment id testbank-py-1-ch01-14

18. What is the difference between an editor and an interpreter? 1. An editor allows program files to be entered and modified; an interpreter reads and executes program files 2. An editor allows program files to be entered and modified; an interpreter produces an indexed database of terms and keywords 3. An editor allows program files to be entered and modified; an interpreter produces an organized list of files 4. An editor converts program files into an executable program; an interpreter allows program files to be entered and modified Section 1.4 Becoming Familiar with Your Programming Environment Title What is the difference between an editor and a compiler? type mc section 1.4 Becoming Familiar with Your Programming Environment id testbank-py-1-ch01-16 19. What reads Python programs and executes the program instructions? 1. editor 2. CPU 3. compiler 4. interpreter Section 1.4 Becoming Familiar with Your Programming Environment Title What is used to execute a Python program? type mc section 1.4 Becoming Familiar with Your Programming Environment id testbank-py-1-ch01-17 20. What extension is used for Python files? 1. .Python 2. .py 3. .dat 4. .txt Section 1.4 Becoming Familiar with Your Programming Environment Title What extension is used for Python source files?


20. type mc section 1.4 Becoming Familiar with Your Programming Environment id testbank-py-1-ch01-18 21. By entering the command python3, the program runs in which mode? 1. interactive mode 2. print mode 3. command mode 4. backup mode Section 1.4 Becoming Familiar with Your Programming Environment Title What mode is invoked when the user enters "python" at the command prompt? type mc section 1.4 Becoming Familiar with Your Programming Environment id testbank-py-1-ch01-19 22. The Python compiler reads the file containing your source code and converts it to: 1. machine code 2. assembly code 3. byte code 4. virtual machine code Section 1.4 Becoming Familiar with Your Programming Environment Title What type of code is created by the Python compiler? type mc section 1.4 Becoming Familiar with Your Programming Environment id testbank-py-1-ch01-20 23. What is the correct sequence of steps invoked by the Python Interpreter: 1. source code -> virtual machine -> byte code -> compiler 2. source code -> compiler -> byte code -> virtual machine 3. compiler -> source code -> virtual machine -> byte code 4. byte code -> virtual machine -> source code -> compiler Section 1.4 Becoming Familiar with Your Programming Environment Title What is the role of the Interpreter? type mc section 1.4 Becoming Familiar with Your Programming Environment id testbank-py-1-ch01-21


24. An integrated development environment bundles tools for programming into a unified application. What kinds of tools are usually included? 1. A web browser 2. An editor and an interpreter 3. Presentation tools 4. Source files and bytecode files Section 1.4 Becoming Familiar with Your Programming Environment Title What kind of tools can be found in an integrated development environment? type mc from testbank-py-1-ch01-15 section 1.4 Becoming Familiar with Your Programming Environment id testbank-py-2-ch01-15 25. A Python interpreter is: 1. a folder hierarchy 2. a piece of hardware 3. a piece of software 4. a type of secondary storage Section 1.4 Becoming Familiar with Your Programming Environment Title What is a Python virtual machine? type mc from testbank-py-1-ch01-47 section 1.4 Becoming Familiar with Your Programming Environment id testbank-py-2-ch01-47 26. A collection of programming instructions that carry out a particular task is called a: 1. program 2. compiler 3. function 4. comment Section 1.5 Analyzing Your First Program Title What is a collection of programming instructions called? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-24 27. To use or call a function, you need to specify: 1. the function name and its arguments 2. the function name only 3. the function name and at least one argument


27.

4. the function name and a comment describing its use Section 1.5 Analyzing Your First Program Title How do you call a function? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-25

28. A sequence of characters enclosed in quotes is called: 1. a string 2. a list 3. a function 4. an argument Section 1.5 Analyzing Your First Program Title What is a sequence of characters enclosed in quotes called? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-26 29. Which of the following is considered a string in Python? 1. Today is Wednesday 2. "Today is Wednesday" 3. # Today is Wednesday # 4. Today_is_Wednesday Section 1.5 Analyzing Your First Program Title What is a string in Python? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-27 30. What is wrong with the following code snippet? print("Hello") print("World!") 1. The print function cannot be called twice 2. The print function is missing an argument 3. Nothing, the program prints Hello World on the same line 4. The second line should not be indented Section 1.5 Analyzing Your First Program Title


30. What is wrong with the code snippet? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-28 31. What is printed by the following code snippet? print(25 + 84) 1. 2584 2. 109 3. 25 + 84 4. Nothing, this code snipped causes a compile time error Section 1.5 Analyzing Your First Program Title What is printed by a given code snippet? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-29 32. What is printed by the following code snippet? print("The answer is", 25 + 84) 1. The answer is 2584 2. The answer is 109 3. The answer is 25 + 84 4. Nothing, this code snipped causes a compile time error Section 1.5 Analyzing Your First Program Title What is printed by a given code snippet? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-30 33. What is printed by the following code snippet? print("The answers are:", 4 + 3 * 2, 7 * 5 - 24) 1. The answers are: 10 11 2. The answers are: 14 11 3. The answers are: 24 10 4. Nothing, this code snipped causes a compile time error Section 1.5 Analyzing Your First Program


33. Title What is printed by a given code snippet? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-31 34. What is printed by the following code snippet? print("25 + 84") 1. 2584 2. 109 3. 25 + 84 4. Nothing, this code snipped causes a compile time error Section 1.5 Analyzing Your First Program Title What is printed by a given code snippet? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-32 35. What is printed by the following code snippet? print(Hello) 1. Nothing, an error is produced indicating that Hello is not defined 2. Hello 3. 'Hello' 4. "Hello" Section 1.5 Analyzing Your First Program Title What is printed by a given code snippet? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-33 36. What is printed by the following code snippet? print("Good", "Morning", "Class", "!") 1. GoodMorningClass! 2. Good Morning Class! 3. Good Morning Class ! 4. nothing, this code produces a syntax error Section


36. 1.5 Analyzing Your First Program Title What is printed by a given code snippet? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-34 37. Which line in the following program is a comment line? 1: print("Your lucky number is...") 2: lucky = 7 3: # Display the lucky number 4: print(lucky) 1. Line number 1 2. Line number 2 3. Line number 3 4. Line number 4 Section 1.5 Analyzing Your First Program Title What is the syntax for a comment line? type mc from testbank-py-1-ch01-22 section 1.5 Analyzing Your First Program id testbank-py-2-ch01-22 38. What is the purpose of a comment? 1. A comment provides information to the virtual machine 2. A comment provides information to the compiler 3. A comment provides information to the programmer 4. A comment provides information to the user running the program Section 1.5 Analyzing Your First Program Title What is the purpose of a comment? type mc from testbank-py-1-ch01-23 section 1.5 Analyzing Your First Program id testbank-py-2-ch01-23 39. Which of the following code segments will display Hello World! when it is run? 1. print(Hello "," World"!") 2. print("Hello", "World!")


39.

3. print("Hello", "World", "!") 4. print("Hello", ",", "World", "!") Section 1.5 Analyzing Your First Program Title Which code segment displays the desired result? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-53

40. When a function is called, the values placed in parentheses are referred to as: 1. arguments 2. keywords 3. operators 4. statements Section 1.5 Analyzing Your First Program Title What are the parts of a function call? type mc section 1.5 Analyzing Your First Program id testbank-py-1-ch01-54 41. What is another name for a compile-time error? 1. Logic error 2. Semantic error 3. Syntax error 4. Lexicographic error Section 1.6 Errors Title What is another name for a compile-time error? type mc section 1.6 Errors id testbank-py-1-ch01-35 42. Although the following code statement is valid, print(10/0), what will happen when this code is executed? 1. The program prints 0 2. The error message ZeroDivisionError: int division or modulo by zero is displayed 3. The program runs, but nothing is printed 4. The error message SyntaxError: EOL while scanning string literal Section 1.6 Errors Title What is another name for a compile-time error? type


42.

mc section 1.6 Errors id testbank-py-1-ch01-36

43. The programmer, not the compiler, is responsible for testing a program to identify what? 1. Undefined symbols 2. Syntax errors 3. Logic errors 4. Out-of-memory errors Section 1.6 Errors Title The programmer, not the compiler, is responsible for testing a program to identify? type mc section 1.6 Errors id testbank-py-1-ch01-37 44. Which type of error is usually the most difficult to locate in your program? 1. Indentation Error 2. Logic Error 3. Syntax Error 4. Zero Division Error Section 1.6 Errors Title Which type of error is most difficult to locate? type mc section 1.6 Errors id testbank-py-1-ch01-55 45. What is it called when you describe the steps that are necessary for finding a solution to a problem in programming? 1. algorithm 2. compile 3. interpret 4. code Section 1.7 Problem Solving: Algorithm Design Title What is it called when you describe the steps that are necessary for finding a solution to a problem in programming? type mc section 1.7 Problem Solving: Algorithm Design id testbank-py-1-ch01-38


46. The following pseudocode calculates the total purchase price for an item including sales tax, what is the missing last line? Start by setting the total cost to zero. Ask the user for the item cost. Ask the user for the tax rate. Set the item tax to item cost times tax rate. _________________________________ 1. Set the total cost to the item cost plus the tax rate. 2. Set the total cost to the item cost times the tax. 3. Set the total cost to the item cost plus the tax. 4. Set the total cost to the item tax. Section 1.7 Problem Solving: Algorithm Design Title What is the missing pseudocode? type mc section 1.7 Problem Solving: Algorithm Design id testbank-py-1-ch01-39 47. What is the purpose of the following algorithm, written in pseudocode? num = 0 Repeat the following steps 15 times Ask user for next number If userNum > num num = userNum Print num 1. To print out the 15 numbers 2. To find the smallest among 15 numbers 3. To search for a particular number among 15 numbers 4. To find the highest among 15 numbers Section 1.7 Problem Solving: Algorithm Design Title What is the purpose of this algorithm? type mc section 1.7 Problem Solving: Algorithm Design id testbank-py-1-ch01-40 48. Which of the following is NOT an example of an algorithm? 1. A recipe to make chocolate chip cookies 2. A grocery list 3. Instructions for changing a flat tire 4. Steps required to calculate the amount of paint required to paint a room Section 1.7 Problem Solving: Algorithm Design Title


48. Which of the following is NOT an example of an algorithm? type mc section 1.7 Problem Solving: Algorithm Design id testbank-py-1-ch01-41 49. Which of the following pseudocode statements represents a decision? 1. For each number in a sequence... 2. While the balance is > 0 3. total cost = unit cost + tax 4. if total cost > 15 Section 1.7 Problem Solving: Algorithm Design Title Which of the following pseudocode statements represents a decision statement? type mc section 1.7 Problem Solving: Algorithm Design id testbank-py-1-ch01-42 50. A sequence of steps that is unambiguous, executable, and terminating is called: 1. a logarithm 2. a programming task 3. an algorithm 4. pseudocode Section 1.7 Problem Solving: Algorithm Design Title What is a list of steps that are unambiguous, executable, and terminating called? type mc section 1.7 Problem Solving: Algorithm Design id testbank-py-1-ch01-50 51. Which of the following pseudocode statements represents a repetition statement? 1. if total cost > 15 2. set i equal to 3 3. total cost = unit cost + tax 4. while the balance is > 0 Section 1.7 Problem Solving: Algorithm Design Title Which of the following pseudocode statements represents a repetition statement? type mc from testbank-py-1-ch01-43 section 1.7 Problem Solving: Algorithm Design


51. id testbank-py-2-ch01-43 52. Which of the following statements is NOT correct? 1. Pseudocode should be unambiguous. 2. Pseudocode should be executable. 3. Pseudocode should be properly formatted. 4. Pseudocode should be terminating. Section 1.7 Problem Solving: Algorithm Design Title Which of the following is NOT important when writing pseudocode? type mc from testbank-py-1-ch01-44 section 1.7 Problem Solving: Algorithm Design id testbank-py-2-ch01-44 53. Imagine that you are planning to buy a new cell phone. After doing some research, you have determined that there are two different cell phones that will meet your needs. These cell phones have different purchase prices and each mobile service provider charges a different rate for each minute that the cell phone is used. In order to determine which cell phone is the better buy, you need to develop an algorithm to calculate the total cost of purchasing and using each cell phone. Which of the following options lists all the inputs needed for this algorithm? 1. The cost of each cell phone and the rate per minute for each cell phone 2. The cost of each cell phone and the number of minutes provided with each cell phone 3. The cost of each cell phone, the rate per minute for each cell phone, and the number of minutes provided with each cell phone 4. The cost of each cell phone, the rate per minute for each cell phone, and the number of minutes you would use the cell phone Section 1.7 Problem Solving: Algorithm Design Title Which inputs do you need to calculate cost of purchasing/using cell phone? type mc from testbank-py-1-ch01-45 section 1.7 Problem Solving: Algorithm Design id testbank-py-2-ch01-45 54. Consider the following pseudocode. What does it produce? Create a list of consecutive integers from two to n (2, 3, 4, ..., n). Initially, let p equal 2. Repeat the following steps until p is greater than n: Remove all of the multiples of p less than or equal to n from the list. If the list contains a number greater than p Find the first number remaining in the list greater than p.


54.

Replace p with this number. Otherwise set p equal to n + 1 1. All even numbers up to n 2. All factorial numbers up to n 3. All odd numbers up to n 4. All prime numbers up to n Section 1.7 Problem Solving: Algorithm Design Title Software needed to run Python on a computer? type mc from testbank-py-1-ch01-48 section 1.7 Problem Solving: Algorithm Design id testbank-py-2-ch01-48

55. Consider the following pseudocode. What does it produce? Set a = 0 Set b = 0 Set c = 1 Set d = 1 Report the value of d Repeat until a equals 10 Set d = b + c Set b = c Set c = d Add 1 to a Report the value of d 1. 1 1 2 3 5 8 13 21 34 55 89 2. 1 1 3 5 7 9 11 13 15 17 19 21 3. 1 1 3 6 9 12 15 18 21 24 27 30 4. 1 2 3 4 5 6 7 8 9 10 11 Section 1.7 Problem Solving: Algorithm Design Title What does this algorithm produce? type mc from testbank-py-1-ch01-49 section 1.7 Problem Solving: Algorithm Design id testbank-py-2-ch01-49


1. To store a value for later use in Python, the programmer needs to create a: 1. number 2. character 3. variable 4. boolean Section 2.1 Variables Title What is the term used to store a value for later use in a Python program? type mc section 2.1 Variables id testbank-py-1-ch02-01 2. How is a value stored in a variable? 1. an assignment statement 2. an expression 3. a print statement 4. an equality statement Section 2.1 Variables Title How is a value stored in a variable? type mc section 2.1 Variables id testbank-py-1-ch02-03 3. What is the value of the variable num after the following code snippet? num = 5 num2 = 6 num = num2 + 3 1. 5 2. 9 3. 8 4. 11 Section 2.1 Variables Title What is the value of the variable num after the following code statement? type mc section 2.1 Variables id testbank-py-1-ch02-04 4. What is the right way to assign the value of num + 10 to num2? 1. num2 = num + 10 2. num = num2 + 10


4.

3. num2 + 10 = num 4. num + 10 = num2 Section 2.1 Variables Title What is the right way to assign the value of num + 10 to num2? type mc section 2.1 Variables id testbank-py-1-ch02-06

5. What is wrong with the following code snippet? 2ndNum = 78 1. The 2ndNum variable is never assigned a value 2. The 2ndNum variable is assigned a non-numeric value 3. The 2ndNum variable is not a valid variable name 4. The 2ndNum variable is never initialized Section 2.1 Variables Title What is wrong with the following code snippet? type mc section 2.1 Variables id testbank-py-1-ch02-08 6. What is a variable called that should remain unchanged throughout your program? 1. a constant variable 2. a data variable 3. a string variable 4. a boolean variable Section 2.1 Variables Title What is a variable called that should remain unchanged throughout your program? type mc section 2.1 Variables id testbank-py-1-ch02-09 7. Which of the following variables should be coded as a constant in Python? 1. character: 'a' 2. string: "hello"


7.

3. number: 1234 4. pi: 3.14159 Section 2.1 Variables Title Python naming conventions for variables type mc section 2.1 Variables id testbank-py-1-ch02-10

8. Which of the following variable names follows the Python naming convention for constants? 1. maxSize 2. MAXSIZE 3. MAX SIZE 4. max_size Section 2.1 Variables Title Python naming conventions for variables type mc section 2.1 Variables id testbank-py-1-ch02-11 9. Why is it important to follow Python naming standards for variables representing constants? 1. it is good programming style 2. it is required by the Python programming language 3. it is required by graphic programs 4. it is required for all non-zero numbers Section 2.1 Variables Title Python naming conventions for variables type mc section 2.1 Variables id testbank-py-1-ch02-12 10. Which of the following is an appropriate constant name to represent the number of pencils in a pack? 1. NUM_PENCILS_PER_PACK = 12 2. numPencilsPerPack = 12 3. NUMpencilsPERpack = 12


10.

4. numpencilsperpack = 12 Section 2.1 Variables Title Which of the following is an appropriate constant name to represent the number of pencils in a pack? type mc from testbank-py-1-ch02-14 section 2.1 Variables id testbank-py-2-ch02-14

11. A variable is: 1. A storage location with a name 2. An assignment statement 3. An expression 4. A point in a program where a decision is made Section 2.1 Variables Title What is the definition of a variable? type mc from testbank-py-1-ch02-02 section 2.1 Variables id testbank-py-2-ch02-02 12. What is wrong with this assignment statement? num + 10 = num2 1. The left hand side of an assignment statement cannot include an operator. 2. Nothing, this statement compiles and executes. 3. The value of 10 must be defined before this statement can be executed. 4. The num variable must be defined before this statement can be executed Section 2.1 Variables Title What is wrong with this assignment statement? type mc from testbank-py-1-ch02-05 section 2.1 Variables id testbank-py-2-ch02-05 13. What is wrong with the following code snippet?


13. num = 78A 1. The num variable is never assigned a value 2. 78A is not a valid value in a Python program 3. The name num is not a valid variable name 4. The num variable is never initialized Section 2.1 Variables Title What is wrong with the following code snippet? type mc from testbank-py-1-ch02-07 section 2.1 Variables id testbank-py-2-ch02-07 14. Which line of code creates a variable named x and initializes it to the integer 5? 1. x = 5.0 2. x = 5 3. x = '5' 4. x = "5" Section 2.1.2 Number Types Title Which line of code creates a variable named x and initializes it to the integer 5? type mc from testbank-py-1-ch02-15 section 2.1.2 Number Types id testbank-py-2-ch02-15 15. Which of the following items is an example of a floating-point literal? 1. 100000 2. 100,000 3. 100000.0 4. 100,000.0 Section 2.1.2 Number Types Title Which of the following items is an example of a floating-point literal? type mc section 2.1.2 Number Types id testbank-py-2-ch02-97 16. Which of the following names is not a legal variable name?


16.

1. bottle-volume 2. cans_per_pack 3. four 4. x2 Section 2.1.3 Variable Names Title Which of the following names is not a legal variable name? type mc section 2.1.3 Variable Names id testbank-py-1-ch02-16

17. Which of the following statements about variable names is not correct? 1. Variable names are case sensitive. 2. Variable names can begin with a letter, an underscore or a number. 3. Variable names cannot be reserved words such as if and class. 4. Variable names cannot contain symbols such as ? and %. Section 2.1.3 Variable Names Title Which statement about variable names is not correct? type mc section 2.1.3 Variable Names id testbank-py-2-ch02-98 18. Which of the following names is the best for a constant variable holding the price of a can of soda? 1. soda_price 2. soda-price 3. SodaPrice 4. SODA_PRICE Section 2.1.4 Constants Title Which of the following names is the best for a constant variable holding the price of a can of soda? type mc section 2.1.4 Constants id testbank-py-1-ch02-17 19. What convention is normally used when naming constants in a Python program? 1. Constant names are normally written in all capital letters. 2. Constant names normally begin with a # character. 3. Constant names normally begin and end with an underscore. 4. Constant names normally begin with a capital letter followed only by numbers. Section 2.1.4 Constants


19. Title What convention is normally used when naming constants in a Python program? type mc section 2.1.4 Constants id testbank-py-2-ch02-99 20. What symbol is used to begin a comment in a Python program? 1. ! 2. @ 3. # 4. $ Section 2.1.5 Comments Title What symbol is used to begin a comment in a python program? type mc section 2.1.5 Comments id testbank-py-1-ch02-18 21. A numeric constant that appears in your code without explanation is known as a: 1. floating-point number 2. magic number 3. string 4. variable Section 2.1.5 Comments Title What name is given to a numeric constant that appears in your code without explanation? type mc section 2.1.5 Comments id testbank-py-2-ch02-100 22. Which of the following statements correctly multiplies num1 times num2? 1. num1 * num2 2. num1 x num2 3. num1 · num2 4. num1 ** num2 Section 2.2 Arithmetic Title Which of the following statements correctly multiplies num1 times num2? type mc


22.

section 2.2 Arithmetic id testbank-py-1-ch02-19

23. What is the value of result after the following code snippet? num1 = 10 num2 = 20 num3 = 2 result = num1 / num2 / num3 print(result) 1. 1 2. 0 3. The code has an error 4. 0.25 Section 2.2 Arithmetic Title What is the value of result after the following code snippet? type mc section 2.2 Arithmetic id testbank-py-1-ch02-22 24. What will be the values of the variables num1 and num2 after the given set of assignments? num1 = 20 num2 = 10 num1 = num1 + num2 / 2 num2 = num1 1. num1 = 20.0, num2 = 10.0 2. num1 = 15.0, num2 = 10.0 3. num1 = 25.0, num2 = 25.0 4. num1 = 15.0, num2 = 15.0 Section 2.2 Arithmetic Title What will be the values of the variables num1 and num2 after the given set of assignments? type mc section 2.2 Arithmetic id testbank-py-1-ch02-23 25. What is the value of result after the following code snippet?


25. num1 = 10 num2 = 20 num3 = 2 result = num1 // num2 // num3 print(result) 1. 1 2. 0 3. The code has an error 4. 0.25 Section 2.2 Arithmetic Title What is the value of result after the following code snippet? type mc section 2.2 Arithmetic id testbank-py-1-ch02-24 26. What is the value of result after the following code snippet? num1 = 20 num2 = 10 num3 = 2 result = num1 // num2 // num3 print(result) 1. 1 2. 0 3. The code has an error 4. 0.25 Section 2.2 Arithmetic Title What is the value of result after the following code snippet? type mc section 2.2 Arithmetic id testbank-py-1-ch02-25 27. What is the value of result after the following code snippet? num1 = 20 num2 = 10 num3 = 2 result = num1 // num2 / num3 print(result) 1. 1.0 2. 0.0 3. The code has an error


27.

4. 0.25 Section 2.2 Arithmetic Title What is the value of result after the following code snippet? type mc section 2.2 Arithmetic id testbank-py-1-ch02-26

28. Which code snippet is the correct Python equivalent to the following Algebraic expression ? c = √(a2 + b2) 1. sqrt(a ^ 2 + b ^ 2) 2. sqrt(a ** 2 + b ** 2) 3. sqrt(a * 2 + b * 2) 4. squareroot(a ** 2 + b ** 2) Section 2.2 Arithmetic Title What is the value of result after the following code snippet? type mc section 2.2 Arithmetic id testbank-py-1-ch02-28 29. What symbol is used to find remainder of a floor division? 1. // 2. / 3. % 4. # Section 2.2 Arithmetic Title What symbol is used to find remainder of a floor division? type mc section 2.2 Arithmetic id testbank-py-1-ch02-29 30. A(n) _____________________ is a collection of programming instructions that carry out a particular task. 1. argument 2. parameter 3. function


30.

4. literal Section 2.2 Arithmetic Title What is a collection of programming instructions that carry out a particular task? type mc section 2.2 Arithmetic id testbank-py-1-ch02-30

31. What is the value of 4 ** 3? 1. 12 2. 64 3. 1 4. Nothing, there is an error in the statement Section 2.2 Arithmetic Title What is the value of 4 ** 3? type mc section 2.2 Arithmetic id testbank-py-1-ch02-31 32. What is returned by the function: round(x) if x = 5.64? 1. Nothing, there is an error in the statement 2. 5 3. 5.6 4. 6 Section 2.2 Arithmetic Title What is returned by the function: round(x)if x = 5.64? type mc section 2.2 Arithmetic id testbank-py-1-ch02-32 33. What is returned by the function: abs(x) if x = 5.64? 1. Nothing, there is an error in the statement 2. 5 3. 5.64


33.

4. 6 Section 2.2 Arithmetic Title What is returned by the function: abs(x)if x = 5.64? type mc section 2.2 Arithmetic id testbank-py-1-ch02-33

34. What is returned by the function: max(1, 4, 15, 2, 3, 24)? 1. 1 2. 24 3. 15 4. 2 Section 2.2 Arithmetic Title What is returned by the max function? type mc section 2.2 Arithmetic id testbank-py-1-ch02-34 35. What is returned by the function: round(3.14159, 2)? 1. 3 2. 3.14159 3. 3.2 4. 3.14 Section 2.2 Arithmetic Title What is returned by the function: round(3.14159, 2)? type mc section 2.2 Arithmetic id testbank-py-1-ch02-35 36. What must be done first before you can use a function from the standard library? 1. the function must be defined 2. the function must be imported 3. the function must be included in a module


36.

4. the function must be enclosed in parenthesis Section 2.2 Arithmetic Title What must be done first before you can use a function from the standard library? type mc section 2.2 Arithmetic id testbank-py-1-ch02-38

37. What is returned by the function: sqrt(64)? 1. 8.0 2. 32.0 3. 4.0 4. 64.0 Section 2.2 Arithmetic Title What is returned by the sqrt function? type mc section 2.2 Arithmetic id testbank-py-1-ch02-39 38. What is wrong with the following code snippet? ((num1 + num2) * num3 / 2 * (1 - num4) 1. nothing, the code compiles and runs 2. there is an extra parenthesis 3. parenthesis are not required 4. illegal expression Section 2.2 Arithmetic Title What is wrong with the following code snippet? type mc section 2.2 Arithmetic id testbank-py-1-ch02-40 39. Which of the following statements correctly calculates the average of three numbers: num1, num2, and num3? 1. num1 + num2 + num3 / 3 2. num1 + num2 + num3 % 3 3. ( num1 + num2 + num3 ) / 3


39.

4. ( num1 + num2 + num3 / 3 ) Section 2.2 Arithmetic Title Which of the following statements computes the average of three numbers? type mc from testbank-py-1-ch02-20 section 2.2 Arithmetic id testbank-py-2-ch02-20

40. Which of the following suggestions is the best way to make code easier for other programmers to understand? 1. Use more statements in the source code. 2. Give each variable a name that explains its purpose. 3. Avoid using complex calculations in the source code 4. Use single-letter variable names in the source code Section 2.2 Arithmetic Title What is the best way to make code easier for other programmers to understand? type mc from testbank-py-1-ch02-21 section 2.2 Arithmetic id testbank-py-2-ch02-21 41. Assume that you have an integer variable, pennies, that currently contains an integer number of pennies. Which statement determines the number of dollars and cents for that number of pennies? 1. dollars = pennies // 100 cents = pennies % 100 2. dollars = pennies / 100 cents = pennies % 100 3. dollars = pennies // 100 cents = pennies / 100 4. dollars = pennies % 100 cents = pennies / 100 Section 2.2 Arithmetic Title Which statement determines the number of dollars and cents for a number of pennies? type mc from testbank-py-1-ch02-27


41.

section 2.2 Arithmetic id testbank-py-2-ch02-27

42. What is wrong with the following code snippet? result = num1 // num2 / num3 num1 = 20 num2 = 10 num3 = 2 print(result) 1. A variable is used before it is assigned a value. 2. Nothing, the code compiles and runs. 3. The // symbol cannot be used in a Python program. 4. One or more of the variable names is not valid. Section 2.2 Arithmetic Title What is wrong with the following code snippets which includes variables? type mc from testbank-py-1-ch02-36 section 2.2 Arithmetic id testbank-py-2-ch02-36 43. A(n) _____________________ is a collection of code that has been written by someone else that is ready for you to use in your program. 1. variable 2. argument 3. function 4. library Section 2.2 Arithmetic Title What is a collection of code that has been written and translated by someone else. type mc from testbank-py-1-ch02-37 section 2.2 Arithmetic id testbank-py-2-ch02-37 44. Consider the following code segment: x=5


44. y = 7 z=x-y*2 After this code segment executes, the value of z is: 1. -9 2. -4 3. 5 4. 7 Section 2.2.1 Basic Arithmetic Operations Title Evaluate expressions involving basic arithmetic operations type mc section 2.2.1 Basic Arithmetic Operations id testbank-py-1-ch02-41 45. The Python code that represents the formula c = (a / b)3 is: 1. c = a / b ** 3 2. c = (a / b) ** 3 3. c = 3 ^ (a / b) 4. c = (a / b) ^ 3 Section 2.2.2 Powers Title Translate a formula to equivalent Python code type mc section 2.2.2 Powers id testbank-py-1-ch02-42 46. Consider the following code segment: x=5 y=3 z=2 result = x // y + x % z After this code segment, the value of result is: 1. 2 2. 3 3. 4 4. 5 Section 2.2.3 Floor Division and Remainder Title Evaluate an expression involving division and remainder type mc section 2.2.3 Floor Division and Remainder id


46. testbank-py-1-ch02-43 47. Which function call will cause Python to report an error? 1. abs(1, 2) 2. max(1, 2) 3. min(1, 2) 4. round(1, 2) Section 2.2.4 Calling Functions Title Which function call will cause Python to report an error? type mc section 2.2.4 Calling Functions id testbank-py-2-ch02-101 48. Which statement computes the square root of 5 and stores it in the variable, r? Assume that the math module has already been imported. 1. r = math.squareRoot(5) 2. r = math.sqrt(5) 3. r = math.squareRoot[5] 4. r = math.sqrt[5] Section 2.2.5 Mathematical Functions Title Which statement computes the square root of 5? type mc section 2.2.5 Mathematical Functions id testbank-py-1-ch02-44 49. Which of the following statements computes the minimum of the variables a, b, c and d, and stores it in x? 1. x = minimum(a, b, c, d) 2. x = min(a, b, c, min(d)) 3. x = min(min(a, b), min(c, d)) 4. min(a, b, c, d) = x Section 2.2.5 Mathematical Functions Title Which statement computes the minimum value of four type mc section 2.2.5 Mathematical Functions variables? id testbank-py-1-ch02-45


50. What is the value of length after this statement: length = len("Good Morning")? 1. 10 2. 11 3. 12 4. 13 Section 2.4 Strings Title What is the value of length after this statement: length = len("Good Morning")? type mc section 2.4 Strings id testbank-py-1-ch02-47

51. Which statement correctly creates a new variable by combining the two string variables: firstName and lastName? 1. name = "firstName" + "lastName" 2. name = firstName + lastName 3. name = first name + last name 4. name = firstName & lastName Section 2.4 Strings Title Which statement correctly creates a new variable by combining the strings firstName and lastName? type mc section 2.4 Strings id testbank-py-1-ch02-49 52. What is printed from the following code snippet: message = "ho.." print(message * 3) 1. ho..ho..ho 2. ho.. 3. ho..ho..ho.. 4. nothing is printed, this code snippet causes an error Section 2.4 Strings Title What is printed from the given snippet? type mc section 2.4 Strings


52. id testbank-py-1-ch02-50

53. What is printed by the following code snippet: street = " Main Street" address = 123 + street print(address) 1. 123Main Street 2. 123 Main Street 3. 123 "Main Street" 4. nothing is printed, this code snippet causes an error Section 2.4 Strings Title What is printed from the given snippet? type mc section 2.4 Strings id testbank-py-1-ch02-51 54. The following code snippet has an error, how can this be corrected so it prints: 123 Main Street? 1. street = " Main Street" 2. address = 123 + street 3. print(address) 1. change the value '123' in line 2 to a string using the str function 2. reverse lines 1 and 2 3. change line 1 to read: street = 123 + "Main Street" 4. change line 2 to read: address = 123 + "Main Street" Section 2.4 Strings Title What has to change to correctly print a street number and street name? type mc section 2.4 Strings id testbank-py-1-ch02-52 55. What is printed by the following code snippet? num = int("45") * float("1.5") print(num) 1. nothing, this causes an error 2. 46.5 3. 45 * 1.5


55.

4. 67.5 Section 2.4 Strings Title What is printed by the following code snippet? type mc section 2.4 Strings id testbank-py-1-ch02-54

56. What is the index value of the letter 'h' in the string below ? message = "hello" 1. 1 2. 0 3. 3 4. 4 Section 2.4 Strings Title What is the index value of the letter 'h' in the string below ? type mc section 2.4 Strings id testbank-py-1-ch02-55 57. Given the code snippet below, what code is needed to print the person's initials? firstName = "Pamela" middleName = "Rose" lastName = "Smith" 1. print(firstName[1], middleName[1], lastName[1]) 2. print(firstName[0], middleName[0], lastName[0]) 3. print(firstName + middleName + lastName) 4. print(firstName, middleName, lastName) Section 2.4 Strings Title Given the code snippet below, what code is needed to print the person's initials? type mc section 2.4 Strings id testbank-py-1-ch02-56 58. Which statement finds the last letter of the string variable name?


58.

1. last = name[len(name)] 2. last = len(name) - 1 3. last = len(name) 4. last = name[len(name) - 1] Section 2.4 Strings Title Which statement finds the last letter of the string variable name? type mc section 2.4 Strings id testbank-py-1-ch02-58

59. A ___________________________ is a collection of programming instructions that can be appllied to an object. 1. function 2. method 3. class 4. object Section 2.4 Strings Title Which is the name of a collection of programming instructions that carry out a particular task to control the behavior of an object? type mc section 2.4 Strings id testbank-py-1-ch02-59 60. A sequence of characters is referred to as a: 1. string 2. module 3. variable 4. expression Section 2.4 Strings Title What is a sequence of characters? type mc from testbank-py-1-ch02-46 section 2.4 Strings id testbank-py-2-ch02-46 61. What is it called when you join two strings together in Python?


61.

1. concatenation 2. addition 3. repetition 4. conversion Section 2.4 Strings Title What is it called when you join two strings together in Python? type mc from testbank-py-1-ch02-48 section 2.4 Strings id testbank-py-2-ch02-48

62. What functions can be used to convert a string into a number? 1. stri and len 2. int and float 3. sqrt, abs and round 4. integer and float Section 2.4 Strings Title What functions are used to convert strings to numbers? type mc from testbank-py-1-ch02-53 section 2.4 Strings id testbank-py-2-ch02-53 63. What output is generated by the following code snippet? firstName = "Pamela" middleName = "Rose" lastName = "Smith" print(firstName[0], middleName[0], lastName[5]) 1. nothing, this causes an index of bounds error 2. PRh 3. P R h 4. PRS Section 2.4 Strings Title Given the code snippet below, what code is printed? type mc


63. from testbank-py-1-ch02-57 section 2.4 Strings id testbank-py-2-ch02-57

64. What is printed by the following code snippet? name = "Robert" formalName = name.upper() print(formalName) 1. Robert 2. robert 3. ROBERT 4. formalName Section 2.4 Strings Title Which is the result of the following code snippet? type mc from testbank-py-1-ch02-60 section 2.4 Strings id testbank-py-2-ch02-60 65. What is printed by the following code snippet? name = "Robert" formalName = name.lower() print(formalName) 1. Robert 2. robert 3. ROBERT 4. formalName Section 2.4 Strings Title Which is the result of the following code snippet? type mc from testbank-py-1-ch02-61 section 2.4 Strings id testbank-py-2-ch02-61


66. What is printed by the following code snippet? name = "today is thursday" name.replace("t", "T") name.replace("i", "I") print(name) 1. today is thursday 2. Today is Thursday 3. Today Is Thursday 4. Today Is thursday Section 2.4 Strings Title Which is the result of the following code snippet? type mc from testbank-py-1-ch02-62 section 2.4 Strings id testbank-py-2-ch02-62

67. What is printed by the following code snippet?

name = "today is thursday" newName = name.replace("t", "T") print(newName) 1. today is thursday 2. Today is Thursday 3. Today Is Thursday 4. Today Is thursday Section 2.4 Strings Title Which is the result of the following code snippet? type mc from testbank-py-1-ch02-63 section 2.4 Strings id testbank-py-2-ch02-63 68. What is the value of x after the following code segment? x = len("Hello World!") 1. 10 2. 11 3. 12 4. 13


68. Section 2.4.1 The String Type Title Determine the length of a string type mc section 2.4.1 The String Type id testbank-py-1-ch02-64 69. Assume that s is an arbitrary string containing at least 2 characters. What is displayed by the following code segment? print(s[0], s[len(s) - 1]) 1. The first character of s, followed immediately by the second last character of s. 2. The first character of s, followed immediately by the last character of s. 3. The first character of s, followed by a space, followed by the second last character of s. 4. The first character of s, followed by a space, followed by the last character of s. Section 2.4.1 The String Type Title Display specific characters from a string type mc section 2.4.1 The String Type id testbank-py-1-ch02-65 70. Which of the following symbols can be used to begin a string literal in Python? 1. * 2. # 3. " 4. > Section 2.4.1 The String Type Title Which of the following symbols can be used to begin a string literal in Python? type mc section 2.4.1 The String Type id testbank-py-2-ch02-13 71. What is the value of words after the following code segment? words = "Hello" + "World" * 3 1. "HelloWorldWorldWorld" 2. "Hello World World World"


71.

3. "HelloWorldHelloWorldHelloWorld" 4. "Hello World Hello World Hello World" Section 2.4.2 Concatenation and Repetition Title String Concatenation and Repetition type mc section 2.4.2 Concatenation and Repetition id testbank-py-1-ch02-66

72. Which of the following statements causes Python to report an error? 1. x = 17 + 18.4 2. x = 17 + "18.4" 3. x = 17 + int(18.4) 4. x = 17 + float("18.4") Section 2.4.3 Converting Between Numbers and Strings Title Working with Numbers and Strings type mc section 2.4.3 Converting Between Numbers and Strings id testbank-py-1-ch02-67 73. What letter is displayed by the following code segment? title = "Python for Everyone" print(title[3]) 1. e 2. h 3. o 4. t Section 2.4.4 Strings and Characters Title Identify a character within a string type mc section 2.4.4 Strings and Characters id testbank-py-1-ch02-68 74. Consider the following code segment: product = "Cookies" product = product.lower() After this code segment executes, the value of the product variable is:


74.

1. "cookies" 2. "cOOKIES" 3. "Cookies" 4. "COOKIES" Section 2.4.5 String Methods Title Trace code that invokes the lower method on a string type mc section 2.4.5 String Methods id testbank-py-1-ch02-69

75. Consider the following code segment: title = "Python for Everyone" newTitle = title.replace("e", "*") After this code runs, the value stored in newTitle is: 1. "Python for *veryone" 2. "Python for Ev*ryone" 3. "Python for Ev*ryon*" 4. "Python for *v*ryon*" Section 2.4.5 String Methods Title Trace code that invokes the replace method on a string type mc section 2.4.5 String Methods id testbank-py-1-ch02-70 76. What is displayed by the following code segment? print("\"Hello World!\"") 1. Hello World! 2. "Hello World!" 3. \"Hello World!\" 4. The program reports an error Section 2.4.5 String Methods Title Trace code that includes escape sequences type mc section 2.4.5 String Methods id testbank-py-1-ch02-71


77. Which statement causes A and B to be printed on different lines? 1. print("AB") 2. print("A,B") 3. print("A\nB") 4. print("A", "B") Section 2.4.5 String Methods Title Which statement causes A and B to be printed on different lines? type mc section 2.4.5 String Methods id testbank-py-2-ch02-102 78. Which statement correctly saves the price in the variable cost? userInput = input("Please enter the price:") 1. cost = float(userInput) 2. cost = userInput 3. cost = int(userInput) 4. cost = float[userInput] Section 2.5 Input and Output Title Which statement correctly saves the price in the variable cost? type mc section 2.5 Input and Output id testbank-py-1-ch02-75 79. Which statement correctly saves the number of items in the variable quantity? userInput = input("Please enter the quantity:") 1. quantity = float(userInput) 2. quantity = userInput 3. quantity = int(userInput) 4. quantity = int[userInput] Section 2.5 Input and Output Title Which statement correctly saves the price in the variable quantity? type mc section 2.5 Input and Output id testbank-py-1-ch02-76


80. What is printed by the following code snippet? cost = 25.45378 print("%.2f" % cost) 1. 25.45378 2. %25.45 3. 25.45 4. nothing, there is an error Section 2.5 Input and Output Title Which is printed by the following code snippet? type mc section 2.5 Input and Output id testbank-py-1-ch02-77

81. Which output format string correctly allows for 5 positions before and two digits after the decimal point? 1. "%8.2f" 2. "%5.2f" 3. "%7.2f" 4. "%5d.2f" Section 2.5 Input and Output Title Which output format string correctly allows for 5 positions before and two digits after the decimal point? type mc section 2.5 Input and Output id testbank-py-1-ch02-78 82. Which output format correctly prints an item description left justified with up to 10 letters? 1. "%10" 2. "%10s" 3. "%-10s" 4. "-%10s" Section 2.5 Input and Output Title Which output format correctly prints an item description left justified with up to 10 letters? type mc section 2.5 Input and Output id


82.

testbank-py-1-ch02-79

83. What is the output for the following code snippet: area = 25 print("The area is %05d" % area) 1. The area is 25 2. nothing, there is an error in the code snippet 3. The area is 00025 4. The area is 25 Section 2.5 Input and Output Title What is the output for the following code snippet? type mc section 2.5 Input and Output id testbank-py-1-ch02-80 84. What function is used to read a value from the keyboard? 1. input 2. print 3. keyboard 4. next Section 2.5 Input and Output Title What function is used to read input from the keyboard? type mc from testbank-py-1-ch02-72 section 2.5 Input and Output id testbank-py-2-ch02-72 85. The message used to tell the user what input is expected is known as a(n): 1. input 2. keyword 3. comment 4. prompt Section 2.5 Input and Output Title The message used to tell the user what input is expected is known as a(n): type mc from testbank-py-1-ch02-73


85. section 2.5 Input and Output id testbank-py-2-ch02-73

86. What is the data type of the value returned by the input function? 1. integer 2. string 3. float 4. character Section 2.5 Input and Output Title What is the data type of the value returned by the input function? type mc from testbank-py-1-ch02-74 section 2.5 Input and Output id testbank-py-2-ch02-74 87. Consider the following code segment: a = input("Enter the value of a: ") b = input("Enter the value of b: ") print(a + b) When this code segment is run the user enters 1 at the first prompt and 5 at the second prompt. The output displayed is: 1. 1 2. 6 3. 15 4. 1 + 5 Section 2.5.1 User Input Title Trace code that reads two values from the user type mc section 2.5.1 User Input id testbank-py-1-ch02-81 88. The line of code which reads a value from the user and stores it in a variable named x as a floating-point value is: 1. x = float() 2. x = input("Enter the value of x: ") 3. x = float(input("Enter the value of x: ")) 4. x = input(float())


88.

Section 2.5.2 Numerical Input Title Read numerical input from the user type mc section 2.5.2 Numerical Input id testbank-py-1-ch02-82

89. The line of code that displays the floating point number stored in the variable x using 3 decimal places is: 1. print("%.3f", x) 2. print("%.3f" % x) 3. print("%3.f", x) 4. print("%3.f" % x) Section 2.5.3 Formatted Output Title Format output to 3 decimal places type mc section 2.5.3 Formatted Output id testbank-py-1-ch02-83 90. What output is generated by the following code segment? a = 10.0 b = 0.50 print("The total is %.2f and the tax is %.2f." % (a, b)) 1. The total is .00 and the tax is .50 2. The total is 10.0 and the tax is 0.5 3. The total is 10.0 and the tax is 0.50 4. The total is 10.00 and the tax is 0.50 Section 2.5.3 Formatted Output Title Format multiple values in a single output statement type mc section 2.5.3 Formatted Output id testbank-py-1-ch02-84 91. Consider the following code segment: x = 12 print("%d%%" % x) The output generated by this code segment is: 1. 12


91.

2. %12 3. 12% 4. 12%% Section 2.5.3 Formatted Output Title Format integer output type mc section 2.5.3 Formatted Output id testbank-py-1-ch02-85

92. A graphics application shows information inside a ____________________ 1. panel 2. window 3. form 4. page Section 2.6 Graphics: Simple Drawings Title A graphics application shows information inside a ____________________ type mc section 2.6 Graphics: Simple Drawings id testbank-py-1-ch02-86 93. Which statement draws a square on the canvas? 1. canvas.drawRect(0, 50, 0, 50) 2. canvas.drawRect(50, 50, 0, 0) 3. canvas.drawRect(0, 0, 50, 100) 4. canvas.drawRect(0, 0, 50, 50) Section 2.6 Graphics: Simple Drawings Title Which statement draws a square on the canvas? type mc section 2.6 Graphics: Simple Drawings id testbank-py-1-ch02-87 94. Which statement sets the fill color when drawing shapes on the canvas? 1. canvas.setOutline("black") 2. canvas.setFill("black") 3. canvas.fill("black") 4. canvas.fillRect("black") Section 2.6 Graphics: Simple Drawings Title


94. Which statement fills a shape? type mc section 2.6 Graphics: Simple Drawings id testbank-py-1-ch02-88 95. Which statement writes the word Hello on the canvas? 1. canvas.setString(10, 10, "Hello") 2. canvas.setText(10, 10, "Hello") 3. canvas.drawText(10, 10, "Hello") 4. canvas.drawString(10, 10, "Hello") Section 2.6 Graphics: Simple Drawings Title Which statement writes test to the canvas? type mc section 2.6 Graphics: Simple Drawings id testbank-py-1-ch02-89 96. Which of the given print statements generates the following output? ABCDE"\ 1. print("ABCDE\"\\") 2. print("ABCDE"\") 3. print("ABCDE"\) 4. print("ABCDE\"\") Section 2.6 Graphics: Simple Drawings Title Which print statement generates output with quote and backslash? type mc section 2.6 Graphics: Simple Drawings id testbank-py-1-ch02-90 97. Which statement imports the entire contents of the sympy module? 1. from sympy import * 2. import contents 3. import * from sympy 4. sympy import Section 2.6 Graphics: Simple Drawings Title Which statement imports the entire contents of the sympy module? type mc


97.

section 2.6 Graphics: Simple Drawings id testbank-py-2-ch02-94

98. Which statement creates an expression in SymPy form? 1. f = x ** 2 2. f = sympify("x ** 2") 3. f = sympy(x ** 2) 4. sympy("f = x ** 2") Section 2.6 Graphics: Simple Drawings Title Which statement creates an expression in SymPy form? type mc section 2.6 Graphics: Simple Drawings id testbank-py-2-ch02-95 99. Which SymPy function is used to display a graph of a mathematical function? 1. diff 2. draw 3. plot 4. subs Section 2.6 Graphics: Simple Drawings Title Which SymPy function is used to display a graph of a mathematical function? type mc section 2.6 Graphics: Simple Drawings id testbank-py-2-ch02-96 100. Consider the following code segment: from graphics import GraphicsWindow win = GraphicsWindow(400, 200) canvas = win.canvas() The line of code that should be added to the end of the code segment above to draw a diagonal line connecting the upper left corner to the lower right corner is: 1. canvas.drawLine(0, 0, 0, 0) 2. canvas.drawLine(0, 0, 200, 400) 3. canvas.drawLine(200, 400, 400, 200) 4. canvas.drawLine(400, 200, 0, 0) Section 2.6.2 Lines and Polygons Title


100. Draw a diagonal line on a canvas type mc section 2.6.2 Lines and Polygons id testbank-py-1-ch02-91 101. The statement that sets the fill color to red is: 1. canvas.setFill(0, 128, 0) 2. canvas.setFill(64, 0, 128) 3. canvas.setFill(64, 255, 64) 4. canvas.setFill(128, 0, 0) Section 2.6.3 Filled Shapes and Color Title Which statement sets the fill color to red? type mc section 2.6.3 Filled Shapes and Color id testbank-py-1-ch02-92 102. Which of the following statements draws a circle? 1. canvas.drawOval(100, 200, 100, 200) 2. canvas.drawOval(200, 100, 200, 200) 3. canvas.drawOval(200, 200, 100, 200) 4. canvas.drawOval(200, 200, 200, 100) Section 2.6.4 Ovals, Circles and Text Title Which statement draws a circle? type mc section 2.6.4 Ovals, Circles, and Text id testbank-py-1-ch02-93


1. What statement is used to implement a decision? 1. while 2. if 3. for 4. import Section 3.1 The if statement Title What is a decision statement? type mc section 3.1 The if Statement id testbank-py-1-ch03-01 2. What are the two parts of an if statement? 1. A condition and a body 2. A check and an increment 3. An increment and a body 4. An increment and a return value Section 3.1 The if statement Title What are the two parts of an if statement? type mc section 3.1 The if Statement id testbank-py-1-ch03-02 3. Which of the following statements is true about the if statement? 1. The if statement can have only one condition that evaluates to an integer value. 2. The if block is optional. 3. The else block is optional. 4. The if and else blocks can be aligned to any indentation level. Section 3.1 The if statement Title Which statement is true about the if statement type mc section 3.1 The if Statement id testbank-py-1-ch03-03 4. Which of the following is the correct syntax for an if statement? 1. if (x < 10) size = "small"; 2. if (x < 10)


4.

2. size = "small" else (x < 20) size = "medium" 3. if x < 10 : size = "small" else : size = "medium" 4. if x < 10 : size = "small" else size = "medium" Section 3.1 The if statement Title What is the correct syntax for an if statement? type mc section 3.1 The if Statement id testbank-py-1-ch03-04

5. Which of the following correctly identifies what is wrong with the code snippet below:

if y > 300 : x=y else : x=0 print("x:", x) 1. Nothing, the program runs as intended 2. The statement after the if statement must be indented 3. The statement after the if statement and the statement after the else statement must be indented 4. No colon is needed after the else statement Section 3.1 The if statement Title What is the correct syntax for an if statement? type mc section 3.1 The if Statement id testbank-py-1-ch03-05 6. Assuming that the user provides 303 as input, what is the output of the following code snippet? y = int(input("Please enter a number: ")) if y > 300 :


6.

x=y else : x=0 print("x:", x) 1. x: 0 2. x: 303 3. x: 300 4. There is no output due to a syntax error. Section 3.1 The if statement Title What is the output of an if/else statement given sample input value type mc section 3.1 The if Statement id testbank-py-1-ch03-06

7. What is the output of the following code snippet if the cost contains 100: if cost > 150 : discount = 0.8 * cost else : discount = cost print("Your cost is:", discount) 1. Nothing, the code contains a syntax error 2. Your cost is: 0 3. Your cost is: 80 4. Your cost is: 100 Section 3.1 The ifstatement Title What is the output of a conditional expression? type mc section 3.1 The if Statement id testbank-py-1-ch03-10 8. Consider the following code segment: if count > 0 : x=x+1 print(x) If count is initialized to -1 and x is initialized to 4 then the value displayed by this code segment is: 1. -1 2. 0 3. 4


8.

4. 5 Section 3.1 The if Statement Title Trace an if statement type mc section 3.1 The if Statement id testbank-py-1-ch03-11

9. Consider the following code segment: numPizzas = 1 numPeople = 4 if numPeople == 5 : numPizzas = 2 After this code segment executes, what value is in the variable numPizzas? 1. 1 2. 2 3. 4 4. 5 Section 3.1 The if Statement Title Trace an if statement type mc section 3.1 The if Statement id testbank-py-1-ch03-12 10. Consider the following code segment: c=2 b=1 if b == 0 : c=c+1 else : c=c-1 print(c) What value is printed by this code segment? 1. 1 2. 2 3. 3 4. 4


10. Section 3.1 The if Statement Title Trace an if/else statement type mc section 3.1 The if Statement id testbank-py-1-ch03-13 11. Which statement about if statements is not correct? 1. A compound statement requires a colon at the end of the header. 2. All statements in a statement block must be indented to the same indentation level. 3. Comments can be indented to any level. 4. The statements in a statement block must be indented 2 spaces more than the header. Section 3.1 The if Statement Title Which statement about if statements is not correct? type mc section 3.1 The if Statement id testbank-py-2-ch03-117 12. The following code snippet contains an error. What is the error? cost = int(input("Enter the cost: ")) if cost > 100 cost = cost - 10 print("Discounted cost:", cost) 1. Syntax error: missing colon after if statement 2. Logical error: use of an uninitialized variable 3. Syntax error: missing an else statement 4. Syntax error: incorrect indentation Section 3.1 The if statement Title Find the error in a code snippet containing an if statement type mc from testbank-py-1-ch03-07 section 3.1 The if Statement id testbank-py-2-ch03-07 13. Assuming that the user provides 95 as input, what is the output of the following code snippet? y = int(input("Please enter a number: ")) if y > 300 :


13.

x=y else : x=0 print("x:", x) 1. x: 0 2. x: 95 3. x: 300 4. There is no output due to a syntax error Section 3.1 The if statement Title What is the output of an if/else statement for a given input value? type mc from testbank-py-1-ch03-08 section 3.1 The if Statement id testbank-py-2-ch03-08

14. What is printed by the following code snippet if itemCount contains a value of 10 and cost contains 80: if itemCount > 5 : discount = 0.8 totalCost = cost * discount print("Total discounted price is:", totalCost) 1. Nothing, the program will run but not print any results 2. Total discounted price is: 64.0 3. Total discounted price is: 0.0 4. Total discounted price is: 16.0 Section 3.1 The if statement Title What is the output of a compound statement? type mc from testbank-py-1-ch03-09 section 3.1 The if Statement id testbank-py-2-ch03-09 15. What is the error in this statement? if count = max : print("You win") 1. Equality is evaluated using two equal signs (==), not one. 2. The print function should not be indented 3. There must be an else statement 4. Nothing, if count equals max, it would print "You win"


15. Section 3.2 Relational Operators Title What is the error in this statement? type mc section 3.2 Relational Operators id testbank-py-1-ch03-14 16. What is the opposite of this condition: count > 10? 1. count >= 10 2. count < 9 3. count <= 10 4. count <= 9 Section 3.2 Relational Operators Title What is the opposite of a conditional statement? type mc section 3.2 Relational Operators id testbank-py-1-ch03-15 17. What is the output of the following code snippet if count contains 56? if count % 2 == 0 : print("Count is an even number") else : print("Count is an odd number") 1. Count is an even number 2. Count is an odd number 3. Nothing, there is a syntax error 4. Nothing, the program runs but does not print any output Section 3.2 Relational Operators Title What is the output of a code snippet with relational operators? type mc section 3.2 Relational Operators id testbank-py-1-ch03-16 18. What is the output of the following code snippet if count contains 56? if count % 2 == 0 : print("Count is an even number")


18. else : print("Count is an odd number") 1. Count is an even number 2. Count is an odd number 3. Nothing, there is a syntax error 4. Nothing, the program runs but does not print any output Section 3.2 Relational Operators Title What is the output of a code snippet with relational operators? type mc section 3.2 Relational Operators id testbank-py-1-ch03-17 19. What type of operator is <= operator? 1. Lexicographic 2. Arithmetic 3. Inequality 4. Relational Section 3.2 Relational Operators Title What type of operator is !< operator? type mc section 3.2 Relational Operators id testbank-py-1-ch03-18 20. The operator >= stands for 1. greater than 2. greater than or equal to 3. not equal to 4. this is not a valid Python operator Section 3.2 Relational Operators Title Which relational operator is this? type mc section 3.2 Relational Operators id testbank-py-1-ch03-19 21. Which statement correctly tests if the user entered the letter Y? 1. if userInput = "y" : 2. if userInput = "Y" : 3. if userInput == "Y" : 4. if userInput == "y" :


21.

Section 3.2 Relational Operators Title Which statement correctly tests for a user input value? type mc section 3.2 Relational Operators id testbank-py-1-ch03-20

22. Assuming the user enters 15 as input, what is the output of the following code snippet? number = int(input("Please enter a number: ")) if number >= 20 : print("The numer is big") else : print("The number is small") 1. There is no output due to a syntax error 2. The number is big 3. The number is small 4. The program runs successfully but does not print any output Section 3.2 Relational Operators Title What is the output of a given code snippet and given input value? type mc section 3.2 Relational Operators id testbank-py-1-ch03-21 23. What is the output of the following code snippet if the input is 34? number = int(input("Please enter a number: ")) if number != 20 : number = number + 1 else : number = number - 1 print(number) 1. 34 2. 33 3. 35 4. 36 Section 3.2 Relational Operators Title What is the output of a given code snippet and given input value? type mc section


23. 3.2 Relational Operators id testbank-py-1-ch03-22 24. Assuming that the user enters a value of 45, what is the output of the following code snippet? number = int(input("Please enter a number: ")) if number < 100 : number = number + 5 if number < 500 : number = number - 2 if number > 15 : number = number + 1 else : nmber = number - 1 print(number) 1. 105 2. 45 3. 43 4. 49 Section 3.2 Relational Operators Title What is the output of a code statement containing multiple if statements and a given input value? type mc section 3.2 Relational Operators id testbank-py-1-ch03-23 25. In Python, which of the following orderings is used to compare strings? 1. Semantic 2. Alphabetic 3. Syntatic 4. Lexicographic Section 3.2 Relational Operators Title Which ordering is used to compare strings? type mc section 3.2 Relational Operators id testbank-py-1-ch03-26 26. Which of the following if statements is problematic because of the limited precision of floating-point numbers? 1. if 4 // 3 == 1 : 2. if sqrt(2) * sqrt(2) == 2.0 : 3. if "10" == 5 : 4. if 4 <= 4 :


26. Section 3.2 Relational Operators Title If statements and the limited precision of floating-point numbers type mc section 3.2 Relational Operators id testbank-py-1-ch03-28 27. Consider the following code segment: s1 = "CAT" s2 = "cat" Which of the following if statements has a condition that evaluates to True? 1. if s1 == s2 : 2. if s1 = s2 : 3. if s1 < s2 : 4. if s1 >= s2 : Section 3.2 Relational Operators Title Comparing strings with relational operators type mc section 3.2 Relational Operators id testbank-py-1-ch03-29 28. Given the following list of strings, what is the correct order using lexicographic ordering: "Ann", "amy", "Heather", "hanna", "joe", "john", "Leo", "Jim" ? 1. amy, Ann, hanna, Heather, Jim, joe, john, Leo 2. Ann, Heather, Jim, Leo, amy, hanna, joe, john 3. amy, hanna, joe, john, Ann, Heather, Jim, Leo 4. Leo, john, joe, Jim, Heather, hanna, Ann, amy Section 3.2 Special Topic: Lexicographic Ordering of Strings Title Given a list of strings, what is the correct order using lexicographic ordering? type mc section 3.2 Relational Operators id testbank-py-1-ch03-31 29. Which of the following is not an example of a relational operator? 1. = 2. < 3. <=


29.

4. != Section 3.2 Relational Operators Title Which of the following is not an example of a relational operator? type mc section 3.2 Relational Operators id testbank-py-2-ch03-118

30. Which expression is equivalent to the expression shown below? floor - 1 < 13 1. 13 < floor - 1 2. 13 >= floor - 1 3. floor < 12 4. floor - 1 <= 12 Section 3.2 Relational Operators Title Which is expression is equivalent to the expression shown below? type mc section 3.2 Relational Operators id testbank-py-2-ch03-119 31. A store provides a 10% discount on items with a price of at least $100. Otherwise, no discount is applicable. Which of the following DOES NOT correctly compute the discount amount when the item's price is stored in the price variable? 1. discount = 0 if price >= 100 : discount = 0.10 * price 2. discount = 0.10 * price if price <= 100 : discount = 0 3. discount = 0 if price >= 100 : discount = price / 10 4. discount = 10 if price >= 100 : discount = 0.1 * price else : discount = 0 Section


31. 3.2 Relational Operators Title Which statement DOES NOT correctly compute the discount? type mc from testbank-py-1-ch03-24 section 3.2 Relational Operators id testbank-py-2-ch03-24 32. Which of the following conditions is true, given that num1 contains 3 and num2 contains 4? 1. num1 + 1 < num2 2. num1 + 1 > num2 3. num1 + num2 != 7 4. num1 - num2 <= 0 Section 3.2 Relational Operators Title Which of the following conditions evaluates to True given two variables? type mc from testbank-py-1-ch03-25 section 3.2 Relational Operators id testbank-py-2-ch03-25 33. Which condition will cause the statement block of the if statement to execute only when count is 0? 1. if count = 0 : 2. if count < 0 : 3. if count =< 0 : 4. if count == 0 : Section 3.2 Relational Operators Title Which condition will cause the statement block of the if statement to execute? type mc from testbank-py-1-ch03-27 section 3.2 Relational Operators id testbank-py-2-ch03-27 34. Which statement evaluates to True when comparing the two strings: name1 = "Heather" name2 = "hanna" 1. name1 == name2


34.

2. name1 > name2 3. name1 < name2 4. Relational operators cannot be used to compare strings Section 3.2 Title Which statement evaluates to true when comparing two strings? type mc from testbank-py-1-ch03-30 section 3.2 Relational Operators id testbank-py-2-ch03-30

35. Assuming a user enters 30, 20, and 10 as the input values, what is the output of the following code snippet? num1 = int(input("Enter a number: ")) num2 = int(input("Enter a number: ")) num3 = int(input("Enter a number: ")) if num1 > num2 : if num1 > num3 : print(num1) else : print(num3) else : if num2 > num3 : print(num2) else : print(num3) 1. 0 2. 10 3. 20 4. 30 Section 3.3 Nested Branches Title What is the output of the nested if code snippet given three input values? type mc section 3.3 Nested Branches id testbank-py-1-ch03-33 36. What is the output of the following code snippet? num1 = 100 if num1 < 100 : if num1 < 50 : num1 = num1 - 5 else :


36.

num1 = num1 - 10 else : if num1 > 150 : num1 = num1 + 5 else : num1 = num1 + 10 print(num1) 1. 95 2. 100 3. 105 4. 110 Section 3.3 Nested Branches Title What is the output of an if/else code snippet? type mc section 3.3 Nested Branches id testbank-py-1-ch03-35

37. Which of the following options refers to the technique of simulating program execution on a sheet of paper? 1. Compiling 2. Prototyping 3. Debugging 4. Tracing Section 3.3 Nested Branches Title Which refers to the technique of simulating program execution on a sheet of paper? type mc section 3.3 Nested Branches id testbank-py-1-ch03-36 38. Which of the following code segments is an example of a nested if statement? 1. if a == b : print(a) 2. if a == b : print(a) else : print(b) 3. if a == b : print(a) if c == d : print(c) 4. a = a - 1 if a > 0 else a = a + 1


38.

Section 3.3 Nested Branches Title Which of the following is an example of a nested if statement? type mc section 3.3 Nested Branches id testbank-py-1-ch03-38

39. Consider the following code segment: if a > b : print("X") if a == b : print("Y") What is displayed if a is 1 and b is 0? 1. X 2. Y 3. X followed by Y on the next line 4. Nothing Section 3.3 Nested Branches Title Trace a nested if statement type mc section 3.3 Nested Branches id testbank-py-1-ch03-39 40. Consider the following code segment: if a > b : print("X") if a == b : print("Y") What is displayed if a is 0 and b is 0? 1. X 2. Y 3. X followed by Y on the next line 4. Nothing Section 3.3 Nested Branches Title Trace a nested if statement type mc section 3.3 Nested Branches


40. id testbank-py-1-ch03-40 41. Consider the following code segment: if a > b : print("X") if a == b : print("Y") What is displayed if a is 1 and b is 2? 1. X 2. Y 3. X followed by Y on the next line 4. Nothing Section 3.3 Nested Branches Title Trace a nested if statement type mc section 3.3 Nested Branches id testbank-py-1-ch03-41 42. Consider the following code segment: if a == b : print("W") else : print("X") if b == c : print("Y") else : print("Z") If a, b and c are all 0 then the output generated by this code segment is: 1. W 2. W followed by Y on the next line 3. X followed by Y on the next line 4. W followed by X on the next line, followed by Y on the next line Section 3.3 Nested Branches Title Trace nested if/else statements type mc section 3.3 Nested Branches id testbank-py-1-ch03-42


43. Consider the following code segment: if a == b : print("W") else : print("X") if b == c : print("Y") else : print("Z") If a is 0, b is 1 and c is 0 then the output generated by this code segment is: 1. W 2. X 3. X followed by Y on the next line 4. X followed by Z on the next line Section 3.3 Nested Branches Title Trace nested if/else statements type mc section 3.3 Nested Branches id testbank-py-1-ch03-43 44. Consider the following code segment: if a == b : print("W") else : print("X") if b == c : print("Y") else : print("Z") If a is 0, b is 1 and c is 1 then the output generated by this code segment is: 1. W 2. X 3. X followed by Y on the next line 4. X followed by Z on the next line Section 3.3 Nested Branches Title Trace nested if/else statements type mc section


44. 3.3 Nested Branches id testbank-py-1-ch03-44 45. What error will Python display when it attempts to execute the following if/else statement? if a == b : print("Equal") else : print("Not Equal") if a > b : print("a is larger") else : print("b is larger") 1. Python will display an error indicating that == should be replaced with = 2. Python will display an error indicating that an if statement cannot reside inside the body of an else 3. Python will display an error indicating that there is a problem with the indentation 4. No error will be displayed Section 3.3 Nested Branches Title Find the error in an if statement type mc section 3.3 Nested Branches id testbank-py-1-ch03-45 46. What error will Python display when it attempts to execute the following if/else statement? if a = b : print("Equal") else : print("Not Equal") if a > b : print("a is larger") else : print("b is larger") 1. Python will display an error indicating that = is invalid sytax 2. Python will display an error indicating that an if statement cannot reside inside the body of an else 3. Python will display an error indicating that there is a problem with the indentation 4. No error will be displayed Section 3.3 Nested Branches Title Find the error in an if statement type mc section 3.3 Nested Branches id


46. testbank-py-1-ch03-46 47. What is the definition of a nested statement? 1. A decision statement that is contained inside the statement block of another decision statement 2. A compound statement that consists of a header and a statement block 3. A decision statement that immediately follows another decision statement at the same indentation level 4. A statement that is used to validate user input Section 3.3 Nested Branches Title What is the definition of a nested statement? type mc from testbank-py-1-ch03-32 section 3.3 Nested Branches id testbank-py-2-ch03-32 48. Assuming that a user enters 25 for the price of an item, which of the following hand-trace tables is valid for the given code snippet? price = 0 status = "" price = float(input("Enter the price for your item: ")) if price >= 50 : status = "reasonable" if price >= 75 : status = "costly" else : status = "inexpensive" if price <= 25 : status = "cheap" 1. price status 0 "inexpensive" 25 "cheap" 2. price status 0 "inexpensive" 25 "reasonable" 3. price status 0 "inexpensive" 25 "reasonable" "costly" 4. price status 0 "inexpensive" 25 "costly" Section 3.3 Nested Branches Title


48. Which hand-trace table is valid for this snippet? type mc from testbank-py-1-ch03-37 section 3.3 Nested Branches id testbank-py-2-ch03-37 49. What is the output of the following code snippet when the user enters 75 as the grade? grade = int(input("Enter student grade: ")) if grade >= 90 : letterGrade = "A" if grade >= 80 : letterGrade = "B" if grade >= 70 : letterGrade = "C" if grade >= 60 : letterGrade = "D" else : letterGrade = "E" print(letterGrade) 1. A 2. B 3. C 4. D Section 3.4 Multiple Alternatives Title What is the output of an if statement with multiple alternatives? type mc section 3.4 Multiple Alternatives id testbank-py-1-ch03-47 50. What is the wrong with the following code snippet? grade = int(input("Enter student grade: ")) if grade >= 90 : letterGrade = "A" if grade >= 80 : letterGrade = "B" if grade >= 70 : letterGrade = "C" if grade >= 60 : letterGrade = "D" else : letterGrade = "E"


50. print(letterGrade) 1. Everyone will get an "E" 2. Anyone with a grade higher than 60 will receive a "D" 3. Nothing is wrong, students will get the correct grade 4. The code block will not compile Section 3.4 Multiple Alternatives Title What is the wrong with the code snippet that has multiple alternatives? type mc section 3.4 Multiple Alternatives id testbank-py-1-ch03-48 51. What is the output of the following code snippet? x = 20 if x <= 20 : print("1", end="") if x <=40 : print("2", end="") if x <= 30 : print("3", end="") 1. 1 2. 2 3. 3 4. 123 Section 3.4 Multiple Alternatives Title What is the output of the following code snippet? type mc section 3.4 Multiple Alternatives id testbank-py-1-ch03-50 52. Consider the following code snippet: number = int(input("Enter a number: ")) if number > 30 : ... elif number > 20 : ... elif number > 10 : ... else : ... Assuming that the user input is 40, which block of statements is executed? 1. if number > 30 : ... 2. else if number > 20 : ...


52.

3. else if number > 10 : ... 4. else : ... Section 3.4 Multiple Alternatives Title Which statement is executed when the user enters 40 for the input value? type mc section 3.4 Multiple Alternatives id testbank-py-1-ch03-51

53. Consider the following code snippet: number = int(input("Enter a number: ")) if number < 10 : print("Too small") elif number < 50 : print("Intermediate") elif number < 100 : print("High") else : print("Too high") Assuming that the user input is 60, what is the output of the this code snippet? 1. Too high 2. High 3. Intermediate 4. Too small Section 3.4 Multiple Alternatives Title What is output of the if/elif/else snippet with this input? type mc section 3.4 Multiple Alternatives id testbank-py-1-ch03-52 54. Consider the following code snippet. num1 = 0 num2 = 0 num3 = 0 num4 = 0 num5 = 0 num1 = int(input("Enter a number: ")) num2 = int(input("Enter a number: ")) if num1 < num2 : num3 = num1 else :


54.

num3 = num2 if num1 < num2 + 10 : num4 = num1 elif num1 < num2 + 20 : num5 = num1 print("num1 =", num1, "num2 =", num2, "num3 =", num3, "num4 =", num4, "num5 =", num5) Assuming that the user enters the numbers 20 and 12 as the two input values, what is the output of the code snippet? 1. num1 = 20 num2 = 12 num3 = 20 num4 = 0 num5 = 20 2. num1 = 20 num2 = 12 num3 = 12 num4 = 20 num5 = 0 3. num1 = 20 num2 = 12 num3 = 12 num4 = 0 num5 = 20 4. num1 = 20 num2 = 12 num3 = 20 num4 = 20 num5 = 0 Section 3.4 Multiple Alternatives Title What is output of the if/else and if/elif snippet with two input values? type mc section 3.4 Multiple Alternatives id testbank-py-1-ch03-53

55. What is the value of the price variable after the following code snippet is executed? price = 42 if price < 40 : price = price + 10 if price > 30 : price = price * 2 if price < 100 : price = price - 20 1. 42 2. 52 3. 84 4. 64 Section 3.4 Multiple Alternatives Title What is value of a variable after (if/if/if) snippet is executed? type mc section 3.4 Multiple Alternatives id testbank-py-1-ch03-54 56. Consider the following code snippet: age = int(input("Enter your age: "))


56. if age < 10 : print("Child") if age < 30 : print("Young Adult") if age < 70 : print("Old") if age < 100 : print("Impressively old") Assuming that the user inputs 80 as the age, what is the output? 1. Child Young adult Old 2. Young adult Old 3. Impressively old 4. Child Young adult Old Impressive old Section 3.4 Multiple Alternatives Title What is output of the code snippet with this input? type mc section 3.4 Multiple Alternatives id testbank-py-1-ch03-55 57. Consider the follow code segment. It is supposed to convert numeric marks to letter grades. However, it may contain a bug. Examine the program, and identify what bug, if any, is present. grade = "F" if mark >= 80 : grade = "A" if mark >= 70 : grade = "B" if mark >= 60 : grade = "C" if mark >= 50 : grade = "D" 1. The greater than or equal signs need to be replaced with equal signs 2. All instances of if, except the first, need to be replaced with elif 3. All instances of if, except the first, need to be replaced with else 4. There is nothing wrong with the code segment (it works as intended) Section


57. 3.4 Multiple Alternatives Title What is wrong with this multiple alternatives statement? type mc section 3.4 Multiple Alternatives id testbank-py-1-ch03-58 58. Consider the follow code segment. It is designed to classify widgets as too small if they are less than 10mm in diameter or too large if they are 15mm in diameter or more. Otherwise they should be classified as just right. However, this code may contain a bug. Examine the program, and identify what bug, if any, is present. if size >= 0 : print("Too small") elif size >= 10 : print("Just right") elif size >= 15 : print("Too big") 1. The greater than or equal signs need to be replaced with greater than signs 2. All instances of elif need to be replaced with else 3. The order of the conditions (and bodies) must be changed 4. There is nothing wrong with the code segment (it works as intended) Section 3.4 Multiple Alternatives Title What is wrong with this multiple alternatives statement? type mc section 3.4 Multiple Alternatives id testbank-py-1-ch03-59 59. Consider the following code segment. It is designed to convert letter grades to grade points. Examine the program, and identify what bug, if any, is present. if letter == "A" : gradePoints = 4.0 elif letter == "B" : gradePoints = 3.0 elif letter == "C" : gradePoints = 2.0 elif letter == "D" : gradePoints = 1.0 else : gradePoints = 0.0 1. The double equal signs need to be replaced with greater than or equal signs 2. All instances of elif need to be replaced with else 3. The order of the conditions (and bodies) must be changed 4. There is nothing wrong with the code segment (it works as intended)


59. Section 3.4 Multiple Alternatives Title What is wrong with this multiple alternatives statement? type mc section 3.4 Multiple Alternatives id testbank-py-1-ch03-60 60. Assume that the following import statements appear at the beginning of your program: from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.application import MIMEApplication Which statement creates a new email message that can contain both text and images? 1. msg = MIMEApplication() 2. msg = MIMEImage() 3. msg = MIMEMultipart() 4. msg = MIMEText() Section 3.4 Multiple Alternatives Title Which statement creates a new email message that can contain both text and images? type mc section 3.4 Multiple Alternatives id testbank-py-2-ch03-113 61. Which part of an email message includes information about the sender and the recipient? 1. The application 2. The attachment 3. The footer 4. The header Section 3.4 Multiple Alternatives Title Which part of an email message includes information about the sender and the recipient? type mc section 3.4 Multiple Alternatives id testbank-py-2-ch03-114 62. What type of object needs to be created to attach a PDF file to an email message? 1. MIMEApplication 2. MIMEDocument 3. MIMEImage


62.

4. MIMEPDF Section 3.4 Multiple Alternatives Title What type of object needs to be created to attach a PDF file to an email message? type mc section 3.4 Multiple Alternatives id testbank-py-2-ch03-115

63. What library needs to be imported to send a message after it has been created? 1. email 2. login 3. mimelib 4. smtplib Section 3.4 Multiple Alternatives Title What library needs to be imported to send a message after it has been created? type mc section 3.4 Multiple Alternatives id testbank-py-2-ch03-116 64. Which type of statement should be used to choose exactly one of several alternatives? 1. if 2. if-elif 3. if-else 4. if-elif-else Section 3.4 Multiple Alternatives Title Which type of statement should be used to choose exactly one of several alternatives? type mc section 3.4 Multiple Alternatives id testbank-py-2-ch03-120 65. Given that the following code is incorrect, what code would fix the following code snippet? grade = int(input("Enter student grade: ")) if grade >= 90 : letterGrade = "A" if grade >= 80 : letterGrade = "B" if grade >= 70 : letterGrade = "C" if grade >= 60 :


65.

letterGrade = "D" else : letterGrade = "E" print(letterGrade) 1. Change the if statements to elif statements (except the first one) 2. Change the if statements to else statements (except the first one) 3. Reverse the order of the if statements 4. Change the last statement to if instead of else Section 3.4 Multiple Alternatives Title How can you correct a code snippet that has multiple alternatives? type mc from testbank-py-1-ch03-49 section 3.4 Multiple Alternatives id testbank-py-2-ch03-49

66. Consider the following code snippet: age = int(input("Enter your age:")) if age < 10 : print("Child", end="") if age < 30 : print("Young Adult", end="") if age < 70 : print("Old", end="") if age < 100 : print("Impressively old", end="") Assuming that the user inputs 30 as the age, what is the output? 1. ChildYoung adultOldImpressively old 2. Young adultOldImpressively old 3. OldImpressively old 4. Impressively old Section 3.4 Multiple Alternatives Title What is output of the code snippet with this input? type mc section 3.4 Multiple Alternatives id testbank-py-1-ch03-56 67. Consider the following code snippet: age = int(input("Enter your age: ")) if age < 10 : print("Child", end="")


67. if age < 30 : print("Young Adult", end="") if age < 70 : print("Old", end="") if age < 100 : print("Impressively old", end="") Assuming that the user inputs 5 as the age, what is the output? 1. Child 2. ChildYoung Adult 3. ChildYoung AdultOld 4. ChildYoung adultOldImpressively old Section 3.4 Multiple Alternatives Title What is output of the code snippet with this input? type mc from testbank-py-1-ch03-57 section 3.4 Multiple Alternatives id testbank-py-2-ch03-57 68. Flowcharts are made up of all the following elements, EXCEPT: 1. elements for tasks 2. elements for input/output 3. elements for pseudocode 4. elements for decisions Section 3.5 Problem Solving: Flowcharts Title What are the parts of a flowchart? type mc section 3.5 Problem Solving: Flowcharts id testbank-py-1-ch03-61 69. The flowchart shows the order in which steps should be executed, and the diamond-shaped boxes indicate: 1. input 2. algorithms 3. tasks 4. decision statements Section 3.5 Problem Solving: Flowcharts Title What are the parts of a flowchart? type mc section 3.5 Problem Solving: Flowcharts id testbank-py-1-ch03-62


70. A messy network of possible pathways through a program is referred to as: 1. knotted logic 2. spaghetti code 3. twisted conditions 4. zigzag functions Section 3.5 Problem Solving: Flowcharts Title A messy network of possible pathways through a program is referred to as: type mc section 3.5 Problem Solving: Flowcharts id testbank-py-2-ch03-121 71. When testing code for correctness, it always makes sense to 1. Aim for complete coverage of all decision points 2. Identify boundary cases and test them 3. Check all cases using hand-tracing 4. Assume invalid input will never occur Section 3.6 Problem Solving: Test Cases Title What is reasonable for checking/testing code? type mc section 3.6 Problem Solving: Test Cases id testbank-py-1-ch03-63 72. Consider the following code segment: if a == 0 : print("a is 0") elif a < 0 : print("a is less than 0") else : print("a is greater than 0") What is the minimum number of test cases needed to test every line of code in this segment? 1. 2 2. 3 3. 4 4. 5 Section 3.6 Problem Solving: Test Cases Title How many test cases are needed to test every line of code in this segment? type mc section 3.6 Problem Solving: Test Cases id


72. testbank-py-1-ch03-64 73. Which operators listed below are considered boolean operators: 1. < / > 2. and / or 3. == / != 4. <= / >= Section 3.7 Boolean Variables and Operators Title What are boolean operators? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-66 74. Consider the following code snippet: emp = int(input("Enter Celsius temperature: ")) if temp > 0 and temp < 100 : print("Liquid") if temp <= 0 or temp >= 100 : print("Not liquid") Assuming the user enters a value of 120, what will be the output: 1. Nothing is printed 2. Liquid 3. Not Liquid 4. LiquidNotLiquid Section 3.7 Boolean Variables and Operators Title Given a code snippet and an input value, what output is produced? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-67 75. Which of the following variables is used to store a condition that can be either True or False? 1. Logical 2. Boolean 3. Algebraic 4. Conditional Section 3.7 Boolean Variables and Operators Title What kind of variable is used to store a true/false condition? type mc


75.

section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-68

76. Rewrite the following algebraic expression to an equivalent Python expression: 32 <= temp <= 100 1. if temp <= 32 and temp <= 100 2. if temp <= 32 or temp <= 100 3. if temp >= 32 and temp <= 100 4. if temp >= 32 or temp <= 100 Section 3.7 Boolean Variables and Operators Title Rewrite an algebraic expression into the equivelant Python expression? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-71 77. What value causes the following logical expression to 'short-circuit'? if temp >= 32 and temp <= 100 1. temp = 0 2. temp = 32 3. temp = 100 4. temp = 75 Section 3.7 Boolean Variables and Operators Title What value causes a given expression to short-circuit? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-72 78. Using De Morgan's law, what is the equivalent to this statement? if not (state == "PA" or state == "OH") 1. if state != "PA" and state != "OH" 2. if state != "PA" or state != "OH" 3. if state == "PA" and state == "OH" 4. if state == "PA" or state == "OH" Section 3.7 Boolean Variables and Operators Title Using De Morgan's law, identify an equivalent expression? type mc


78. section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-74 79. Using De Morgan's law, what is the equivalent to this statement? if not (state == "PA" and state == "OH") 1. if state != "PA" and state != "OH" 2. if state != "PA" or state != "OH" 3. if state == "PA" and state == "OH" 4. if state == "PA" or state == "OH" Section 3.7 Boolean Variables and Operators Title Using De Morgan's law, identify an equivelant expression? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-75 80. Consider the following code snippet: attendance = True failed = False Which of the following if statements include a condition that evaluates to True? 1. if attendance == "true" : 2. if attendance : 3. if failed : 4. if attendance == failed : Section 3.7 Boolean Variables and Operators Title What if statements include a condition that evaluates to true? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-76 81. Consider the following code snippet: age = int(input("Enter your age: ")) if age < 13 : print("Child", end="") if age >= 13 and age <= 19 : print("Teen", end="") if age > 19 and age < 30 : print("Young adult", end="") if age >= 30 and age <= 50 :


81.

print("Adult", end="") if age > 50 : print("Young at heart", end="") Assuming that the user enters 55 as the age, what is the output? 1. Teen 2. Young at heart 3. Child 4. Adult Section 3.7 Boolean Variables and Operators Title What is output of the code snippet with this input? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-77

82. Given the following code snippet: grade = int(input("Enter student grade: ")) if grade >= 90 : letterGrade = "A" elif grade >= 80 and grade < 90 : letterGrade = "B" elif grade >= 70 and grade < 80 : letterGrade = "C" elif grade >= 60 and grade < 70 : letterGrade = "D" else : letterGrade = "E" print(letterGrade) what is value of grade when the user enters 75? 1. "A" 2. "B" 3. "C" 4. "D" Section 3.7 Boolean Variables and Operators Title What is the output of a code snippet given a specific input value? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-80 83. Which of the following operators is used to invert a conditional statement? 1. or 2. and 3. not


83.

4. equal Section 3.7 Boolean Variables and Operators Title Which operator is used to invert a conditional statement? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-81

84. Given that the following code snippet: isFelon = False answer = input("have you ever committed a felony? ") if answer == "Yes" or answer == "yes" : isFelon = True age = int(input("what is your age? ")) which statement assigns the variable mayVote a value of True if a person may vote if they are 18 or older and not a felon? 1. mayVote = age > 18 or not isFelon 2. mayVote = not ( age >= 18 and isFelon) 3. mayVote = age >= 18 and not isFelon 4. mayVote = not ( age >= 18 or isFelon) Section 3.7 Boolean Variables and Operators Title Which of the following statements assigns the Boolean variable correctly? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-83 85. Given the following code snippet: MIN_SPEED = 45 MAX_SPEED = 65 speed = 55 if not (speed < MAX_SPEED) : speed = speed - 10 if not (speed > MIN_SPEED) : speed = speed + 10 print(speed) what output is produced? 1. 45 2. 55 3. 65 4. 50 Section


85. 3.7 Boolean Variables and Operators Title What is the output of a Boolean not code snippet? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-84 86. Given the following code snippet: score = 0 price = 100.0 if score > 0 and price < 200 and price / score > 10 : print("buy!") which of the following statements is true? 1. The output is buy! 2. The code snippet runs, but there is no output 3. The code snippet has syntax errors 4. The code snippet causes a divide-by-zero exception Section 3.7 Boolean Variables and Operators Title Which statement is true on the basis of this code snippet? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-85 87. Which of the following options checks that city is neither Atlanta or Philadelphia? 1. if not city == "Atlanta" or not city == "Philadelphia" 2. if not (city == "Atlanta" or city == "Philadelphia") 3. if not (city == "Atlanta" and city == "Philadelphia") 4. if not city == "Atlanta" or city == "Philadelphia" Section 3.7 Boolean Variables and Operators Title Which of the following options checks that city is neither Atlanta or Philadelphia? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-86 88. Assuming a user enters 30, 55, and 10 as the input, what is the output of the following code snippet? num1 = int(input("Enter a number: ")) num2 = int(input("Enter a number: ")) num3 = int(input("Enter a number: "))


88. if not (num1 > num2 and num1 > num3) : print(num1) elif not(num2 > num1 and num2 > num3) : print(num2) elif not (num3 > num1 and num3 > num2) : print(num3) 1. 55 2. 10 3. 0 4. 30 Section 3.7 Boolean Variables and Operators Title What is the output of the nested if code snippet given three input values? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-87 89. Assuming a user enters 30, 55, and 10 as the input, what is the output of the following code snippet? num1 = int(input("Enter a number: ")) num2 = int(input("Enter a number: ")) num3 = int(input("Enter a number: ")) if num1 > num2 and num1 > num3 : print(num1) elif num2 > num1 and num2 > num3 : print(num2) elif num3 > num1 and num3 > num2 : print(num3) 1. 55 2. 10 3. 0 4. 30 Section 3.7 Boolean Variables and Operators Title What is the output of the nested if code snippet given three input values? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-88 90. Which of the following conditions is True only when the variables a, b, and c contain three different values? 1. if a != b and a != c and b != c : 2. if a != b or a != c or b != c : 3. if not (a == b and b == c and a == c) : 4. if a != b != c : Section


90.

3.7 Boolean Variables and Operators Title Which of the following conditions is true only when the variables a, b, and c contain three different values? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-89

91. Consider the following code segment. It should display a message only if the cost is between 50 and 75 dollars. The message should also be displayed if the cost is exactly 50 dollars or exactly 75 dollars. if _________________ : print("The cost is in the desired range") What condition should be placed in the blank to achieve the desired behavior? 1. cost > 50 2. cost < 75 3. cost >= 50 and cost <= 75 4. cost >= 50 or cost <= 75 Section 3.7 Boolean Variable and Operators Title Complete an if statement with an appropriate condition type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-90 92. Water is liquid between 0 and 100 degrees Celsius. The following code segment should display a message if the water is not liquid. For this question, we will assume that water is liquid if it is exactly 0 degrees or exactly 100 degrees. if _________________ : print("The water is not liquid") What condition should be placed in the blank to achieve the desired behavior? 1. temp < 0 2. temp > 100 3. temp < 0 and temp > 100 4. temp < 0 or temp > 100 Section 3.7 Boolean Variables and Operators Title Complete an if statement with an appropriate condition type mc section


92. 3.7 Boolean Variables and Operators id testbank-py-1-ch03-91 93. Suppose that b is False and x is 0. Which of the following expressions evaluates to True? 1. b or x == 1 2. b and x == 0 3. not b and x == 1 4. not b or x == 1 Section 3.7 Boolean Variables and Operators Title Which of the following expressions evaluates to True? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-92 94. Suppose that b is False and x is 0. Which of the following expressions evaluates to True? 1. not b and x == 1 2. b or x == -1 3. not b or b 4. x == 1 or x == -1 Section 3.7 Boolean Variables and Operators Title Which of the following expressions evaluates to True? type mc section 3.7 Boolean Variables and Operators id testbank-py-1-ch03-93 95. Which operator has the lowest precedence? 1. != 2. * 3. ** 4. and Section 3.7 Boolean Variables and Operators Title Which operator has the lowest precedence? type mc section 3.7 Boolean Variables and Operators id testbank-py-2-ch03-122


96. Which of the following values make the expression not x == y and z > x true? 1. x = 10, y = 10, z = 15 2. x = 10, y = 20, z = 15 3. x = 10, y = 2, z = 5 4. x = 10, y = 20, z = 10 Section 3.7 Boolean Variables and Operators Title Which of the following values make the expression not x == y and z > x true? type mc from testbank-py-1-ch03-34 section 3.7 Boolean Variables and Operators id testbank-py-2-ch03-34 97. What two values does the Boolean (bool) data type have in Python? 1. Yes / No 2. True / False 3. 0 / 1 4. -1 / 1 Section 3.7 Boolean Variables and Operators Title What are the values of a boolean variable? type mc from testbank-py-1-ch03-65 section 3.7 Boolean Variables and Operators id testbank-py-2-ch03-65 98. Given two variables x and y, how do you test whether exactly one of them is zero? 1. if x == 0 or y == 0 : 2. if x = 0 or y = 0 : 3. if x == 0 and y != 0 or y == 0 and x != 0 : 4. if x == 0 and y != 0 and y == 0 and x != 0 : Section 3.7 Boolean Variables and Operators Title Given a code snippet, determine the correct boolean expression to test for a given condition? type mc from testbank-py-1-ch03-69 section 3.7 Boolean Variables and Operators id testbank-py-2-ch03-69 99. Given two variables x and y, how do you test whether at least one of them is zero?


99.

1. if x == 0 or y == 0 : 2. if x = 0 or y = 0 : 3. if x == 0 and y != 0 or y == 0 and x != 0 : 4. if x == 0 and y != 0 and y == 0 and x != 0 : Section 3.7 Boolean Variables and Operators Title Given a code snippet, determine the correct boolean expression to test for a given condition? type mc from testbank-py-1-ch03-70 section 3.7 Boolean Variables and Operators id testbank-py-2-ch03-70

100. The following logical expression will 'short-circuit'... quantity > 0 and price/quantity < 10 1. When quantity is equal to 0 2. When quantity is equal to 5 3. When price/quantity is less than 10 4. When price/quantity is greater than 10 Section 3.7 Boolean Variables and Operators Title What value causes a given expression to short-circuit? type mc from testbank-py-1-ch03-73 section 3.7 Boolean Variables and Operators id testbank-py-2-ch03-73 101. Which of the following expressions represents a legal way of checking whether a value assigned to the num variable falls within the range 0 to 150 (inclusive)? 1. if num >= 150 and num <= 0 : 2. if num >= 0 and num <= 150 : 3. if num >= 0 or num <= 150 : 4. if num >= 150 or num <= 0 : Section 3.7 Boolean Variables and Operators Title Which expression checks whether a value falls between 0 and 150 inclusive? type mc from testbank-py-1-ch03-78 section 3.7 Boolean Variables and Operators id testbank-py-2-ch03-78


102. Which of the following expressions represents a legal way of checking whether a value assigned to the num variable is either less than 100 or more than 200? 1. if num < 100 and num > 200 : 2. if num < 100 and num > 200 : 3. if num < 100 or num > 200 : 4. if num <= 100 or num >= 200 : Section 3.7 Boolean Variables and Operators Title Which of the following expressions represents a legal way of checking whether a value assigned to the num variable is either less than 100 or more than 200? type mc from testbank-py-1-ch03-79 section 3.7 Boolean Variables and Operators id testbank-py-2-ch03-79 103. Which of the following conditions is true only when the integer variable middle is between 0 and 10 inclusive? 1. middle >= 0 and middle <= 10 2. 0 < middle < 10 3. 0 <= middle or middle <= 10 4. middle > 0 and middle < 10 Section 3.7 Boolean Variables and Operators Title Which of the following conditions is true only when the integer variable middle is between 0 and 10? type mc from testbank-py-1-ch03-82 section 3.7 Boolean Variables and Operators id testbank-py-2-ch03-82 104. What string method can be used to determine if the string contained in the variable text only consists of numbers? 1. text.isalnum() 2. text.isalpha() 3. text.isdigit() 4. text.islower() Section 3.8 Analyzing Strings Title What String method checks for all numbers in a variable? type mc section 3.8 Analyzing Strings id testbank-py-1-ch03-100


105. What will be printed by the following code snippet? name = "Ravi Avalon" counter = name.count("av") print(counter) 1. 0 2. 1 3. 2 4. -1 Section 3.8 Analyzing Strings Title What value is returned when using the String method count? type mc section 3.8 Analyzing Strings id testbank-py-1-ch03-101 106. What will be printed by the following code snippet? name = "Dino the Dinosaur" counter = name.count("Di") print(counter) 1. 0 2. 1 3. 2 4. -1 Section 3.8 Analyzing Strings Title What value is returned when using the String method count? type mc section 3.8 Analyzing Strings id testbank-py-1-ch03-102 107. Which of the following statements returns the number of blank spaces contained in the string sentence? 1. sentence.count(" ") 2. " " in sentence 3. sentence.find(" ") 4. count(sentence) Section 3.8 Analyzing Strings Title What method is used to identify the number of spaces in a string variable? type mc section 3.8 Analyzing Strings


107.

id testbank-py-1-ch03-103

108. Review the code snippet below: name1 = "Betty joe" name2 = "Betty Jean" name3 = "Betty Jane" if name1 < name2 : if name1 < name3 : print(name1, "is first") else : print(name3, "is first") else : if name2 < name3 : print(name2, "is first") else : print(name3, "is first") what output is produced? 1. Betty joe is first 2. Betty Jean is first 3. Betty Jane is first 4. Betty joe is firstBetty Jean is firstBetty Jane is first Section 3.8 Analyzing Strings Title Review the code snippet below; what output is produced? type mc section 3.8 Analyzing Strings id testbank-py-1-ch03-105 109. How do you test if a filename (given as a string) has an extension of ".png", ".jpg" or ".gif"? 1. if filename.endswith(".png" or ".jpg" or ".gif") : 2. if filename.endswith(".png") or filename.endswith(".jpg") or filename.endswith(".gif") : 3. if ".png" in filename or ".jpg" in filename or ".gif" in filename : 4. if filename.contains(".jpg", ".gif", ".png") : Section 3.8 Analyzing Strings Title How do you test if a filename (given as a string) has a valid extension? type mc section 3.8 Analyzing Strings id testbank-py-1-ch03-106 110. What value is displayed by the following code segment?


110. s = "Computer Science" x = s.find("TER") print(x) 1. -1 2. 0 3. 5 4. 6 Section 3.8 Analyzing Strings Title Search for a substring within a string type mc section 3.8 Analyzing Strings id testbank-py-1-ch03-107 111. What value is displayed by the following code segment? name = "John Smith" print(name.startswith("john")) 1. -1 2. 0 3. False 4. True Section 3.8 Analyzing Strings Title Determine what is output by the starts with method type mc section 3.8 Analyzing Strings id testbank-py-1-ch03-108 112. Which of the following checks to see if the string variable sentence starts with the string "Dear"? 1. if "Dear" in sentence : 2. if sentence.find("Dear") : 3. if "Dear" not in sentence : 4. if sentence.startswith("Dear") : Section 3.8 Analyzing Strings Title Which statement tests if a string contains a substring at the beginning? type mc section 3.8 Analyzing Strings id testbank-py-1-ch03-95


113. What value is printed by the following code snippet? name = "John R. Johnson" firstName = "John" location = name.find(firstName) print(location) 1. -1 2. 0 3. 8 4. 1 Section 3.8 Analyzing Strings Title What value is returned when using the find substring command? type mc section 3.8 Analyzing Strings id testbank-py-1-ch03-96 114. What value is printed by the following code snippet? name = "John R. Johnson" firstName = "Joe" location = name.find(firstName) print(location) 1. -1 2. 0 3. 8 4. 1 Section 3.8 Analyzing Strings Title What value is returned when using the find substring command? type mc section 3.8 Analyzing Strings id testbank-py-1-ch03-97 115. What string method can be used to determine if the string contained in the variable text only consists of letters? 1. text.isalnum() 2. text.isalpha() 3. text.isdigit() 4. text.islower() Section 3.8 Analyzing Strings Title What String method checks for all characters in a variable? type


115.

mc section 3.8 Analyzing Strings id testbank-py-1-ch03-98

116. What string method can be used to determine if all characters within a string are lowercase? 1. text.isalnum() 2. text.isalpha() 3. text.isdigit() 4. text.islower() Section 3.8 Analyzing Strings Title What String method checks for all lowercase characters? type mc section 3.8 Analyzing Strings id testbank-py-1-ch03-99 117. Review the code snippet below: sentence = input("Enter some text: ") firstCh = sentence[0] Which of the following statements correctly determines if the first letter of the string contained in sentence is an uppercase letter? 1. if firstCh.isupper() : 2. if not (firstCh.isupper()) : 3. if firstCh.isspace() : 4. if not (firstCh.isspace()) : Section 3.8 Analyzing Strings Title Which of the following statements correctly determines if the first letter of the string is an uppercase letter? type mc from testbank-py-1-ch03-104 section 3.8 Analyzing Strings id testbank-py-2-ch03-104 118. What value is displayed when the following code segment is executed? s = "Jonathan" print(s.endswith("n")) 1. -1 2. 0


118.

3. False 4. True Section 3.8 Analyzing Strings Title Trace code involving the endswith method type mc section 3.8 Analyzing Strings id testbank-py-2-ch03-123

119. Which of the following checks to see if there is a comma anywhere in the string variable name? 1. if "," in name : 2. if name.contains(",") : 3. if "," not in name : 4. if name.startswith(",") : Section 3.8 Analyzing Strings Title Which statement tests if a string contains a substring? type mc from testbank-py-1-ch03-94 section 3.8 Analyzing Strings id testbank-py-2-ch03-94 120. Which of the following statements can be used to validate whether the value a user entered for a grade is in the range 0 to 100, including both 0 and 100? 1. if grade > 0 and grade < 100 : 2. if grade >= 0 and grade <= 100 : 3. if grade <= 0 and grade >= 100 : 4. if grade <=0 or grade >=100 : Section 3.9 Application: Input Validation Title Which statement validates the user input is between 0 and 100? type mc section 3.9 Application: Input Validation id testbank-py-1-ch03-109 121. Which of the following statements is the best choice to validate user input when entering a marital status as a single letter? 1. if maritalStatus == "s" or maritalStatus == "m" : 2. if maritalStatus == "S" or maritalStatus == "M" :


121.

3. if (maritalStatus == "s" or maritalStatus == "m" or maritalStatus == "S" or maritalStatus == "M") : 4. if maritalStatus == "s" or "S" or "m" or "M" : Section 3.9 Application: Input Validation Title Which statements can be used to validate the user entered a valid marital status? type mc from testbank-py-1-ch03-110 section 3.9 Application: Input Validation id testbank-py-2-ch03-110

122. Review the code snippet below: maritalStatus = input("Enter your marital status (s for single, m for married): ") maritalStatus = maritalStatus.upper() Which of the following statements can be used to validate whether the user entered a valid marital status? 1. if maritalStatus == "S" or maritalStatus == "M" : 2. if maritalStatus == "s" or maritalStatus == "m" : 3. if (maritalStatus == "s" or maritalStatus == "m") and (maritalStatus == "S" or maritalStatus == "M") : 4. if maritalStatus == "s" or "S" or "m" or "M" : Section 3.9 Application: Input Validation Title Which statements can be used to validate the user entered a valid marital status? type mc from testbank-py-1-ch03-111 section 3.9 Application: Input Validation id testbank-py-2-ch03-111 123. Review the code snippet below: month = int(input("Enter your two digit birth month: ")) Which of the following statements checks that the user entered a valid month? 1. if month >= 1 or month <= 12 : 2. if month >= 1 and month <= 12 3. if month > 1 or month < 12 : 4. if month > 1 and month < 12 :


123. Section 3.9 Application: Input Validation Title Which statements can be used to validate the user entered a valid birth month? type mc from testbank-py-1-ch03-112 section 3.9 Application: Input Validation id testbank-py-2-ch03-112 124. Which statement will successfully import the pyplot submodule? 1. from math import pyplot 2. from matplotlib import pyplot 3. import pyplot 4. import * from pyplot Section 3.9 Application: Input Validation Title Which statement will successfully import the pyplot submodule? type mc section 3.9 Application: Input Validation id testbank-py-2-ch03-124 125. Which statement adds a bar to a pyplot graph after pyplot has been imported by the following statement? from matplotlib import pyplot 1. bar(4, 44.5) 2. pyplot.bar(4, 44.5) 3. pyplot(4, 44.5) 4. bar.pyplot(4, 44.5) Section 3.9 Application: Input Validation Title Which statement adds a bar to a pyplot graph? type mc section 3.9 Application: Input Validation id testbank-py-2-ch03-125


1. How many times will the following loop run? i=0 while i < 10 : print(i) i=i+1 1. 0 2. 8 3. 9 4. 10 Section 4.1 The while loop Title How many iterations of while loop? type mc section 4.1 The while Loop id testbank-py-1-ch04-02 2. How many times does the code snippet given below display "Loop Execution"? i=1 while i != 10 : print("Loop Execution") i=i+1 1. Infinite times 2. 8 times 3. 9 times 4. 10 times Section 4.1 The while Loop Title How many iterations of while loop? type mc section 4.1 The while Loop id testbank-py-1-ch04-04 3. What is the output of the following code snippet? i=1 while i < 10 : print(i, end = " ") i=i+2 if i == 5 : i=9 1. 1 3 5 2. 1 3 9


3.

3. 1 3 5 7 9 4. 1 3 5 9 Section 4.1 The while Loop Title What does this while loop print? type mc section 4.1 The while Loop id testbank-py-1-ch04-06

4. What is the output of the code fragment given below? i=0 j=0 while i < 125 : i=i+2 j=j+1 print(j) 1. 0 2. 62 3. 63 4. The code fragment displays no output because it does not compile. Section 4.1 The while Loop Title What is output of while loop? type mc section 4.1 The while Loop id testbank-py-1-ch04-09 5. What is the output of the following loop? s =1 n =1 while s < 10 * n : s=s+n n=n+1 print(s) 1. 211 2. 210 3. 120 4. 123 Section 4.1 The while Loop Title What is the output of the following while loop? type mc


5. section 4.1 The while Loop id testbank-py-1-ch04-10 6. What will be the result of running the following code fragment? year = 0 rate = 5 principal = 10000 interest = 0 while year < 10 : interest = (principal * year * rate) / 100 print("Interest ", interest) 1. The code fragment will display the interest calculated for nine years. 2. The code fragment will continue to display the calculated interest forever because the loop will never end. 3. The code fragment will not display the calculated interest and halt abruptly. 4. The code fragment will not display any output because it will not compile. Section 4.1 The while Loop Title What is result of while loop? type mc section 4.1 The while Loop id testbank-py-1-ch04-11 7. Which of the following code snippets displays the output exactly 10 times? 1. i=0 while i <= 10 : print("This is example 1.") i=i+1 2. i=0 while i < 10 : print("This is example 2.") i=i+1 3. i=0 while i < 10 : print("This is example 3.") 4. i=1 while i < 10 : print("This is example 4.") i=i+1 Section 4.1 The while Loop


7. Title Which while loop executes 10 times? type mc section 4.1 The while Loop id testbank-py-1-ch04-12 8. What is the output of the following code snippet? i=1 while i != 9 : print(i , end = " ") i=i+1 if i == 9 : print("End") 1. 1 End 2. 1 End (infinite loop) 3. 1 2 3 4 5 6 7 8 End 4. 1 2 3 4 5 6 7 8 End (infinite loop) Section 4.1 The while Loop Title What is output of while loop? type mc section 4.1 The while Loop id testbank-py-1-ch04-13 9. How many times is the text "Let's have fun with Python." printed when this code snippet is run? i=0 while i <= 10 : print("Let's have fun with Python.") i=i+1 if i % 2 == 0 : i = 10 1. 1 2. 2 3. 3 4. 10 Section 4.1 The while Loop Title How many times does do loop with nested if execute? type mc section 4.1 The while Loop id


9. testbank-py-1-ch04-15 10. Select the statement that correctly completes the loop in this code snippet. years = 20 rate = 0.05 balance = 10000 while years > 0 : # Place code here interest = balance * rate / 100 balance = balance + interest 1. years = years + 1 2. years = years - 1 3. balance = balance + 1 4. balance = balance - 1 Section 4.1 The while Loop Title Insert appropriate code in while loop type mc section 4.1 The while Loop id testbank-py-1-ch04-16 11. Is the following code snippet legal? b = False while b != b : print("Do you think in Python?") 1. Yes, it is legal but does not print anything. 2. Yes, it is legal and prints "Do you think in Python?" once. 3. Yes, it is legal and prints "Do you think in Python?" twice. 4. No, it is not legal and gives a compilation error. Section 4.1 The while Loop Title While loops with Boolean conditions type mc section 4.1 The while Loop id testbank-py-1-ch04-17 12. What is the output of the following code snippet?


12. i = 1 while i < 20 : print(i , " ") i=i+2 if i == 15 : i = 19 1. 1 3 5 7 9 11 13 15 17 19 2. 1 3 5 7 9 11 13 19 3. 1 3 5 7 9 11 13 15 17 4. 1 3 5 7 9 11 13 17 19 Section 4.1 The while Loop Title What is output of while loop with nested if? type mc section 4.1 The while Loop id testbank-py-1-ch04-18 13. What are the values of i and j after the following code snippet is run? i = 10 j = 20 count = 0 while count < 5 : i=i+i i=i+1 j=j-1 j=j-j count = count + 1 print("i = ", i , ", j = ", j) 1. i = 45, j = 1 2. i = 351, j = 0 3. i = 351, j = 2 4. i = 1311, j = 35 Section 4.1 The while Loop Title What are values of i and j after while loop? type mc section 4.1 The while Loop id testbank-py-1-ch04-19 14. How many times does the following code fragment display "Hi"? i = 10 while i >= 0 : print("Hi")


14. i = i - 1 1. 9 times 2. 10 times 3. 11 times 4. 12 times Section 4.1 The while Loop Title How many times does while loop execute? type mc section 4.1 The while Loop id testbank-py-1-ch04-24 15. What is the output of the code snippet given below? n=0 while n * n < 100 : print(n * n, end = " ") n=n+1 1. 0 1 4 9 16 25 36 49 64 81 2. 0 1 2 3 4 5 6 7 ... 99 100 3. 0 1 1 2 3 5 8 13 21 34 55 89 4. 0 0 0 0 0 0 (infinite loop) Section 4.1 The while Loop Title What is output of this while loop? type mc section 4.1 The while Loop id testbank-py-1-ch04-26 16. What is the output of the code snippet given below? s = "abcde" length = len(s) i=1 while i < length : print(s[i]) i=i+1 1. No output 2. abcd 3. abcde 4. bcde Section 4.1 The while Loop Title What is the output of while loop with the slice operator? type


16. mc section 4.1 The while Loop id testbank-py-1-ch04-29 17. What is the output of the code snippet given below? s = "abcde" i=1 while i < 5 : if i > 1 : print(s[i]) 1. No output 2. No output (infinite loop) 3. abcde 4. bcde Section 4.1 The while Loop Title What is output of while loop with nested if? type mc section 4.1 The while Loop id testbank-py-1-ch04-30 18. What is the output of the code snippet given below? s = "12345" i=0 while i < 5 : print(s[i]) i=i+1 1. No output 2. 1234 3. 12345 4. 2345 Section 4.1 The while Loop Title What is output of while loop? type mc section 4.1 The while Loop id testbank-py-1-ch04-32 19. What is the output of the code snippet given below? s = "12345"


19. i = 1 while i < 5 : if i > 1 : print(s[i]) 1. No output 2. No output (infinite loop) 3. 12345 4. 2345 Section 4.1 The while Loop Title What is output of while loop with nested if? type mc section 4.1 The while Loop id testbank-py-1-ch04-33 20. How many times does the code snippet below display "Hello"? i=0 while i != 15 : print("Hello") i=i+1 1. Infinite times 2. 14 times 3. 15 times 4. 16 times Section 4.1 The while Loop Title How many times does while loop display result? type mc section 4.1 The while Loop id testbank-py-1-ch04-34 21. How many times does the following loop run? i=0 j=1 while j >= 1 : print(i , ";" , j) i=i+1 if i % 3 == 0 : j=j- 1 1. 1 time 2. 2 times 3. 3 times 4. 4 times


21. Section 4.1 The while Loop Title How many times does this loop with a nested if run? type mc section 4.1 The while Loop id testbank-py-1-ch04-36 22. What is the output of the following code snippet? i=1 while i <= 10 : print("Inside the while loop") i = i + 10 1. No output because of compilation error. 2. "Inside the while loop" will be displayed 10 times. 3. No output after successful compilation. 4. "Inside the while loop" will be displayed only once. Section 4.1 The while Loop Title What is output of while loop? type mc section 4.1 The while Loop id testbank-py-1-ch04-38 23. How many copies of the letter A are printed by the following loop? i=0 while i < 5 : print("A") i=i+1 1. 0 2. 4 3. 5 4. Infinity Section 4.1 The while Loop Title How many copies of the letter A are printed by the following loop? type mc section 4.1 The while Loop id testbank-py-1-ch04-39 24. How many copies of the letter B are printed by the following loop?


24. i = 0 while i == 5 : print("B") i=i+1 1. 0 2. 4 3. 5 4. Infinity Section 4.1 The while Loop Title How many copes of the letter B are printed by the following loop? type mc section 4.1 The while Loop id testbank-py-1-ch04-40 25. How many copies of the letter C are printed by the following loop? i=0 while i < 5 : print("C") i=i-1 1. 0 2. 4 3. 5 4. Infinity Section 4.1 The while Loop Title How many copies of the letter C are printed by the following loop? type mc section 4.1 The while Loop id testbank-py-1-ch04-41 26. What is the value of i at the end of the following code segment? i=1 while i < 32 : i=i*2 1. 16 2. 31 3. 32 4. 64 Section 4.1 The while Loop Title What is the value of i at the end of this loop? type


26.

mc section 4.1 The while Loop id testbank-py-1-ch04-42

27. The following while loop should continue to run as long as the user does not enter a negative number. What condition should be used to achieve this behavior? x = int(input("Enter an integer: ")) while ____________ : x = int(input("Enter an integer: ")) 1. x != 0 2. x == 0 3. x <= 0 4. x >= 0 Section 4.1 The while Loop Title Fill in the correct condition for a while loop type mc section 4.1 The while Loop id testbank-py-1-ch04-43 28. What term is used to describe a loop where the number of times that the loop will execute is known before the body of the loop executes for the first time? 1. Definite 2. Fiscal 3. Indefinite 4. Infinite Section 4.1 The while Loop Title What term is used to describe a loop where the number of times that the loop will execute is known before the body of the loop executes for the first time? type mc section 4.1 The while Loop id testbank-py-2-ch04-148 29. Which of the following changes will make the following code snippet display Let us learn Python exactly 10 times? i=0 while i <= 10 : print("Let us learn Python") i=i+1 1. Replace while i <= 10 with while i < 9


29.

2. Replace while i <= 10 with while i < 11 3. Replace while i <= 10 with while i < 12 4. Replace i = 0 with i = 1 Section 4.1 The while Loop Title What changes needed so while loop executes 10 times? type mc from testbank-py-1-ch04-14 section 4.1 The while Loop id testbank-py-2-ch04-14

30. Which statement corrects the off-by-one error in the following code: # This code prints the first 10 numbers starting with zero i=0 while i <= 10 : print(i) i=i+1 1. Replace i = 0 with i = 1 2. Replace while i <= 10 with while i < 10 3. Replace i = i + 1 with i = i + 2 4. Replace while i <= 10 with while i + 1< 10 Section 4.1 The while loop Title How do you fix an off-by-one error? type mc from testbank-py-1-ch04-01 section 4.1 The while Loop id testbank-py-2-ch04-01 31. What is the output of the following code fragment? i=1 sum = 0 while i <= 15 : sum = sum + i i=i+1 print("The value of sum is", sum) 1. The value of sum is 0 2. The value of sum is 105 3. The value of sum is 120 4. The value of sum is 136 Section


31. 4.1 The while Loop Title What is the output of while loop that sums? type mc from testbank-py-1-ch04-20 section 4.1 The while Loop id testbank-py-2-ch04-20 32. What are the values of i and j after the following code fragment runs? i = 60 j = 50 count = 0 while count < 5 : i=i+i i=i+1 j=j-1 j=j-j count = count + 1 print("i =", i, ", j =", j) 1. i = 1951, j = 0 2. i = 1951, j = 45 3. i = 65, j = 1 4. i = 65, j = 45 Section 4.1 The while Loop Title What are values of variables after while loop executes? type mc from testbank-py-1-ch04-21 section 4.1 The while Loop id testbank-py-2-ch04-21 33. Which type of error could be reported by Python when the program contains an "off-by-one" error? 1. Syntax error 2. Compile-time error 3. Run-time error 4. Infinite loop error Section 4.1 The while Loop Title What type of error is an off-by-one error? type mc from


33. testbank-py-1-ch04-22 section 4.1 The while Loop id testbank-py-2-ch04-22 34. What is the output of the code snippet given below? i=0 while i != 11 : print(i, end=" ") i=i+3 1. 0 3 6 9 12 2. 0 3 6 9 12 15 18 3. 0 1 3 5 7 9 4. 0 3 6 9 12 ... (infinite loop) Section 4.1 The while Loop Title What is output of while loop? type mc from testbank-py-1-ch04-23 section 4.1 The while Loop id testbank-py-2-ch04-23 35. What is the output of the following code fragment? i=1 sum = 0 while i <= 11 : sum = sum + i i=i+1 print("The value of sum is", sum) 1. The value of sum is 65 2. The value of sum is 66 3. The value of sum is 55 4. The value of sum is 56 Section 4.1 The while Loop Title What is output of while loop? type mc from testbank-py-1-ch04-25 section 4.1 The while Loop id testbank-py-2-ch04-25


36. What is the last line of output produced by the code snippet below? i=0 total = 0 while total < 0 : i=i+1 total = total - i print(i, total) 1. 0 0 2. 1 1 3. No output 4. 0 -1 Section 4.1 The while Loop Title What does this code snippet produce? type mc from testbank-py-1-ch04-27 section 4.1 The while Loop id testbank-py-2-ch04-27 37. How many times does the following loop run? i=0 j=1 while j >= 1 : print("" , i , ";" , j) i=j+1 if i % 2 == 0 : j=j-1 1. 0 times 2. 1 time 3. 2 times 4. 4 times Section 4.1 The while Loop Title How many times does do loop with nested if execute? type mc from testbank-py-1-ch04-28 section 4.1 The while Loop id testbank-py-2-ch04-28 38. What is the output of the code snippet given below? s = "abcde"


38. j = len(s) - 1 while j >= 0 : print(s[j]) j=j- 1 1. abcd 2. bcde 3. bcbcd 4. edcba Section 4.1 The while Loop Title What is output of the while loop? type mc from testbank-py-1-ch04-31 section 4.1 The while Loop id testbank-py-2-ch04-31 39. What is the output of the code snippet given below? i=0 while i != 11 : print(" ", i) i=i+2 1. No output 2. 0 2 4 6 8 3. 10 12 14 16 18 ... (infinite loop) 4. 0 2 4 6 8 ... (infinite loop) Section 4.1 The while Loop Title What is output of while loop? type mc from testbank-py-1-ch04-35 section 4.1 The while Loop id testbank-py-2-ch04-35 40. What will be the output of the following code snippet? token = False while token : print("Hello") 1. "Hello" will continue to be displayed until the user stops the program. 2. No output because of compilation error. 3. No output after successful compilation. 4. "Hello" will be displayed only once. Section


40. 4.1 The while loop Title What is output of while loop with Boolean condition? type mc from testbank-py-1-ch04-37 section 4.1 The while Loop id testbank-py-2-ch04-37 41. What is the output of the code snippet given below? i=0 while i != 9 : print(i, end = " ") i=i+2 1. No output 2. 0 2 4 6 8 3. 10 12 14 16 18 ... (infinite loop) 4. 0 2 4 6 8 10 12 14 ... (infinite loop) Section 4.1 The while Loop Title What is output of while loop? type mc from testbank-py-1-ch04-03 section 4.1 The while Loop id testbank-py-2-ch04-03 42. What is the output of the code fragment given below? i=0 j=0 while i < 27 : i=i+2 j=j+1 print("j =", j) 1. j = 27 2. j = 12 3. j = 13 4. j = 14 Section 4.1 The while Loop Title What is output of while loop? type mc


42. from testbank-py-1-ch04-05 section 4.1 The while Loop id testbank-py-2-ch04-05 43. The code snippet below is supposed to check whether an integer greater than 1 is a prime number. What will be the result of executing it? j=2 result = 0 number = int(input("Please enter an integer (2 or greater):")) while j < number : if number % j == 0 : result = 1 j=j+1 if result == 1 : print("Number:", number, "is Not Prime.") else : print("Number:", number, "is Prime.") 1. The code snippet contains a compile error. 2. The code snippet displays the desired result. 3. The code snippet displays an incorrect result. 4. The code snippet causes an infinite loop. Section 4.1 The while Loop Title Will the while loop with if/else produce desired result? type mc from testbank-py-1-ch04-07 section 4.1 The while Loop id testbank-py-2-ch04-07 44. What is the output of the following code snippet? a=2 n = 16 r=1 b=a i=n while i > 0 : if i % 2 == 0 : # n is even b=b*b i=i/2 else : r=r*b i=i- 1


44. print("r =", r) 1. r = 16 2. r = 128 3. r = 4096 4. r = 65536 Section 4.1 The while Loop Title What is the output of while loop with nested if? type mc from testbank-py-1-ch04-08 section 4.1 The while Loop id testbank-py-2-ch04-08 45. What are the final values of the variables i, j, and n at the end of this loop? i=0 j = 12 n=0 while i != j : i=i+2 j=j-2 n=n+1 1. 2 10 1 2. 4 8 2 3. 6 6 3 4. 0 12 0 Section 4.2: Problem Solving: Hand-Tracing Title What are final values of three variables in a for loop? type mc section 4.2 Problem Solving: Hand-Tracing id testbank-py-1-ch04-44 46. When hand-tracing the loop in the code snippet below, which variables are important to evaluate? i = 10 j =5 k = -10 sum = 0 while i > 0 : sum = sum + i + j i=i- 1 print("Iteration: ", i) 1. The variables i and j 2. The variables i and sum


46.

3. The variables i, j, and k 4. The variables j and k Section 4.2 Problem solving: hand-tracing Title Which variables are important to monitor when hand-tracing a code snippet? type mc section 4.2 Problem Solving: Hand-Tracing id testbank-py-1-ch04-45

47. When hand tracing, drawing a line through the value stored in a variable means that 1. The value stored there has changed to something new 2. The variable is the wrong data type for the code being executed 3. The expression being evaluated uses that variable 4. The variable must be inside a loop Section 4.2 Problem solving: hand-tracing Title What does it mean to draw a line through values when hand-tracing? type mc section 4.2 Problem Solving: Hand-Tracing id testbank-py-1-ch04-46 48. When hand-tracing a portion of code, which statement about Boolean conditions is true? 1. They typically are too complex to be evaluated. 2. They do not need to be monitored because their result usually is not stored in a variable. 3. It is rare to encounter a Boolean condition. 4. They are crucial to evaluate since they determine if-statement conditions and looping. Section 4.2 Problem solving: hand-tracing Title Which statement about Boolean conditions is true? type mc section 4.2 Problem Solving: Hand-Tracing id testbank-py-1-ch04-47 49. What is the output of this code snippet? s=1 n=1 while s < 3 * n : s=s+n print(s , end = " ") n=n+1 1. 2 4 7 11 16 22 2. 1 3 5 7 9


49.

3. 2 3 5 6 7 4. 2 4 6 8 Section 4.2 Problem Solving: Hand-Tracing Title What is output of do-while loop? type mc section 4.2 Problem Solving: Hand-Tracing id testbank-py-1-ch04-48

50. What are the values of i and j after the following code snippet executes? i = 20 j = 70 count = 0 while count < 5 : i=i+i i=i+1 j=j-1 j=j-j count = count + 1 print(i) print(j) 1. i = 25, j = 1 2. i = 25, j = 65 3. i = 671, j = 0 4. i = 671, j = 65 Section 4.2 Problem Solving: Hand-Tracing Title What are values of variables after while loop executes? type mc section 4.2 Problem Solving: Hand-Tracing id testbank-py-1-ch04-49 51. The process of hand-tracing code is valuable because 1. It is usually faster than just running the code. 2. It is the best way to design an algorithm. 3. You must already have a working program in order to do it. 4. It gives valuable insight that you do not get by running the code. Section 4.2 Problem Solving: Hand-Tracing Title Why is hand tracing valuable? type mc section 4.2 Problem Solving: Hand-Tracing


51. id testbank-py-1-ch04-50 52. What is the output of the code snippet given below? s = "aeiou" i=0 while i < 5 : print(s[i], s[i + 1], end = " ") i=i+1 if i >= 3 : i=5 1. a 2. a e 3. a e i o u 4. a e e i i o Section 4.2 Problem Solving: Hand-Tracing Title What is output of the loop with nested if? type mc section 4.2 Problem Solving: Hand-Tracing id testbank-py-1-ch04-51 53. What is the sentinel value in the following code segment? value = 15 x = int(input("Enter an integer: ")) while x != 0 : value = value * 2 print(value + 3) x = int(input("Enter an integer: ")) 1. 0 2. 2 3. 3 4. 15 Section 4.3 Application: Processing Sentinel Values Title What is the sentinel value in the following code segment? type mc section 4.3 Application: Processing Sentinel Values id testbank-py-1-ch04-52 54. Of the following options, what should the user enter to cause the following while loop to terminate? done = False


54. while not done : x = float(input("Enter a number: ")) if x > 5.0 : print(x) elif x > 0.0 : done = False elif x < -5.0 : print(-x) else : done = True 1. -7.5 2. -2.5 3. 2.5 4. 7.5 Section 4.3 Application: Processing Sentinel Values Title What value will cause the while loop to terminate? type mc section 4.3 Application: Processing Sentinel Values id testbank-py-1-ch04-53 55. Which of the following statements is correct about a sentinel? 1. A sentinel is a value that creates a bridge between a data set and unrelated input. 2. A sentinel is a value that is part of the data to be processed by the program. 3. A sentinel is a value that terminates a program. 4. A sentinel is a value that indicates the end of an input sequence. Section 4.3 Application: Processing Sentinel Values Title Which statement about sentinels is correct? type mc section 4.3 Application: Processing Sentinel Values id testbank-py-1-ch04-55 56. What will be the output of the following code snippet? token1 = True while token1 : for i in range(0,10) : print("Hello") token1 = False 1. No output. 2. Hello will be displayed 10 times. 3. Hello will be displayed 9 times. 4. Hello will be displayed infinite times. Section 4.3 Application: Processing Sentinel Values


56. Title What is output of while loop with Boolean condition? type mc section 4.3 Application: Processing Sentinel Values id testbank-py-1-ch04-57 57. Insert a statement that will correctly terminate this loop when the end of input is reached. done = False while done != True : x = input("Enter a value") if x == "Q" : _________________ 1. stop 2. done = 1 3. exit 4. done = True Section 4.3 Application: Processing Sentinel Values Title Insert code to terminate a loop type mc section 4.3 Application: Processing Sentinel Values id testbank-py-1-ch04-60 58. Which of the following loops executes exactly 10 times? 1. for i in range(1, 11) : i= 1 2. found = False while i < 10 and found != True : i=i+1 if i % 10 == 0 : found = True 3. i= 0 while i <= 10 : i=i+1 4. i=0


58.

4. for i in range (1, 10) : print(i) Section 4.3 Application: Processing Sentinel Values Title Which of the following loops executes exactly 10 times? type mc from testbank-py-1-ch04-130 section 4.3 Application: Processing Sentinel Values id testbank-py-2-ch04-130

59. When will the loop in the following code snippet stop? sum = 0 count = 1 str = input("Enter values, Q to quit: ") while count < 100 and str != "Q" : value = float(str) sum = sum + value count = count + 1 str = input("Enter values, Q to quit: ") I. When the user enters an integer II. When the user enters the character Q III. After the user enters 100 numbers 1. I or II 2. II only 3. III only 4. II or III Section 4.3 Application: Processing Sentinel Values Title When does do loop with sentinel stop? type mc from testbank-py-1-ch04-133 section 4.3 Application: Processing Sentinel Values id testbank-py-2-ch04-133 60. The value that denotes the end of an input sequence is known as a: 1. Sedimentary value 2. Sentimental value 3. Sentinel value 4. Sequential value Section


60. 4.3 Application: Processing Sentinel Values Title The value that denotes the end of an input sequence is known as a(n): type mc section 4.3 Application: Processing Sentinel Values id testbank-py-2-ch04-149 61. Which of the following command lines starts the python program sum.py so that it will read its input from values.txt instead of the keyboard? 1. python sum.py < values.txt 2. python sum.py > values.txt 3. python values.txt < sum.py 4. python values.txt > sum.py Section 4.3 Application: Processing Sentinel Values Title Which command line uses input redirection correctly? type mc section 4.3 Application: Processing Sentinel Values id testbank-py-2-ch04-150 62. What happens when the following loop is executed? val1 = True val2 = False while val1 : if val1 : print("Hello") val1 = val2 1. No output will be displayed because of a compilation error. 2. "Hello" will be displayed only once. 3. "Hello" will be displayed an infinite number of times. 4. No output will be displayed even after successful compilation of the code snippet. Section 4.3 Application: Processing Sentinel Values Title What is output of while loop with nested if and Boolean conditions? type mc from testbank-py-1-ch04-54 section 4.3 Application: Processing Sentinel Values id testbank-py-2-ch04-54 63. Which statement is correct about the execution of the loop in the following code fragment?


63. num = int(input("Please enter a number (0 when done): ")) incr = 0 while num != 0 : incr = incr + 1 num = int(input("Please enter a number (0 when done): ")) print(incr) 1. The loop will execute only when 0 is entered. 2. The execution of the loop is independent of user input. 3. The program prints the count of positive inputs. 4. The program prints the count of inputs not equal to zero. Section 4.3 Application: Processing Sentinel Values Title Which statement is true about do loop with user input? type mc from testbank-py-1-ch04-56 section 4.3 Application: Processing Sentinel Values id testbank-py-2-ch04-56 64. What is the sentinel value in the following code snippet? age = 0 sumOfAges = 0 stop = 1 age = int(input("Enter an age (-1 to stop):")) while age != -1 : sumOfAges = sumOfAges + age age = input("Enter an age (-1 to stop):") print("Sum of ages ", sumOfAges) 1. 0 2. 1 3. 2 4. -1 Section 4.3 Application: Processing Sentinel Values Title Which is the sentinel in this snippet? type mc from testbank-py-1-ch04-58 section 4.3 Application: Processing Sentinel Values id testbank-py-2-ch04-58 65. What will be the final output of the following code snippet when a user enters input values in the order 10, 20, 30, 40, 50, and -1?


65. sum = 0 count = 0 salary = 0 average = 0 while salary != -1 : salary = float(input("Enter salaries (-1 to stop): ")) if salary != -1 : sum = sum + salary count = count + 1 if count > 0 : average = sum / count print("The average salary: ", average) else : print("No data!") 1. The average salary: 0.0 2. The average salary: 30.0 3. The average salary: 24.83333 4. There will be no output as the code snippet will not compile. Section 4.3 Application: Processing Sentinel Values Title What is output of snippet with input that includes a sentinel? type mc from testbank-py-1-ch04-59 section 4.3 Application: Processing Sentinel Values id testbank-py-2-ch04-59 66. Storyboards are a helpful part of the design process because the storyboard develops 1. A pseudocode description of the algorithm being designed 2. The mathematical formulas required for computing a correct answer 3. The information needed to solve the problem, and how to present that information 4. The amount of time and space needed to find a solution Section 4.4 Problem Solving: Storyboards Title What is the role of the storyboard? type mc section 4.4 Problem Solving: Storyboards id testbank-py-1-ch04-61 67. When designing storyboards, it is a good idea to use different colors to 1. Make it easy to distinguish between user input and program output. 2. Match the colors your program will use when it is finally designed. 3. Emphasize the difference between numbers and words. 4. Draw lines to divide up panels into different regions. Section 4.4 Problem Solving: Storyboards


67. Title What is the role of colors when designing using storyboards? type mc section 4.4 Problem Solving: Storyboards id testbank-py-1-ch04-62 68. Suppose you must design a program to calculate the roll-out (number of inches traveled in one revolution of the pedals of a bicycle based on its gear combinations). The user must provide the gear sizes, which must be converted into roll-out for all different gear combinations. How can the flow of user interaction for this problem be designed? 1. Hand-tracing can confirm code that implements gear selection. 2. Pseudocode can guide algorithm design through divide-and-conquer strategy. 3. A storyboard can be used. 4. The physical gears can lead to ideas for the correct algorithm to use. Section 4.4 Problem Solving: Storyboards Title How can user interaction be designed for an example problem? type mc section 4.4 Problem Solving: Storyboards id testbank-py-1-ch04-63 69. Which statement about storyboards is true? 1. A storyboard can help prevent potential user confusion early in the design process. 2. Storyboards are used primarily to understand how implemented programs work. 3. The storyboard helps to train users about how to use software. 4. Storyboards have no relationship to the structure of an actual working program. Section 4.4 Problem Solving: Storyboards Title Which statement about storyboards is true? type mc section 4.4 Problem Solving: Storyboards id testbank-py-1-ch04-64 70. What will be printed by the statements below? a = 10 while a > 5 : print(a , end = " ") a=a-2 1. 10 9 8 7 6 5 2. 10 8 6 4 3. 10 8 6 4. 10 8


70. Section 4.5 Common Loop Algorithms Title What will be printed by the statements below? type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-68 71. What will be printed by the statements below? val = 1 sum = 0 while val < 5 : sum = sum + val val = val + 1 print(sum) 1. 4 2. 5 3. 10 4. 15 Section 4.5 Common Loop Algorithms Title What will be printed by the statements below? type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-70 72. What will be printed by the statements below? val = 1 sum = 0 while val < 5 : sum = 0 sum = sum + val val = val + 1 print(sum) 1. 15 2. 10 3. 5 4. 4 Section 4.5 Common Loop Algorithms Title What will be printed by the statements below? type mc


72. section 4.5 Common Loop Algorithms id testbank-py-1-ch04-71 73. What will be printed by the statements below? for ctr in range(0, 10) : print(ctr, end = " ") 1. 0 1 2 3 4 5 6 7 8 9 10 2. 0 1 2 3 4 5 6 7 8 9 3. 0 2 4 6 8 4. 0 1 3 5 7 9 Section 4.5 Common Loop Algorithms Title What will be printed by the statements below? type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-72 74. What will be printed by the statements below? for ctr in range(10, 5, -1) : print(ctr, end = " ") 1. 10 9 8 7 6 5 2. 10 9 8 7 6 3. 5 6 7 8 9 10 4. 6 7 8 9 10 Section 4.5 Common Loop Algorithms Title What will be printed by the statements below? type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-73 75. Which of the following loops will print the odd numbers between 0 and 20? 1. num = 1 while num < 20 : print(num, " ") num = num + 2 2. num = 1 while num < 20 : print(num, " ")


75.

2. 3.

num = num + 1 num = 0 while num < 20 : print(num, " ") num = num + 2

4. num = 1 while num < 20 : num = num + 2 print(num, " ") Section 4.5 Common Loop Algorithms Title What will be printed by the statements below? type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-74 76. Which of the following loops will print the odd numbers between 0 and 20? 1. num = 1 while num < 11 : value = num * 2 - 1 print(value, " ") num = num + 1 2. num = 1 while num < 20 : value = num * 2 - 1 print(value, " ") num = num + 1 3. num = 1 while num < 10 : print(num, " ") num = num + 2 4. num = 1 while num < 20 : num = num + 2 print(num, " ") Section 4.5 Common Loop Algorithms Title What will be printed by the statements below? type mc


76. section 4.5 Common Loop Algorithms id testbank-py-1-ch04-75 77. Which of the following conditions can be added to the code below so it will loop until the value of sum is greater than 100? sum = input("enter an integer") while # Put condition here : sum = sum + input("Enter an integer") 1. sum != 0 2. sum <= 100 3. sum > 100 4. sum == 100 Section 4.5 Common Loop Algorithms Title Which of the following conditions can be added to the code below so it will loop until the value of sum is greater than 100? type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-76 78. What does the following code compute? sum = 0 count = 0 value = input("enter an integer") while value > 0 : sum = sum + value count = count + 1 value = input("enter next integer") result = sum * 1.0 / count print(result) 1. The average of all the integers in the input 2. The sum of all the positive integers in the input divided by the number of integers in the input 3. The average of all the positive integers in the input 4. The second smallest value in the input Section 4.5 Common Loop Algorithms Title What does the following loop compute? type mc


78. section 4.5 Common Loop Algorithms id testbank-py-1-ch04-77 79. What is the output of the code below? for val in range(0, 4) : print("+", end = "") for num in range(0, val) : print("0", end = "") 1. +0+00+000+0000 2. +000+000+000+000 3. ++0+00+000 4. ++++000000 Section 4.5 Common Loop Algorithms Title What is the output of the code below? type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-79 80. What is the output of the code below? num = 1 for val in range(0, 4) : sum = val for x in range(0, val, num) : sum = sum + x print(sum , end = " ") 1. 1 3 6 2. 1 2 3 6 3. 0 1 3 6 4. 0 1 2 3 3 Section 4.5 Common Loop Algorithms Title What is the output of the code below? type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-80 81. How many times does the following loop execute? i=0 found = False


81. while i < 100 and found != True : i=i+1 print(i, end = " ") j=i*i if i * i * i % j == j : found = True 1. 10 times 2. 20 times 3. 100 times 4. An infinite number of times Section 4.5 Common Loop Algorithms Title How many times does the following loop execute? type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-81 82. The following program is supposed to sum all of the numbers entered by the user. What line of code must be inserted in the blank so that the program will achieve this goal? total = 0.0 inputStr = input("Enter a value: ") while inputStr != "" : value = float(inputStr) ____________________ inputStr = input("Enter a value: ") 1. value = value + inputStr 2. value = value + total 3. total = total + inputStr 4. total = total + value Section 4.5 Common Loop Algorithms Title Complete the while loop that sums the numbers entered by the user type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-84 83. The following program is supposed to count how many even numbers are entered by the user. What line of code must be inserted in the blank so that the program will achieve this goal? evens = 0 inputStr = input("Enter a value: ") ____________________ value = int(inputStr) if value % 2 == 0:


83.

evens = evens + 1 inputStr = input("Enter a value: ") 1. while inputStr != 0 : 2. while inputStr % 2 == 0 : 3. while inputStr == 2 or 4 or 6 or 8 or 10 or ... : 4. while inputStr != "" : Section 4.5 Common Loop Algorithms Title Complete the while loop that counts the number of even numbers entered by the user type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-85

84. The following program is supposed to continue reading values from the user until a value between 25 and 75 is entered. What line of code must be inserted in the blank so that the program will achieve this goal? value = int(input("Enter a value: ")) ____________________ value = int(input("Enter a value: ")) 1. while value >= 25 or value <= 75 : 2. while value >= 25 and value <= 75 : 3. while value < 25 or value > 75 : 4. while value < 25 and value > 75 : Section 4.5 Common Loop Algorithms Title Complete the while loop that reads values until the user enters a value between 25 and 75 type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-86 85. The following program is supposed to print a message any time the user enters two consecutive values that are the same. What line of code must be inserted in the blank so that the program will achieve this goal? value = int(input("Enter a value: ") inputStr = input("Enter a value: ") while inputStr != "" : previous = value value = int(inputStr) ____________________ print("Found consecutive values that are the same") inputStr = input("Enter a value: ") 1. if value == inputStr : 2. if value == input : 3. if previous == inputStr :


85.

4. if previous == value : Section 4.5 Common Loop Algorithms Title Complete the while loop for finding consecutive identical values type mc section 4.5 Common Loop Algorithms id testbank-py-1-ch04-87

86. How many times does the while loop execute? s = "abcdEfghI" found = False count = 0 while found == False : if s[count].isupper() : print(letter) found = True count = count + 1 1. 9 times 2. 8 times 3. 5 times 4. 1 time Section 4.5 Common Loop Algorithms Title Finding the first match type mc from testbank-py-1-ch04-65 section 4.5 Common Loop Algorithms id testbank-py-2-ch04-65 87. Consider the following code snippet. What should be placed in the blank to cause a message to be displayed when the user enters the same letter twice in a row? letter = input("Enter the next letter in the alphabet: ") while letter != "": previous = letter letter = input("Enter the next letter") if ________________________ : print("Duplicate input") 1. letter == letter 2. alphabet[0] == letter 3. letter == previous 4. alphabet[0] == previous Section


87. 4.5 Common Loop Algorithms Title Compare adjacent values type mc from testbank-py-1-ch04-66 section 4.5 Common Loop Algorithms id testbank-py-2-ch04-66 88. What is the output of this code snippet if the user enters the numbers 1 2 3 4 -1? total = 0 validNumber = True while validNumber : value = int(input("Please enter a positive value < 100: ")) if value > 0 and value < 100 : total = total + value else : validNumber = False print(total) 1. 15 2. 14 3. 12 4. 10 Section 4.5 Common Loop Algorithms Title What is the output of this code snippet with this user input? type mc from testbank-py-1-ch04-67 section 4.5 Common Loop Algorithms id testbank-py-2-ch04-67 89. What will be printed by the statements below? a = 10 while a > 5 : a=a-2 print(a , end = " ") 1. 10 8 6 2. 10 8 6 4 3. 8 6 4. 8 6 4 Section 4.5 Common Loop Algorithms Title


89. What will be printed by the statements below? type mc from testbank-py-1-ch04-69 section 4.5 Common Loop Algorithms id testbank-py-2-ch04-69 90. What is printed by the following code segment? position = 0 str = input("Enter a string: ") while position < len(str) and str[position] != 'e' : position = position + 1 print(position) 1. The position of the first 'e' in the string or the length of the string if there is no 'e' 2. The position of the last 'e' in the string or the length of the string if there is no 'e' 3. The position of the first character that is not an 'e' in the string or the length of the string if there is no character that is not an 'e' 4. The position of the last character that is not an 'e' in the string or the length of the string if there is no character that is not an 'e' Section 4.5 Common Loop Algorithms Title What does the code segment below print? type mc from testbank-py-1-ch04-78 section 4.5 Common Loop Algorithms id testbank-py-2-ch04-78 91. Which code snippet produces the sum of the first n positive even numbers? Note that 0 is neither positive nor negative. 1. sum = 0 for i in range(1, n) : if i % 2 == 0 : sum = sum + i 2. sum = 0 for i in range(1, n + 1) : sum = sum + i * 2 3. sum = 0 for i in range (0, n) : if i % 2 == 0 : sum = sum + i 4.


91.

4. sum = 0 for i in range(1, n) : sum = sum + i * 2 Section 4.5 Common Loop Algorithms Title Which code snippet produces the sum of the first n even numbers? type mc from testbank-py-1-ch04-82 section 4.5 Common Loop Algorithms id testbank-py-2-ch04-82

92. What is the output of this loop? i=0 found = False while i < 20 and found != True : sum = i * 2 + i * 3 print(sum, end=" ") if sum > 50 : found = True i=i+1 1. 0 5 10 15 20 25 30 35 40 45 50 55 2. 0 3. No output, compilation error 4. 0 5 10 Section 4.5 Common Loop Algorithms Title What is the output of loop with Boolean? type mc from testbank-py-1-ch04-83 section 4.5 Common Loop Algorithms id testbank-py-2-ch04-83 93. Which of the following for loops will run the loop body 5 times? 1. for i in range(0, 4) : 2. for i in range(0, 5) : 3. for i in range(0, 6) : 4. for i in range(1, 5) : Section 4.6 The for Loop Title Which of the following for loops will run the loop body 5 times type mc


93. section 4.6 The for Loop id testbank-py-1-ch04-100 94. Which of the following for loops will run the loop body 5 times? 1. for i in range(4, 0, -1) : 2. for i in range(5, 0, -1) : 3. for i in range(5, 1, -1) : 4. for i in range(6, 0, -1) : Section 4.6 The for Loop Title Which of the following for loops will run the loop body 5 times type mc section 4.6 The for Loop id testbank-py-1-ch04-101 95. What is the value of j at the end of the following code segment? j=0 for i in range(0, 4) : j=j+i 1. 4 2. 6 3. 8 4. 10 Section 4.6 The for Loop Title Trace a for loop type mc section 4.6 The for Loop id testbank-py-1-ch04-102 96. What is the value of j at the end of the following code segment? j=0 for i in range(1, 10) : if j < 10 : j=j+i 1. 0 2. 1 3. 9 4. 10 Section


96.

4.6 The for Loop Title Trace a for loop type mc section 4.6 The for Loop id testbank-py-1-ch04-103

97. Consider the following for loop: for i in range(0, 10) : print(i) Which of the following while loops will generate the same output? 1. i=0 while i < 10 : print(i) i=i+1 2. i=0 while i <= 10 : print(i) i=i+1 3. i=1 while i < 10 : print(i) i=i+1 4. i=1 while i <= 10 : print(i) i=i+1 Section 4.6 The for Loop Title Convert a for loop to a while loop type mc section 4.6 The for Loop id testbank-py-1-ch04-104 98. Consider the following while loop: j = 10 while j >= 5 : print("X")


98.

j=j-1 Which of the following for loops will generate the same output? 1. for j in range(10, 5) : print("X") 2. for j in range(10, 5, -1) : print("X") 3. for j in range(10, -1, -2) : print("X") 4. for j in range(0, 5) : print("X") Section 4.6 The for Loop Title Convert a while loop to a for loop type mc section 4.6 The for Loop id testbank-py-1-ch04-105

99. What is the output of this loop? counter = 1 for i in range(1, 100) : counter = counter + 1 print(counter) 1. 100 2. 49 3. 60 4. 10 Section 4.6 The for Loop Title What is the output of for loop type mc section 4.6 The for Loop id testbank-py-1-ch04-88 100. What does the following code snippet print? fruitName = "banana" for letter in fruitName : print(letter, end = " ") 1. banana 2. b a n a n a


100.

3. Nothing, there is a syntax error 4. Nothing, this is an infinite loop Section 4.6 The for Loop Title What does the for loop print? type mc section 4.6 The for Loop id testbank-py-1-ch04-89

101. What is the output of the following code snippet? for i in range(4) : for j in range(3) : print("*", end="") print() 1. Prints 3 rows of 4 asterisks each 2. Prints 12 rows of asterisks 3. Prints 4 rows of 3 asterisks each 4. Prints 12 rows of 3 asterisks each Section 4.6 The for Loop Title Which is a loop with a problematic condition? type mc section 4.6 The for Loop id testbank-py-1-ch04-90 102. How many times does the loop execute in the following code fragment? for i in range(0, 50, 4) : print(i) 1. 11 2. 12 3. 13 4. 14 Section 4.6 The for Loop Title How many times does for loop execute? type mc section 4.6 The for Loop id testbank-py-1-ch04-91 103. How many times does the following code snippet display "Loop Execution"?


103. for i in range(0, 10) : print("Loop Execution") 1. Ten times. 2. The code snippet does not run because of a compile error. 3. Infinite loop. 4. Only one time. Section 4.6 The for Loop Title How many times does for loop execute? type mc section 4.6 The for Loop id testbank-py-1-ch04-92 104. Which of the following is considered an equivalent while loop for this for loop? s=0 for i in range(1, 10) : s=s+i 1. s= 0 i=0 while i <= 10 : s=s+i i=i+1 2. s= 0 i=1 while i < 10 : s=s+i i=i+1 3. s= 0 i=1 while i <= 10 : s=s+i i=i+1 4. s= 0 i=0 while i < 10 : s=s+i i=i+1 Section 4.6 The for Loop Title Rewrite a for loop using a while loop type mc


104. section 4.6 The for Loop id testbank-py-1-ch04-93 105. Which statement about this code snippet is accurate? years = 50 balance = 10000 targetBalance = 20000 rate = 3 for i in range(1 , years + 1) : if balance >= targetBalance : i = years + 1 else : interest = balance * rate / 100 balance = balance + interest 1. The loop will run 50 times. 2. The loop will never stop. 3. The loop will run at most 50 times, but may stop earlier when balance exceeds or equals targetBalance. 4. There is a compilation error. Section 4.6 The for Loop Title For loop with inside if statement type mc section 4.6 The for Loop id testbank-py-1-ch04-94 106. What values does counter variable i assume when this loop executes? for i in range(20, 2, -6) : print(i, end = ", ") 1. 20, 14, 8, 2 2. 20, 14, 8, 2, -4 3. 20, 14, 8 4. 14, 8, 2 Section 4.6 The for Loop Title Which values does the counter variable assume in for loop? type mc section 4.6 The for Loop id testbank-py-1-ch04-95 107. What is the output of the following code snippet?


107. f1 = 0 f2 = 1 print(f1, " ") print(f2, " ") for i in range(1, 11) : fRes = f1 + f2 print(fRes, end = " ") f1 = f2 f2 = fRes print() 1. 0 1 5 7 9 11 13 15 17 19 55 2. 0 1 1 2 3 5 8 13 21 34 55 89 3. 0 1 4 6 8 10 12 14 16 18 34 4. 0 1 6 7 9 12 14 17 19 21 55 Section 4.6 The for Loop Title What is the output of for loop? type mc section 4.6 The for Loop id testbank-py-1-ch04-97 108. How many iterations does the following loop carry out? for i in range (-10, 11, 2) : 1. infinite 2. None because of compilation error 3. 11 times 4. 20 times Section 4.6 The for loop Title How many times does the loop execute? type mc section 4.6 The for Loop id testbank-py-1-ch04-98 109. How many times does the following loop execute? for d in range(1, 10) : d=d/3 print(d , " ") 1. 10 2. 9 3. 8 4. An infinite number of times Section 4.6 The for Loop


109. Title How many times does the following loop execute? type mc section 4.6 The for Loop id testbank-py-1-ch04-99 110. Consider the following code segment: s = "Hello World!" __________ print(ch) What should be placed in the blank so that the letters of s are printed out with one letter appearing on each line? 1. for ch in range(s) : 2. for ch in s : 3. for range(ch, s) : 4. for s in ch : Section 4.6 The for Loop Title Which loop prints out the letters of a string with each character appearing on its own line? type mc section 4.6 The for Loop id testbank-py-2-ch04-151 111. Which of the following for loops is illegal? 1. for i in range(0, ) : 2. for i in range(0) : 3. for i in range(0, k) : 4. for i in range( , ) : Section 4.6 The for Loop Title Which of the following for loops is illegal? type mc from testbank-py-1-ch04-96 section 4.6 The for Loop id testbank-py-2-ch04-96 112. When does the execution switch from the inner to the outer loop? j=1 for i in range(0, 10) : while(j < 5) :


112.

print("Hello") if j == 2 : j=6 j=j+1 print("switch from inner to outer", i, " ", j) 1. When the value of j becomes 6 2. When the program executes completely 3. When the condition for the outer loop is met 4. When the value of i is incremented Section 4.7 Nested Loops Title When does execution switch from inner to outer loop? type mc section 4.7 Nested Loops id testbank-py-1-ch04-106

113. A loop inside another loop is called: 1. A sentinel loop 2. A nested loop 3. A parallel loop 4. A while loop Section 4.7 Nested Loops Title What is a loop inside another loop? type mc section 4.7 Nested Loops id testbank-py-1-ch04-107 114. What is the first and last value of i to be displayed by the following code snippet? n = 20 for i in range(0, n) : for j in range(0, i) : print(i) 1. 0 and 20 2. 1 and 20 3. 0 and 19 4. 1 and 19 Section 4.7 Nested Loops Title What are first and last values displayed by nested for loop? type mc section 4.7 Nested Loops id


114. testbank-py-1-ch04-108 115. How many times will the output line be printed in the following code snippet? for num2 in range(1, 4) : for num1 in range(0, 3) : print(num2, " ", num1) 1. 3 times 2. 6 times 3. 9 times 4. 12 times Section 4.7 Nested Loops Title How many times will inner for loop execute? type mc section 4.7 Nested Loops id testbank-py-1-ch04-109 116. What is the last output line of the code snippet given below? for i in range(3) : for j in range(5) : if i % 2 == j % 2 : print("*", end="") else : print(" ", end="") print() 1. No output 2. * * * * * * ... infinite loop 3. * * * * 4. * * * Section 4.7 Nested Loops Title What is output of nested loops? type mc section 4.7 Nested Loops id testbank-py-1-ch04-110 117. What is the last output line of the code snippet given below? i=0 j=0 while i < 10 : num = 1


117.

j=i while j > 1 : print(j, end = " ") num = num * 2 j=j- 1 print("***") i=i+1 1. 3 2 *** 2. 9 8 7 6 5 4 3 2 *** 3. 8 7 6 5 4 3 2 *** 4. 2 *** Section 4.7 Nested Loops Title What is output of nested loops? type mc section 4.7 Nested Loops id testbank-py-1-ch04-111

118. Which for loop prints data across each row in the following code snippet? for i in range(1, 4) : for j in range(1, 4) : print("X", end="") print("") 1. The inner for loop 2. The outer for loop 3. Both for loops 4. Another missing for loop Section 4.7 Nested Loops Title Which for loop in snippet represents rows? type mc section 4.7 Nested Loops id testbank-py-1-ch04-113 119. What will be the output of the following code snippet? for i in range(0,7) : for j in range(7, i, -1) : print("*", end="") print("") 1. A rectangle with six rows and seven columns of asterisks. The number of rows increments by one on completion of one iteration of the inner loop. 2. A right triangle with six rows and seven columns of asterisks. The number of columns increments by one on completion of one iteration of the inner loop. 3. A rectangle with seven rows and six columns of asterisks. The number of rows increments by one on


119.

3. completion of one iteration of the inner loop. 4. A right triangle with seven rows and seven columns of asterisks. The number of columns decrements by one on completion of one iteration of the inner loop. Section 4.7 Nested Loops Title What is output of nested for loops? type mc section 4.7 Nested Loops id testbank-py-1-ch04-114

120. In the following code snippet, how many times will "Hello" be printed? for i in range(0, 10) : for j in range(1, 5) : print("Hello") 1. 40 2. 15 3. 39 4. 14 Section 4.7 Nested Loops Title When does execution switch from inner to outer loop in snippet? type mc section 4.7 Nested Loops id testbank-py-1-ch04-115 121. Which of the following code segments is an example of a nested loop? 1. while i < 0 : if x == 10 : 2. while i < 0 : while x == 10 : 3. if i < 0 : while x == 10 : 4. if i < 0 : if x == 10 : Section 4.7 Nested Loops Title Which of the following code segments is an example of a nested loop? type mc section


121. 4.7 Nested Loops id testbank-py-1-ch04-116 122. Consider the following code segment: for i in range(4) : ____________________ print("*", end="") print() It is supposed to generate the following output: *** *** *** *** Which line of code should be placed in the blank to achieve this goal? 1. for j in range(3) : 2. for j in range(4) : 3. for j in range(i) : 4. for j in range(j) : Section 4.7 Nested Loops Title Draw a pattern with nested for loops type mc section 4.7 Nested Loops id testbank-py-1-ch04-117 123. How many copies of the letter A will the following code segment display? for i in range(100) : for j in range(5) : print("A") 1. 400 2. 495 3. 500 4. 605 Section 4.7 Nested Loops Title How many copies of the letter A will be displayed? type mc section 4.7 Nested Loops id testbank-py-1-ch04-118


124. What does the following code snippet display? for n in range(1, 11) : for x in range(1, 11) : print(n*x, end = " ") print() 1. It displays a multiplication table for numbers 1-10 times 1-10 2. Nothing because it has compilation error. 3. It displays a table of all numbers squared from 1-10 4. It displays a multiplication table for numbers 1-11 times 1-11 Section 4.7 Nested loops Title What does for loop with character creation display? type mc from testbank-py-1-ch04-112 section 4.7 Nested Loops id testbank-py-2-ch04-112 125. What type of chart shows the distribution of data across a fixed number of categories? 1. A Grade Chart 2. A Height Chart 3. A Histogram 4. A Plot Section 4.7 Nested Loops Title What type of chart shows the distribution of data across a fixed number of categories? type mc section 4.7 Nested Loops id testbank-py-2-ch04-139 126. Which print statement displays the value of s without starting a new line? 1. print(end="s") 2. print(s, end="") 3. print(s) 4. print("s") Section 4.7 Nested Loops Title Which print statement displays a value without starting a new line? type mc section 4.7 Nested Loops id testbank-py-2-ch04-152


127. What is the output of this code snippet? str = "ABCabc" i=0 while i < len(str) : ch = str[i] if ch.islower() : print(i , " ") else : i=i+1 1. 3 4 5 2. 3 3. 3 3 3 3 3 ... (infinite loop) 4. 0 1 2 Section 4.8 Processing strings Title What is the output of code snippet with while loop? type mc section 4.8 Processing Strings id testbank-py-1-ch04-119 128. Consider the following code segment. It is supposed to count the number of digits (0 - 9) in a string, text. count = 0 for char in text : ____________________ count = count + 1 What line of code should be placed in the blank to achieve this goal? 1. if text[char] >= "0" and text[char] <= "9" : 2. if text[count] >= "0" and text[count] <= "9" : 3. if char >= "0" and char <= "9" : 4. if text >= "0" and char <= "9" : Section 4.8 Processing Strings Title Complete the for loop that counts the number of digits in a string type mc section 4.8 Processing Strings id testbank-py-1-ch04-120 129. Is the code snippet written below legal? s = "1234" for i in range (0, 4) : print(s[i], s[i + 1]) 1. Yes.


129.

2. No; there should not be a colon at the end of line 2. 3. No; for i = 3, s[i + 1] will result in an string index out of range error. 4. No; for i = 0, s[i] will result in an string index out of range error Section 4.8 Processing Strings Title Are there errors in for loop? type mc section 4.8 Processing Strings id testbank-py-1-ch04-121

130. Consider the following code segment: found = False position = 0 text = "Hello World!" while not found and position < len(text) : if text[position] == "o" : found = True else : position = position + 1 What is the value of position at the end of this code segment? 1. 4 2. 5 3. 7 4. 8 Section 4.8 Processing Strings Title Trace a while loop that processes a string type mc section 4.8 Processing Strings id testbank-py-1-ch04-122 131. Consider the following code segment. It is designed to identify the first location within a string, text where two adjacent characters are the same. i=1 found = False while not found and i < len(text) : ____________________ : found = True else : i=i+1 What line of code should be placed in the blank to achieve this goal? 1. if text[i] == text[0] : 2. if text[i] == text[i - 1] :


131.

3. if text[i] == text[i] : 4. if text[i] == text[i + 1] : Section 4.8 Processing Strings Title Complete the loop that finds the location of two adjacent characters that are the same type mc section 4.8 Processing Strings id testbank-py-1-ch04-123

132. What will be the range of the random numbers generated by the following code snippet? from random import randint randomNum = randint(1,50) 1. Between 1 and 49 2. Between 0 and 50 3. Between 0 and 49 4. Between 1 and 50 Section 4.9 Application: Random Numbers and Simulations Title What is range of random numbers generated by snippet? type mc section 4.9 Application: Random Numbers and Simulations id testbank-py-1-ch04-124 133. Which of the following is the correct code snippet for throwing a pair of dice to get a sum of the numbers on two dice between 2 and 12 with the same probability as when throwing actual dice? 1. randint(1, 6) 2. randint(2, 12) 3. randint(1, 6) + randint(1, 6) 4. randint(1, 12) - 2 Section 4.9 Application: Random Numbers and Simulations Title Which code simulates throwing two dice and summing the result? type mc section 4.9 Application: Random Numbers and Simulations id testbank-py-1-ch04-125 134. Suppose that a program asks a user to enter multiple integers, either positive or negative, to do some calculation.


134. The data entry will stop when the user enters a certain value to indicate the end of the data. What value should the code use as the sentinel? 1. 0 2. -1 3. 999 4. An alphabetic character Section 4.9 Application: Processing Sentinel Values Title What should be the sentinel value in this situation? type mc section 4.9 Application: Random Numbers and Simulations id testbank-py-1-ch04-126 135. Which of the following activities can be simulated using a computer? I. Waiting time in a line at a restaurant II. Tossing a coin III. Shuffling cards for a card game 1. I only 2. II only 3. I and II only 4. I, II, and III Section 4.9 Application: Random Numbers and Simulations Title Which activities can be computer simulated? type mc section 4.9 Application: Random Numbers and Simulations id testbank-py-1-ch04-127 136. What range of numbers are generated by the random() function? 1. greater than or equal to zero and less than one 2. greater than zero and less than one 3. greater than zero and less than or equal to one 4. greater than or equal to zero and less than or equal to one Section 4.9 Application: Random Numbers and Simulations Title What is output of the code snippet with random()? type mc section 4.9 Application: Random Numbers and Simulations id testbank-py-1-ch04-128 137. Assume the following variable has been declared and given a value as shown:


137. from random import randint number = randint(0, 27) * 2 + 3 What are the smallest and largest values that may be assigned to number? 1. 3, 55 2. 0, 27 3. 3, 57 4. 0, 26 Section 4.9: Application: Random Numbers and Simulations Title What are the smallest and largest values that may be assigned to number? type mc section 4.9 Application: Random Numbers and Simulations id testbank-py-1-ch04-135 138. Which line of code will generate a random integer from 1 up to and including 10, and store it in x? Assume that the randint function has been imported from the random module. 1. x = randint(0, 10) 2. x = randint(0, 11) 3. x = randint(1, 10) 4. x = randint(1, 11) Section 4.9 Application: Random Numbers and Simulations Title Which line of code will generate a random integer from 1 up to and including 10? type mc section 4.9 Application: Random Numbers and Simulations id testbank-py-1-ch04-137 139. Which line of code will generate a random floating-point number between 0 and 6, and store it in x? Assume that the random function has been imported from the random module. 1. x = random() 2. x = random() * 6 3. x = random(6) 4. x = random(0, 6) Section 4.9 Application: Random Numbers and Simulations Title Which line of code will generate a random floating-point number between 0 and 6? type mc section 4.9 Application: Random Numbers and Simulations id testbank-py-1-ch04-138 140. What does the following code do?


140. from random import randint sum = 0 COUNT = 1000 for i in range(1,COUNT + 1) : sum = sum + randint(0, 100) print(sum / COUNT) 1. It simulates the outcome of throwing a coin. 2. It calculates the average of 1000 random numbers between 0 and 100. 3. It performs a Monte Carlo fluid dynamics simulation. 4. It calculates the average of 1000 random numbers between 1 and 101. Section 4.9 Application: Random Numbers and Simulations Title What does code snippet with random numbers do? type mc from testbank-py-1-ch04-129 section 4.9 Application: Random Numbers and Simulations id testbank-py-2-ch04-129 141. Which of the following statements correctly prints the result of simulating the toss of a pair of coins to get 0 (heads) or 1 (tails) for each coin? 1. print(randint(0, 1)) 2. print(randint(1, 1)) 3. print(randint(0, 2), randint(0, 2)) 4. print(randint(0, 1), randint(0, 1)) Section 4.9 Application: Random Numbers and Simulations Title Which is correct for simulating the toss of a pair of coins? type mc from testbank-py-1-ch04-131 section 4.9 Application: Random Numbers and Simulations id testbank-py-2-ch04-131 142. Which of the following code snippets will generate a random number between 0 and 79? 1. val = int(random() % 80) 2. val = int(random() * 80 - 1) 3.


142.

3. val = int(random() % 79) 4. val = int(random() * 80) Section 4.9 Application: Random Numbers and Simulations Title Which code generates random numbers 0-79? type mc from testbank-py-1-ch04-132 section 4.9 Application: Random Numbers and Simulations id testbank-py-2-ch04-132

143. Which of the following expressions will generate a random integer in the range -20 to 20, inclusive, where each value has an equal chance of being generated? 1. randint (-20, 20) 2. randint(20) - 41 3. randint (-20) + 40 4. randint(41) - 20 Section 4.9: Application: Random Numbers and Simulations Title Which of the following will generate a random integer in the range 20 to 20, inclusive, where each value has an equal chance of being generated? type mc from testbank-py-1-ch04-134 section 4.9 Application: Random Numbers and Simulations id testbank-py-2-ch04-134 144. Assume the following variable has been declared and given a value as shown: from random import random number = random() * 2 + 3 What are the smallest and largest values that may be assigned to number? 1. 3.0, 5.0 (excluding 5.0) 2. 0.0, 6.0 (excluding 6.0) 3. -3.0, 3.0 (including 3.0) 4. 0.0, 3.0 (including 3.0) Section 4.9: Application: Random Numbers and Simulations Title What are the smallest and largest values that may be assigned to number? type mc from testbank-py-1-ch04-136 section 4.9 Application: Random Numbers and Simulations


144. id testbank-py-2-ch04-136 145. Using computer algorithms to manipulate digital images is known as: 1. Computer vision 2. Data compression 3. Digital photography 4. Image processing Section 4.10 Graphics: Digital Image Processing Title Using computer algorithms to manipulate digital images is known as: type mc section 4.10 Graphics: Digital Image Processing id testbank-py-2-ch04-140 146. A digital image is a collection of __________ arranged in a grid of rows and columns. 1. canvases 2. dots 3. elementary elements 4. pixels Section 4.10 Graphics: Digital Image Processing Title A digital image is a collection of __________ arranged in a grid of rows and columns. type mc section 4.10 Graphics: Digital Image Processing id testbank-py-2-ch04-141 147. In an RGB color model, what color is represented by 255, 255, 255? 1. black 2. green 3. white 4. yellow Section 4.10 Graphics: Digital Image Processing Title In an RGB color model, what color is represented by 255, 255, 255? type mc section 4.10 Graphics: Digital Image Processing id testbank-py-2-ch04-142 148. What RGB values represent green? 1. 0, 0, 255 2. 0, 255, 0 3. 128, 128, 128


148.

4. 255, 0, 0 Section 4.10 Graphics: Digital Image Processing Title What RGB values represent green? type mc section 4.10 Graphics: Digital Image Processing id testbank-py-2-ch04-143

149. Which statement loads an image from a file and stores it in a variable? Assume that the ezgraphics module has already been imported using the statement: from ezgraphics import GraphicsImage, GraphicsWindow 1. graphicsImage = Load("mountain.gif") 2. Image("mountain.gif") 3. image = ("mountain.gif") 4. image = GraphicsImage("mountain.gif") Section 4.10 Graphics: Digital Image Processing Title Which statement loads an image from a file and stores it in a variable? type mc section 4.10 Graphics: Digital Image Processing id testbank-py-2-ch04-144 150. What programming language structure is used iterate over all of the individual pixels in an image? 1. A for loop (not nested) 2. A nested for loop 3. A nested if statement 4. A while loop (not nested) Section 4.10 Graphics: Digital Image Processing Title What programming language structure is typically used to process all of the pixels in an image? type mc section 4.10 Graphics: Digital Image Processing id testbank-py-2-ch04-145 151. Which of the following image processing operations changes the grid structure of the image without modifying the pixel values? 1. Converting an image to grayscale 2. Darkening an image 3. Replacing an image with its negative 4. Rotating an image Section 4.10 Graphics: Digital Image Processing


151. Title Which of the following image processing operations changes the grid structure of the image without modifying the pixel values? type mc section 4.10 Graphics: Digital Image Processing id testbank-py-2-ch04-146 152. Which of the following is not a benefit of solving a simpler problem first? 1. It can be difficult to figure out how to get started when solving a large task. 2. Solving the simpler problem first will motivate you to solve the harder problem. 3. Usually, you learn something useful from solving the simpler task. 4. When the simpler problem is solved first it reduces the amount of time the computer needs to compute the answer for the larger problem. Section 4.11 Problem Solving: Solve a Simpler Problem First Title Why is it beneficial to start by solving a simpler problem first? type mc section 4.11 Problem Solving: Solve a Simpler Problem First id testbank-py-2-ch04-147


1. A ___________________________ is a sequence of instructions with a name. 1. variable 2. argument 3. parameter 4. function Section 5.1 Functions as Black Boxes Title What is a sequence of instructions with a name called in Python? type mc section 5.1 Functions as Black Boxes id testbank-py-1-ch05-04 2. Consider the following function call round(3.14159, 3) what is the return value? 1. 3.14159 2. 3.141 3. 3.14 4. 3.1 Section 5.1 Functions as Black Boxes Title What is returned from the round function when it is called? type mc section 5.1 Functions as Black Boxes id testbank-py-1-ch05-06 3. Consider the following function call ceil(3.14159) what is the return value? 1. 3.14159 2. 3.0 3. 4.0 4. 3.1416 Section 5.1 Functions as Black Boxes Title What is returned from the ceil function when it is called? type mc section 5.1 Functions as Black Boxes id testbank-py-1-ch05-07 4. Which of the following is a correct call to Python's round function? 1. x = round("3.14159", 2) 2. x = round("3.14159") 3. x = round(3.14159) 4. x = round(3, 1, 4, 1, 5, 9)


4. Section 5.1 Functions as Black Boxes Title Which of the following is a correct function call for Python's round function? type mc section 5.1 Functions as Black Boxes id testbank-py-1-ch05-08 5. Consider a function named calc. It accepts two integer arguments and returns their sum as an integer. Which of the following statements is a correct invocation of the calc function? 1. total = calc() 2. total = calc(2) 3. total = calc("2", "3") 4. total = calc(2, 3) Section 5.1 Functions as Black Boxes Title Which of the following is a correct function call? type mc section 5.1 Functions as Black Boxes id testbank-py-1-ch05-09 6. The ceil function in the Python standard library math module takes a single value x and returns the smallest integer that is greater than or equal to x. Which of the following is true about ceil(56.75)? 1. The argument is 56.75, and the return value is 57 2. The argument is 56.75, and the return value is 56 3. The argument is 57, and the return value is 56.75 4. The argument is 56, and the return value is 56.75 Section 5.1 Functions as Black Boxes Title Which is true about Math.ceil(56.75)? type mc section 5.1 Functions as Black Boxes id testbank-py-1-ch05-59 7. Which process helps identify the functions that should make up a computer program? 1. black boxing 2. stepwise refinement 3. parameter passing 4. debugging Section 5.1 Functions as Black Boxes Title Which process helps identify the functions that should make up a computer program? type


7. mc from testbank-py-1-ch05-01 section 5.1 Functions as Black Boxes id testbank-py-2-ch05-01 8. The term Black Box is used with functions because 1. Only the implementation matters; the specification is not important. 2. Only the specification matters; the implementation is not important. 3. Only the arguments matter; the return value is not important. 4. Only the return value matters; the arguments are not important. Section 5.1 Functions as Black Boxes Title Why is the term black box used with functions? type mc from testbank-py-1-ch05-02 section 5.1 Functions as Black Boxes id testbank-py-2-ch05-02 9. One advantage of designing functions as black boxes is that 1. many programmers can work on the same project without knowing the internal implementation details of functions. 2. the result that is returned from black-box functions is always the same data type. 3. the implementation of the function is open for everyone to see. 4. there are fewer parameters. Section 5.1 Functions as Black Boxes Title What is one advantage of designing functions as black boxes? type mc from testbank-py-1-ch05-03 section 5.1 Functions as Black Boxes id testbank-py-2-ch05-03 10. What is supplied to a function when it is called? 1. arguments 2. numbers 3. return values 4. variables Section 5.1 Functions as Black Boxes Title What is supplied to a function when it is called? type


10. mc from testbank-py-1-ch05-05 section 5.1 Functions as Black Boxes id testbank-py-2-ch05-05 11. Consider a function named avg, which accepts four numbers and returns their average. Which of the following is a correct call to the function avg? 1. avg(2, 3.14, 3, 5, 6) 2. average = avg(2, 3.14, 4, 5) 3. avg() 4. average = avg("2", "3", "4", "5") Section 5.1 Functions as Black Boxes Title Which statement correctly calls the average function with 4 parameters? type mc from testbank-py-1-ch05-60 section 5.1 Functions as Black Boxes id testbank-py-2-ch05-60 12. Which of the following statements is true about functions in Python? 1. Functions can have only one argument and can return only one return value. 2. Functions can have multiple arguments and can return multiple return values. 3. Functions can have multiple arguments and can return one return value. 4. Functions can have one argument and can return multiple return values. Section 5.1 Functions as Black Boxes Title Which statement is true about functions? type mc from testbank-py-1-ch05-61 section 5.1 Functions as Black Boxes id testbank-py-2-ch05-61 13. What Python statement exits a function and gives the result to the caller? 1. def 2. return 3. send 4. result Section 5.2 Implementing and Testing Functions Title


13. What Python statement exits the function and gives the result to the caller? type mc section 5.2 Implementing and Testing Functions id testbank-py-1-ch05-11 14. Given the code snippet below, what is returned by the function call: mystery(5,3)? def mystery(num1, num2) : result = num1 * num2 return result 1. 8 2. 15 3. 2 4. 0 Section 5.2 Implementing and Testing Functions Title What is the result of the given function call? type mc section 5.2 Implementing and Testing Functions id testbank-py-1-ch05-12 15. Given the code snippet below, what is returned by the function call: mystery(mystery(5, 3), mystery(5, 3))? def mystery(num1, num2) : result = num1 * num2 return result 1. 225 2. 15 3. 30 4. 0 Section 5.2 Implementing and Testing Functions Title What is the result of the given function call? type mc section 5.2 Implementing and Testing Functions id testbank-py-1-ch05-13 16. What is wrong with the following code snippet? mystery(10, 2) def mystery(num1, num2) :


16.

result = num1 ** num2 return result 1. nothing, it will return 20 2. nothing, it will return 100 3. a variable must be used to store the result of the function call 4. the function must be defined before the statement that calls it Section 5.2 Implementing and Testing Functions Title What is wrong with the following code snippet? type mc section 5.2 Implementing and Testing Functions id testbank-py-1-ch05-14

17. Consider the following function: def w(x, y) : z=x+y return z What is the function's name? 1. w 2. x 3. y 4. z Section 5.2 Implementing and Testing Functions Title What is the function's name? type mc section 5.2 Implementing and Testing Functions id testbank-py-1-ch05-15 18. The following function is supposed to compute the area of a triangle and return the area as the function's result. def triangleArea(base, height) : area = base * height / 2 ____________________ What line of code must be placed in the blank to achieve this goal? 1. print area 2. print(area) 3. return area 4. return triangleArea Section 5.2 Implementing and Testing Functions Title What line of code is needed to complete the function for computing the area of a triangle? type mc


18. section 5.2 Implementing and Testing Functions id testbank-py-1-ch05-16 19. Assume that you are writing a function that computes the volume of a box for shipping electrical components. The components vary in shape -- some are long and skinny, while others are cube-like. Different boxes are used for components with different shapes. Which of the following function headers is the best? 1. def boxVolume() : 2. def boxVolume(sideLength) : 3. def boxVolume(a, b, c) : 4. def boxVolume(length, width, height) : Section 5.2 Implementing and Testing Functions Title Select the best header for a function that computes the volume of a box type mc section 5.2 Implementing and Testing Functions id testbank-py-1-ch05-17 20. Consider the following function: def squareArea(sideLength) : return sideLength ** 2 What is the value of squareArea(3)? 1. 2 2. 3 3. 6 4. 9 Section 5.2 Implementing and Testing Functions Title Trace a function call type mc section 5.2 Implementing and Testing Functions id testbank-py-1-ch05-19 21. Consider the following function: def squareArea(sideLength) : return sideLength ** 2 What is the value of squareArea(squareArea(2))? 1. 2 2. 4 3. 8 4. 16 Section


21. 5.2 Implementing and Testing Functions Title Trace a nested function call type mc section 5.2 Implementing and Testing Functions id testbank-py-1-ch05-20 22. Consider the following function: def mystery(a, b) : result = (a - b) * (a + b) return result What is the result of calling mystery(3, 2)? 1. 2 2. 3 3. 4 4. 5 Section 5.2 Implementing and Testing Functions Title Trace a function call type mc section 5.2 Implementing and Testing Functions id testbank-py-1-ch05-21 23. Consider the following function: ## Compute the volume of a cuboid. # @param width the width of the cuboid # @return the volume of the cuboid def volume(width, height, length) : return width * height * length Based on the recommendations in the textbook, what change should be made to improve the comments for this function? 1. The @param line for width should be removed 2. Additional @param lines should be added for height and length 3. The first line should be expanded to describe how the function performs its calculation 4. The @return line should be removed Section 5.2 Implementing and Testing Functions Title How can the function's comment be improved? type mc section 5.2 Implementing and Testing Functions id


23. testbank-py-1-ch05-22 24. You are writing a function that converts from Liters to Gallons. Which function header is the best? 1. def litersToGallons() : 2. def litersToGallons(liters) : 3. def litersToGallons(gallons) : 4. def litersToGallons(liters, gallons) : Section 5.2 Implementing and Testing Functions Title Which function header is best for a function that converts from Liters to Gallons? type mc section 5.2 Implementing and Testing Functions id testbank-py-1-ch05-23 25. Which of the following statements correctly defines a function? 1. def functionName(parameterName1, parameterName2) : 2. def functionName(parameterName1, parameterName2) 3. functionName(parameterName1, parameterName2) : 4. functionName(parameterName1, parameterName2) Section 5.2 Implementing and Testing Functions Title Which of the following statements correctly defines a function? type mc from testbank-py-1-ch05-10 section 5.2 Implementing and Testing Functions id testbank-py-2-ch05-10 26. Consider the following function. def factorial(n) : result = 1 for i in range(1, n + 1) : result = result * i return result What is the parameter variable for this function? 1. factorial 2. i 3. n 4. result Section 5.2 Implementing and Testing Functions Title Identify the parameter variable for a function


26. type mc from testbank-py-1-ch05-18 section 5.2 Implementing and Testing Functions id testbank-py-2-ch05-18 27. Given the following code snippet, what is considered a parameter variable(s)? def mystery(num1, num2) : result = num1 ** num2 return result mystery(10, 2) 1. 10, 2 2. num1, num2 3. result 4. mystery Section 5.3 Parameter Passing Title Identify the parameter variable(s) in the given code snippet type mc section 5.3 Parameter Passing id testbank-py-1-ch05-24 28. Given the following code snippet, what is considered an argument(s)? def mystery(num1, num2) : result = num1 ** num2 return result mystery(10, 2) 1. 10, 2 2. num1, num2 3. result 4. mystery Section 5.3 Parameter Passing Title Identify the argument(s) in the given code snippet type mc section 5.3 Parameter Passing id testbank-py-1-ch05-25 29. Parameter variables should not be changed within the body of a function because


29.

1. This will generate a compiler error 2. This will generate a run-time error 3. It is confusing because it mixes the concept of a parameter with that of a variable 4. It is confusing because parameter variables cannot store values Section 5.3 Parameter Passing Title Why shouldnt parameter variables be changed within the body of a method? type mc section 5.3 Parameter Passing id testbank-py-1-ch05-26

30. Consider the following program: def squareArea(sideLength) : return sideLength ** 2 a = squareArea(4) What are the arguments (actual parameters) in this program? 1. 2 2. 4 3. sideLength 4. squareArea Section 5.3 Parameter Passing Title Identify the arguments in a program type mc section 5.3 Parameter Passing id testbank-py-1-ch05-27 31. Consider the following program: def main() : a=5 print(doubleIt(a)) def doubleIt(x) : return x * 2 main() What output is generated when this program is run? 1. 2 2. 4 3. 5 4. 10 Section 5.3 Parameter Passing


31. Title Trace a main program and function call type mc section 5.3 Parameter Passing id testbank-py-1-ch05-28 32. Consider the following program: def main() : a = 10 print(doTwice(a)) def doTwice(x) : x=x*2 x=x*2 return x main() What output is generated when this program is run? 1. 2 2. 10 3. 20 4. 40 Section 5.3 Parameter Passing Title Trace a main program and function call type mc section 5.3 Parameter Passing id testbank-py-1-ch05-29 33. Consider the following program: def main() : a=2 doubleIt(a) print(a) def doubleIt(x) : x=x*2 main() What output is generated when this program is run? 1. 2 2. 4 3. 8 4. Python reports an error because doubleIt does not contain a return statement


33. Section 5.3 Parameter Passing Title Trace a main program and function call type mc section 5.3 Parameter Passing id testbank-py-1-ch05-30 34. What happens in this code snippet if sideLength = -10? def cubeSurfaceArea(sideLength) : if sideLength >= 0 : return 6 * (sideLength * sideLength) # There are six sides to a cube; surface area of each side is sideLength squared 1. the function returns 600 2. the function returns -600 3. an error occurs and aborts the program 4. a special value of None will be returned from the function Section 5.4 Return Values Title What is wrong with the following code snippet? type mc section 5.4 Return Values id testbank-py-1-ch05-33 35. What is the purpose of this code snippet? def mystery(n) : if n % 2 == 0 : return True else : return False 1. to determine if n is even or odd 2. to find the remainder of n divided by 2 3. to find the value of n divided by 2 4. to determine if n is positive or negative Section 5.4 Return Values Title What is the purpose of this code snippet? type mc section 5.4 Return Values id


35. testbank-py-1-ch05-35 36. When should a computation be turned into a function? 1. when it may not be used 2. when it is only used once 3. when it may be used more than once 4. only if it contains complex mathematically equations Section 5.4 Return Values Title When should a computation be turned into a function? type mc section 5.4 Return Values id testbank-py-1-ch05-36 37. The following program is supposed to display a message indicating if the integer entered by the user is even or odd. What is wrong with the program? num = int(input("Enter an integer: ")) print("The integer is", evenOdd(num)) def evenOdd(n) : if n % 2 == 0 : return "even" return "odd" 1. The function definition must appear before the function is called. 2. The input and print statements must reside in a function named main. 3. The variable num and the parameter variable n must have the same name. 4. An else clause must be added to the if statement. Section 5.4 Return Values Title What is wrong with this program for determining if an integer is even or odd? type mc section 5.4 Return Values id testbank-py-1-ch05-37 38. The following function is supposed to return -1 when x is negative, +1 when x is positive, or 0 if x is zero. What, if anything, is wrong with the function? def plusMinusZero(x) : if x == 0 : return 0 elif x <= 0 : return -1 else x >= 0 :


38.

return 1 1. A return statement must be added at the end of the function 2. Both occurrences of elif must be replaced with if 3. The <= and >= must be replaced with < and > 4. Nothing is wrong with the function Section 5.4 Return Values Title What is wrong with the function? type mc section 5.4 Return Values id testbank-py-1-ch05-38

39. What is wrong with the following function for computing the amount of tax due on a purchase? def taxDue(amount, taxRate) : amount = amount * taxRate def main() : ... total = taxDue(subtotal, TAX_RATE) ... 1. The amount of tax due is not computed correctly 2. The function must print a value 3. The function must return a value 4. The function must take an additional parameter Section 5.4 Return Values Title What is wrong with the function? type mc section 5.4 Return Values id testbank-py-1-ch05-39 40. For a program that reads city names repeatedly from the user and calculates the distance from a company's headquarters, which of the following would be a good design based on stepwise refinement? 1. Write on function that calculates distance randomly 2. Write one function that reads city name 3. Write one function that reads city name and another function that calculates distance 4. Write one function that reads distance and finds city name Section 5.4 Return Values Title For a program that reads city names repeatedly from the user and calculates the distance from a company's headquarters, which of the following would be a good design based on stepwise refinement? type mc section 5.4 Return Values


40. id testbank-py-1-ch05-65 41. Which statement causes the following function to exit immediately? def mystery(num1, num2) : result = num1 ** num2 return result mystery(10, 2) 1. mystery(10,2) 2. result = num1 ** num2 3. return result 4. None of the statements cause the function to exit immediately. Section 5.4 Return Values Title Which statement causes the function to exit immediately? type mc from testbank-py-1-ch05-31 section 5.4 Return Values id testbank-py-2-ch05-31 42. Which statement should be added or modified to remove the possibility of a run-time error in this code snippet? 1: def floorDivision(value1, value2) : 2: return value1 // value2 1. in line 2: change // to / 2. in line 2: change // to % 3. add this statement after line 1: if value2 == 0 : return 0 4. add this statement after line 1: if value2 == 0 : return Section 5.4 Return Values Title Which statement should be added or modified to remove the run-time error in a code snippet? type mc from testbank-py-1-ch05-32 section 5.4 Return Values id testbank-py-2-ch05-32 43. How many return statements can be included in a function? 1. Exactly one 2. One or two 3. One, two or more 4. Zero or more


43. Section 5.4 Return Values Title How many return statements can be included in a function? type mc from testbank-py-1-ch05-34 section 5.4 Return Values id testbank-py-2-ch05-34 44. Given the following code, what is the output? def main() : i = 20 b = mysteriousFunction2(i) print(b + i) def mysteriousFunction1(i) : n=0 while n * n <= i : n += 1 return n - 1 def mysteriousFunction2(a) : b=0 for n in range(a) : i = mysteriousFunction1(n) b=b+i return b main() 1. 50 2. 60 3. 70 4. 80 Section 5.4 Return Values Title What is output by a code segment where one function calls another function? type mc from testbank-py-1-ch05-64 section 5.4 Return Values id testbank-py-2-ch05-64 45. The purpose of a function that does not return a value is 1. to package a repeated task as a function even though the task does not yield a value


45.

2. to insert a temporary implementation of a function that can be refined later 3. to provide a function that can only be included in an assignment statement 4. only used when the function needs to produce output Section 5.5 Functions Without Return Values Title What is the purpose of methods without a return value? type mc section 5.5 Functions Without Return Values id testbank-py-1-ch05-40

46. Consider the following functions: def printIt(x) : print(x) def incrementIt(x) : return x + 1 def decrementIt(x) : return x - 1 def doubleIt(x) : return x * 2 Which of the following function calls is not a reasonable thing to do? 1. print(printIt(5)) 2. print(incrementIt(5)) 3. print(decrementIt(5)) 4. print(doubleIt(5)) Section 5.5 Functions Without Return Values Title Which of the following function calls is unreasonable? type mc section 5.5 Functions Without Return Values id testbank-py-1-ch05-42 47. The following function is supposed to compute and display the value of n-factorial for integers greater than 0. def factorial(n) : result = 1 for i in range(1, n + 1) : result = result * i What is wrong with this function? 1. The indenting is wrong. All of the lines should be indented by the same amount. 2. The calculation is wrong. The result variable will have something other than n-factorial stored in it. 3. The function is missing a line. A print statement must be added at the end of it. 4. The function is missing a line. A return statement must be added at the end of it.


47. Section 5.5 Functions Without Return Values Title What is wrong with the function that is supposed to compute n-factorial? type mc section 5.5 Functions Without Return Values id testbank-py-1-ch05-43 48. Which function call correctly invokes the partial drawShape function listed below and prints a star triangle? def drawShape(type) : length = len(type) if length == 0 : return if type == "triangle" : print(" *") print(" ***") print("*****") drawShape("triangle") 1. drawShape(triangle) 2. drawShape("triangle") 3. drawShape 4. value = drawShape(triangle) Section 5.5 Functions Without Return Values Title Which call correctly invokes a function? type mc from testbank-py-1-ch05-41 section 5.5 Functions Without Return Values id testbank-py-2-ch05-41 49. Consider the following code segment: def f1(): print("A", end="") def f2(): f1() print("B", end="") What output is generated when it runs? 1. A 2. AB 3. B 4. The code segment does not display any output.


49. Section 5.5 Functions Without Return Values Title What is output by the code segment involving functions? type mc section 5.5 Functions Without Return Values id testbank-py-2-ch05-83 50. Consider the following code segment: def f1(): print("a", end="") return "b" def f2(): print("c", end="") d = f1() print(d, end="") print("e", end="") def f3(): print("f", end="") f2() print("g", end="") f3() What output is generated when it runs? 1. fg 2. fceg 3. fcabeg 4. fcadeg Section 5.5 Functions Without Return Values Title What is output by the code segment involving multiple functions? type mc section 5.5 Functions Without Return Values id testbank-py-2-ch05-84 51. The function below randomly generates a number between 1 and 6 to represent a single die. Which implementation listed below allows for other types of die? def die() : return randint(1, 6) 1. def die(low, high) :


51.

1. 2.

return def die(low, high) : return randint(low, high)

3. def die(high) : return randint(0, high) 4. def die(low, high) : return high % low Section 5.6 Problem Solving: Reusable Functions Title Which implementation makes the die function reusable for other types of die? type mc section 5.6 Problem Solving: Reusable Functions id testbank-py-1-ch05-44 52. Given these two separate functions, which implemenation combines them into one reusable function? def sixSidedDie() : return randint(1, 6) def fourSidedDie() : return randint(1, 4)

1. def die(low, high) : return 2. def die(low, high) : return high % low 3. def die(high) : return randint(0, high) 4. def die(low, high) : return randint(low, high) Section 5.6 Problem Solving: Reusable Functions Title Given these two separate functions, which implemenation combines them into one reusable function? type mc section 5.6 Problem Solving: Reusable Functions id testbank-py-1-ch05-45


53. A programmer notices that the following code snippet uses the same algorithm for computing interest earned, but with different variables, in the two places shown below and in several other places in the program. What could be done to improve the program?

RATE1 = 10 RATE2 = 5.5 interest = investment * RATE1 / 100 ... balance = balance + balance * RATE2 / 100 1. Declare the rates as variables, not constants. 2. Define a function that looks up interest rates. 3. Define a function that prompts the user for an amount and a rate of interest, then returns the interest earned. 4. Define a function that computes the interest earned from an amount and a rate of interest. Section 5.6 Problem Solving: Reusable Functions Title What could be done to improve (program that does same calculation with different values)? type mc section 5.6 Problem Solving: Reusable Functions id testbank-py-1-ch05-62 54. What is wrong with the following code? def grade(score) : if score >= 90 : return "A" elif score >= 80 : return "B" elif score >= 70 : return "C" elif score >= 60 : return "D" 1. The name of the parameter variable is illegal 2. The type of the parameter variable is invalid 3. Another return statement needs to be added to the function 4. One of the existing return statements is not correct Section 5.6 Problem Solving: Reusable Functions Title What is wrong with a function that includes multiple return statements? type mc from testbank-py-1-ch05-63 section 5.6 Problem Solving: Reusable Functions id testbank-py-2-ch05-63


55. A stub function is 1. A short function 2. A function that has been unit tested 3. A function that acts as a placeholder and returns a simple value so another function can be tested 4. A function that is broken down into smaller steps through stepwise refinement Section 5.7 Problem Solving: Stepwise Refinement Title What is a stub method? type mc section 5.7 Problem Solving: Stepwise Refinement id testbank-py-1-ch05-49 56. Consider the following function: def numberToGrade(x) : return "X" This function will eventually be rewritten so that it returns the letter grade associated with x grade points. However, at the moment it is incomplete, and always returns the letter X as a placeholder. In its current form, this function is referred to as a: 1. def 2. param 3. refinement 4. stub Section 5.7 Problem Solving: Stepwise Refinement Title Classify the nature of a function type mc section 5.7 Problem Solving: Stepwise Refinement id testbank-py-1-ch05-50 57. For a program that reads three letter grades and calculates an average of those grades, which of the following would be a good design based on stepwise refinement? 1. Write one function that reads three letter grades, converts each letter grade to a number, and calculates the average of the three numbers. 2. Write one function that reads three letter grades, and a second function to convert each letter to a number and calculate the average of the three numbers. 3. Write one function that reads a letter grade and returns the number equivalent, and one function that computes the average of three numbers. 4. Stepwise refinement cannot be applied to this problem. Section 5.7 Problem Solving: Stepwise Refinement Title For a program that reads three letter grades and calculates an average of those grades, which of the following would be a good design based on stepwise refinement? type mc


57. section 5.7 Problem Solving: Stepwise Refinement id testbank-py-1-ch05-66 58. What is stepwise refinement? 1. The process of unit testing 2. The design of pseudocode for black-box functions 3. The process of breaking complex problems down into smaller, manageable steps 4. The use of a temporary implementation of a function that can be improved later Section 5.7 Problem Solving: Stepwise Refinement Title What is stepwise refinement? type mc from testbank-py-1-ch05-46 section 5.7 Problem Solving: Stepwise Refinement id testbank-py-2-ch05-46 59. Why is hand-tracing or manually walking through the execution of a function helpful? 1. It enforces the "black-box" concept of function design 2. It makes unit testing unnecessary 3. It guarantees that the function will compile without errors 4. It is an effective way to understand a function's subtle aspects Section 5.7 Problem Solving: Stepwise Refinement Title Why is hand-tracing or manually walking through the execution of a function helpful? type mc from testbank-py-1-ch05-47 section 5.7 Problem Solving: Stepwise Refinement id testbank-py-2-ch05-47 60. When hand-tracing functions, the values for the parameter variables: 1. Need not be traced because they are never returned 2. Are the same each time the function is invoked 3. May be undetermined or missing when the function executes 4. Are determined by the arguments supplied in the code that invokes the function Section 5.7 Problem Solving: Stepwise Refinement Title What is true about the values for parameter variables when hand-tracing functions? type mc


60. from testbank-py-1-ch05-48 section 5.7 Problem Solving: Stepwise Refinement id testbank-py-2-ch05-48

61. Which of the following is NOT a good practice when developing a computer program? 1. Put as many statements as possible into the main function 2. Document the purpose of each function parameter 3. Decompose a program into many small functions 4. Place code that is used multiple times into a separate function Section 5.7 Problem Solving: Stepwise Refinement Title Which is NOT a good practice when developing a computer program? type mc from testbank-py-1-ch05-57 section 5.7 Problem Solving: Stepwise Refinement id testbank-py-2-ch05-57 62. The tool that allows you to follow the execution of a program and helps you locate errors is known as a(n): 1. Compiler 2. Debugger 3. Interpreter 4. Virtual machine Section 5.7 Problem Solving: Stepwise Refinement Title The tool that allows you to follow the execution of a program and helps you locate errors is known as a(n): type mc section 5.7 Problem Solving: Stepwise Refinement id testbank-py-2-ch05-78 63. The location where the debugger stops executing your program so that you can inspect the values of variables is called a(n): 1. breakpoint 2. function call 3. inspection point 4. step point Section 5.7 Problem Solving: Stepwise Refinement Title The location where the debugger stops executing your program so that you can inspect the values of variables is called a(n):


63. type mc section 5.7 Problem Solving: Stepwise Refinement id testbank-py-2-ch05-79 64. Which debugging command allows you to quickly run an entire function instead of examining its body a line at a time? 1. Step into 2. Step over 3. Step point 4. Step quickly Section 5.7 Problem Solving: Stepwise Refinement Title Which debugging command allows you to quickly run an entire function instead of examining its body a line at a time? type mc section 5.7 Problem Solving: Stepwise Refinement id testbank-py-2-ch05-80 65. Given the following code snippet, which statement correctly allows the function to update the global variable total?

1. total = 0 2. def main() : 3. avg = 0 4. for i in range(6) : 5. iSquared = i * i 6. total = total + iSquared 7. avg = total / i 8. print(total) 9. print(avg) 1. add the keyword global to line 1 2. line 1 already allows the total variable to be updated 3. move line 1 inside the function definition 4. add the statement global total after line 2 Section 5.8 Variable Scope Title How can global variables be updated in a function definition? type mc section 5.8 Variable Scope id testbank-py-1-ch05-53


66. What is the output from the following Python program?

def myFun(perfect) : perfect = 0 return ((perfect - 1) * (perfect - 1)) def main() : for i in range(4) : print(myFun(i), end = " ") main() 1. 1 1 1 1 2. -1 0 1 4 3. 0 0 0 0 4. 1 0 1 4 Section 5.8 Variable Scope Title What is the output from the code snippet? type mc section 5.8 Variable Scope id testbank-py-1-ch05-54

67. Which of the following statements about variables is true? 1. A variable is visible from the point at which it is defined until the end of the program. 2. You should use global variables whenever possible.. 3. The same name can be used for two different variables in a single method. 4. The same variable name can be used in two different methods. Section 5.8 Variable Scope Title Which statement about variables is true? type mc section 5.8 Variable Scope id testbank-py-1-ch05-58 68. In the code snippet below, which variables are considered global variables: a=0 b=5 def main() : global a, b fun1()


68.

fun2() def fun1() : i=0 b=0 def fun2() : a=b+1 main() 1. a, b, i 2. fun1, fun2 3. a, b 4. i Section 5.8 Variable Scope Title In the given code snippet, identify the global variables type mc section 5.8 Variable Scope id testbank-py-1-ch05-73

69. The variable name perfect in the function myFun in the code snippet below is used as both a parameter variable and a variable in the body of the function. Which statement about this situation is true?

def myFun(perfect) perfect = 0 return ((perfect - 1) * (perfect - 1)) 1. This multiple use of the same variable perfect will not compile because the scopes overlap 2. While this is legal and will compile in Python, it is confusing 3. Because the scopes of these variables do not overlap, there is no problem 4. This situation rarely occurs and the compiler always issues a warning Section 5.8 Variable Scope Title Which statement about variable declarations within functions is true? type mc from testbank-py-1-ch05-51 section 5.8 Variable Scope id testbank-py-2-ch05-51 70. Consider the following code segment:


70. def main() : avg = 0 total = 0 for i in range(6) : iSquared = i * i total = total + iSquared avg = total / i print(total) print(avg) Which of the following answers lists all of the local variables in this code segment? 1. avg, total, i, iSquared 2. i, iSquared 3. avg, total 4. i Section 5.8 Variable Scope Title Which variables are considered local variables? type mc from testbank-py-1-ch05-52 section 5.8 Variable Scope id testbank-py-2-ch05-52 71. What is the output from the following Python program?

def main() : a = 10 r = cubeVolume() print(r) def cubeVolume() : return a ** 3 main() 1. 10 2. 30 3. 1000 4. Nothing, there is an error. Section 5.8 Variable Scope Title What is the output from a code snippet involving multiple functions? type mc from testbank-py-1-ch05-55


71. section 5.8 Variable Scope id testbank-py-2-ch05-55 72. What term is used to describe the portion of a program in which a variable can be accessed? 1. locale 2. region 3. scope 4. volume Section 5.8 Variable Scope Title What term is used to describe the portion of a program in which a variable can be accessed? type mc section 5.8 Variable Scope id testbank-py-2-ch05-85 73. What is the output of the following code snippet? def main() : print(blackBox(4)) def blackBox(a) : if a <= 0 : val = 1 else : val = a + blackBox(a - 2) return val main() 1. 4 2. 2 3. 1 4. 7 Section 5.9 Recursive Functions (Optional) Title What is output of snippet (with recursive function)? type mc section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-1-ch05-67 74. Based on the code snippet, which of the following statements is correct?


74. def main() : reoccur(1) def reoccur(a) : print(a) reoccur(a + 1) main() 1. The code snippet gives a compilation error as the reoccur function cannot call itself. 2. The code snippet executes and infinitely recurses, displaying 1, 2, 3, 4, and so on. 3. The code snippet executes and displays 1. 4. The code snippet executes and does not produce any output. Section 5.9 Recursive Functions (Optional) Title What is output of snippet (with recursive function)? type mc section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-1-ch05-69 75. What is the output if the function call is testMyVal(6) in the following code snippet?

def testMyVal(a) : if a > 0 : testMyVal(a - 2) print(a, end = " ") 1. 0 2 4 6 2. 0 0 0 0 3. The code snippet executes and infinitely recurses, displaying 2, 4, 5, and so on. 4. 6 4 2 0 Section 5.9 Recursive Functions (Optional) Title What is output of snippet (with recursive function)? type mc section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-1-ch05-70 76. Which of the following code snippets returns the factorial of a given number? (Hint: Factorial of 5 = 5! = 1 * 2 * 3 * 4 * 5 = 120) 1. def factorial(num) : return num * factorial(num - 1) 2. def factorial(num) :


76.

2.

if(num == 1) : return 1 else : return num * factorial(num)

3. def factorial(num) : if(num == 1) : return 1 else : print(num * factorial(num - 1)) 4. def factorial(num) : if(num == 1) : return 1 else : return num * factorial(num - 1) Section 5.9 Recursive Functions (Optional) Title Which snippet calculates the factorial of a given number? type mc section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-1-ch05-71 77. Consider this recursive function: def mystery(x) : if x <= 0 : return 0 else : return x + mystery(x - 1) What is mystery(5)? 1. 15 2. 10 3. 0 4. 4 Section 5.9 Recursive Functions (Optional) Title What is output of snippet (with recursive function)? type mc section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-1-ch05-72 78. Consider the following program: def main() :


78.

print(factorial(n))

# Line 1

def factorial(n) : # Line 2 result = 1 for i in range(1, n + 1) : result = result * i # Line 3 return i main() Which of the following lines is a recursive function call? 1. Line 1 2. Line 2 3. Line 3 4. There are no recursive function calls in the program Section 5.9 Recursive Functions (Optional) Title Which line contains a recursive function call? type mc section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-1-ch05-74 79. Consider the following program: def main() : print(factorial(n))

# Line 1

def factorial(n) : # Line 2 if n <= 1 : return 1 return n * factorial(n - 1) # Line 3 main() What line is the recursive call on? 1. Line 1 2. Line 2 3. Line 3 4. There are no recursive function calls in the program Section 5.9 Recursive Functions (Optional) Title Which line contains a recursive function call? type mc section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-1-ch05-75 80. What output is generated when the following program runs?


80. def main() : x = mystery(5) print(x) def mystery(n) : if n == 1 : return 1 return 2 * mystery(n - 1) main() 1. 4 2. 8 3. 16 4. 32 Section 5.9 Recursive Functions (Optional) Title Trace a recursive function type mc section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-1-ch05-76 81. What output is generated when the following program runs? def main() : x = mystery(9, 12) print(x) def mystery(a, b) : if b == 0 : return a else : return mystery(b, a % b) main() 1. 3 2. 6 3. 9 4. 12 Section 5.9 Recursive Functions (Optional) Title Trace a recursive function type mc section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-1-ch05-77


82. Which line of code in the Python program below is the recursive invocation of function myFun?

1: def main() : 2: for i in range(4) : 3: print(myFun(i), end = " ") 4: def myFun(perfect) : 5: perfect = 0 6: return ((perfect - 1) * (perfect - 1)) 7: main() 1. Line 1 2. Line 3 3. Line 6 4. There is no recursive invocation in this code segment Section 5.9 Recursive Functions (Optional) Title Which line of code is the recursive invocation? type mc from testbank-py-1-ch05-56 section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-2-ch05-56 83. What is the output of the following code snippet? def main() : print("fun(2) =", fun(2)) def fun(a) : returnValue = 0 if a > 5 : returnValue = a else : returnValue = fun(2 * a) return returnValue main() 1. fun(2) = 4 2. fun(2) = 8 3. fun(2) = 16 4. fun(2) = 32 Section 5.9 Recursive Functions (Optional) Title What is output by a code segment that includes recursion? type mc from


83. testbank-py-1-ch05-68 section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-2-ch05-68 84. What term is used to refer to a collection of functions and classes organized into one or more user-defined modules? 1. function argument 2. hardware toolbox 3. software toolkit 4. standard library Section 5.9 Graphics: Building an Image Processing Toolkit Title What term is used to refer to a collection of functions and classes organized into one or more user-defined modules? type mc section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-2-ch05-81 85. Which function should not be included in a software toolkit for managing student enrollment in courses? 1. computeNegativeImage 2. enrollStudentInCourse 3. getGradePointAverage 4. setFinalExamMark Section 5.9 Graphics: Building an Image Processing Toolkit Title Which function should not be included in a software toolkit for managing student enrollment? type mc section 5.9 Graphics: Building an Image Processing Toolkit id testbank-py-2-ch05-82


1. What is a list in Python? 1. a series of numbers 2. a container that stores a collection of elements that are arranged in a linear or sequential order 3. a series of strings 4. a series of references or locations of data in memory Section 6.1 Basic Properties of Lists Title What is a list in Python? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-01 2. Given the following list, what value is at index 5? values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 1. 5 2. 6 3. 7 4. 4 Section 6.1 Basic Properties of Lists Title Given the following list, what value is at index 5? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-02 3. Consider the following line of code:

somelist = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", " Which one of the following options is a valid line of code for displaying the element at the twenty-second position in the list? 1. somelist(21) 2. somelist[21] 3. print(somelist(21)) 4. print(somelist[21]) Section 6.1 Basic Properties of Lists Title Which one of the following options is a valid line of code for displaying the element at the twenty-second position in the list? type mc section


3. 6.1 Basic Properties of Lists id testbank-py-1-ch06-03

4. Given the list below, what are the upper and lower bounds?

somelist = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", " 1. 1, 26 2. 0, 25 3. 1, 25 4. 0, 26 Section 6.1 Basic Properties of Lists Title What are the upper and lower bounds of a given list? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-04 5. What is the valid range of index values for a list? 1. at least zero and less than the number of elements in the list 2. at least one and less than the number of elements in the list 3. at least zero and less than or equal to the number of elements in the list 4. at least one and less than or equal to the number of elements in the list Section 6.1 Basic Properties of Lists Title What is the valid range of index values for a list? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-05 6. What is printed after executing the following code snippet?

somelist = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", " for i in range(len(somelist)) : print(somelist[i], end = "") 1. abcdefghijklmnopqrstuvwxyz 2. a b c d e f g h i j k l m n o p q r s t u v w x y z 3. bcdefghijklmnopqrstuvwxyz 4. abcdefghijklmnopqrstuvwxy


6. Section 6.1 Basic Properties of Lists Title What is printed after executing the following code snippet? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-06

7. What is printed after executing the following code snippet?

somelist = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", " for i in range(0, len(somelist), 2) : print(somelist[i], end = "") 1. abcdefghijklmnopqrstuvwxyz 2. a b c d e f g h i j k l m n o p q r s t u v w x y z 3. acegikmoqsuwy 4. bdfhjlnprtvxz Section 6.1 Basic Properties of Lists Title What is printed after executing the following code snippet? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-07 8. Which statement correctly creates a list that contains four elements? 1. values[4] 2. values = [4] 3. values = [1, 2, 3, 4] 4. value[4] = [1, 2, 3, 4] Section 6.1 Basic Properties of Lists Title Which statement correctly creates a list that contains four elements? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-08 9. What is the difference between a list and a string?


9.

1. lists are sequences but strings are not and therefore you cannot access a string element using [] 2. lists are immutable, but strings can be changed 3. lists can hold values of any type, whereas strings are only sequences of characters 4. elements in a list can be accessed using an integer as the index value, but strings can use any numeric data type for the index Section 6.1 Basic Properties of Lists Title What is the difference between a list and a string? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-10

10. Which statement gets the length of the list values? 1. numValues = length(values) 2. numValues = len(values) 3. numValues = size(values) 4. numValues = values.length Section 6.1 Basic Properties of Lists Title Which statement gets the length of the list values? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-11 11. Given a list values that contains the first ten prime numbers, which statement prints the index and value of each element in the list? 1. for i in range(11) : print(i, values[i]) 2. for i in range(10) : print(i, values[i]) 3. for i in range(1, 10) : print(i, values[i]) 4. for i in range(1, 11) : print(i, values[i]) Section 6.1 Basic Properties of Lists Title Given a list values that contains the first ten prime numbers, which statement prints each element in the


11.

list? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-12

12. Given a list values that contains the first ten prime numbers, which statement does NOT print each element in the list? 1. for i in range(len(values)) : print(values[i]) 2. for element in values : print(element) 3. for i in range(0, len(values)) : print(values[i]) 4. for i in range(1, len(values)) : print(values[i]) Section 6.1 Basic Properties of Lists Title Given a list values that contains the first ten prime numbers, which statement does NOT print each element in the list? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-13 13. For the list: prices = [10.00, 15.50, 13.25, 20.15], what value is contained in prices? 1. the location of the list 2. the first value in the list 3. the size of the list 4. the number of elements in the list Section 6.1 Basic Properties of Lists Title For the list: prices = [10.00, 15.50, 13.25, 20.15], what value is contained in prices? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-14 14. Given the following code snippet, which statement correctly creates an alias for the list prices? prices = [10.00, 15.50, 13.25, 20.15]


14.

1. values[10] = prices 2. values = prices 3. for element in prices : values = element 4. values[10] = prices[10] Section 6.1 Basic Properties of Lists Title Given the following code snippet, which statement correctly creates an alias for the list prices? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-15

15. Which of the following statements stores the numbers 1 through 5 into a list named values? 1. values = 1, 2, 3, 4, 5 2. values = (1, 2, 3, 4, 5) 3. values = [1, 2, 3, 4, 5] 4. values = {1, 2, 3, 4, 5} Section 6.1 Basic Properties of Lists Title Which statement stores the numbers 1 through 5 into a list? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-17 16. Consider the following code segment: values = [4, 12, 0, 1, 5] print(values[1]) What is displayed when it runs? 1. 0 2. 1 3. 4 4. 12 Section 6.1 Basic Properties of Lists Title Trace code that accesses a list element type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-18 17. Consider the following list:


17. values = [12, 4, 8, 16, 24] Which statement displays the last element in the list? 1. print(values[0]) 2. print(values[4]) 3. print(values[5]) 4. print(values[24]) Section 6.1 Basic Properties of Lists Title Which statement displays the last element in the list? type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-19 18. Consider the following code segment: values = [1, 2, 3, 4, 5] moreValues = values moreValues[3] = 6 print(values) What is displayed when it runs? 1. [1, 2, 3, 4, 5] 2. [1, 2, 6, 4, 5] 3. [1, 2, 3, 6, 5] 4. [1, 2, 3, 4, 5, 6] Section 6.1 Basic Properties of Lists Title Trace code involving two lists type mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-20 19. What will happen when the following code segment is executed? values = [1.618, 2.71, 3.14] print(values[3]) 1. Python will display an out-of-range error 2. Python won't display anything 3. Python will display 3 4. Python will display 3.14 Section 6.1 Basic Properties of Lists Title What will happen when a code segment involving lists is executed? type


19. mc section 6.1 Basic Properties of Lists id testbank-py-1-ch06-21 20. Consider the following code snippet. What will be stored in the list prices after this code executes? prices = [10.00, 15.50, 13.50, 20.15] for i in range(len(prices)) : prices[i] = prices[i] * 1.06 1. [10.00, 15.50, 13.50, 20.15] 2. [10.60, 16.43, 14.31, 21.36] 3. [1.06, 1.06, 1.06, 1.06] 4. [0.0, 0.0, 0.0, 0.0] Section 6.1 Basic Properties of Lists Title What is stored in the list after the code executes? type mc from testbank-py-1-ch06-16 section 6.1 Basic Properties of Lists id testbank-py-2-ch06-16 21. Given the list values = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], which statement fills the list with these numbers: 1 2 3 4 5 6 7 8 9 10 1. for i in range(10) : values[i] = i 2. for i in range(10) : values[i] = i + 1 3. for i in range(0, 10) : values[i] = i 4. for i in range(1, 10) : values[i] = i Section 6.1 Basic Properties of Lists Title Which statement stores the numbers 1 through 10 into an existing list? type mc from testbank-py-1-ch06-74


21.

section 6.1 Basic Properties of Lists id testbank-py-2-ch06-74

22. Which statement creates a new, empty list? 1. data = 0 2. data = . 3. data = () 4. data = [] Section 6.1 Basic Properties of Lists Title Which statement creates a new, empty list? type mc section 6.1 Basic Properties of Lists id testbank-py-2-ch06-87 23. Which statement correctly identifies the error in this code snippet?

scores = [80, 85, 60.5, 95, 70] print(scores[5]) 1. DataTypeError: cannot mix integer and floating point numbers 2. There is no error. The code runs and prints 70. 3. NameError: name 'scores' is not defined 4. IndexError: list index out of range Section 6.1 Basic Properties of Lists Title Which statement correctly identifies the error in this code snippet? type mc from testbank-py-1-ch06-09 section 6.1 Basic Properties of Lists id testbank-py-2-ch06-09 24. Given the following code snippet, which statement correctly copies the contents of the list prices? prices = [10.00, 15.50, 13.25, 20.15] 1. values[10] = prices 2. values = list(prices) 3.


24.

3. for element in prices : values = element 4. values[10] = prices[10] Section 6.2 List Operations Title Given the following code snippet, which statement correctly copies the contents of the list prices? type mc section 6.2 List Operations id testbank-py-1-ch06-22

25. Given the definition of a list: names = [] which statement correctly adds "Harry" to the list? 1. names[] = "Harry" 2. names[len(names) + 1] = "Harry" 3. names.add("Harry") 4. names.append("Harry") Section 6.2 List Operations Title Given the definition of a list: names = [] which statement correctly adds "Harry" to the list? type mc section 6.2 List Operations id testbank-py-1-ch06-23 26. Which of the following statements looks for the name 'Bob' in the list names? 1. if "Bob" found in names : print("found Bob") 2. if "Bob" in names : print("found Bob") 3. if names contains "Bob" : print("found Bob") 4. if names.indexOf("Bob") >= 0 : print("found Bob") Section 6.2 List Operations Title Which of the following statements looks for the name 'Bob' in the list names? type mc section 6.2 List Operations


26.

id testbank-py-1-ch06-26

27. Given the following code snippet, what is the value of the variable indexValue? states = ["Alaska", "Hawaii", "Florida", "Maine", "Ohio", "Florida"] indexValue = states.index("Hawaii") 1. 2 2. 1 3. -1 4. 0 Section 6.2 List Operations Title Given the following code snippet, what is the value of the variable indexValue? type mc section 6.2 List Operations id testbank-py-1-ch06-28 28. Given the following code snippet, what is the value of the variable removedValue? states = ["Alaska", "Hawaii", "Florida", "Maine", "Ohio", "Florida"] removedValue = states.pop(3) 1. 3 2. Maine 3. Florida 4. Hawaii Section 6.2 List Operations Title Given the following code snippet, what is the value of the variable removedValue? type mc section 6.2 List Operations id testbank-py-1-ch06-29 29. Given the following code snippet, what is the content of the list states? states = ["Alaska", "Hawaii", "Florida", "Maine", "Ohio", "Florida"] states.pop() 1. ["Alaska", "Hawaii", "Florida", "Maine", "Ohio", "Florida"] 2. ["Hawaii", "Florida", "Maine", "Ohio", "Florida"] 3. ["Alaska", "Hawaii", "Florida", "Maine", "Ohio"] 4. [] Section


29.

6.2 List Operations Title Given the following code snippet, what are the contents of list states? type mc section 6.2 List Operations id testbank-py-1-ch06-30

30. Given the following code snippet, what are the contents of the list states? states = ["Alaska", "Hawaii", "Florida", "Maine", "Ohio", "Florida"] states.remove("Florida") 1. ["Alaska", "Hawaii", "Maine", "Ohio", "Florida"] 2. ["Hawaii", "Hawaii", "Maine", "Ohio"] 3. ["Alaska", "Hawaii", "Florida", "Maine", "Ohio"] 4. ["Alaska", "Hawaii", "Florida", "Maine", "Ohio", "Florida"] Section 6.2 List Operations Title Given the following code snippet, what are the contents of the list states? type mc section 6.2 List Operations id testbank-py-1-ch06-31 31. Given the following code snippet, what are the contents of the list fullNames? firstNames = ["Joe", "Jim", "Betsy", "Shelly"] lastNames = states = ["Jones", "Patel", "Hicks", "Fisher"] fullNames = firstNames + lastNames 1. ["Joe", "Jones", "Jim", "Patel", "Betsy", "Hicks", "Shelly", "Fisher"] 2. ["Joe Jones", "Jim Patel", "Betsy Hicks", "Shelly Fisher"] 3. ["Joe", "Jim", "Betsy", "Shelly", "Jones", "Patel", "Hicks", "Fisher"] 4. ["Joe", "Jim", "Betsy", "Shelly"] Section 6.2 List Operations Title Given the following code snippet, what are the contents of the list fullNames? type mc section 6.2 List Operations id testbank-py-1-ch06-33 32. Given the following code snippet, what are the contents of the list names? firstNames = ["Joe", "Jim", "Betsy", "Shelly"]


32. names = firstNames * 2 1. ["Joe", "Jim", "Betsy", "Shelly", "Joe", "Jim", "Betsy", "Shelly"] 2. ["Joe", "Joe", "Jim", "Jim", "Betsy", "Betsy", "Shelly", "Shelly"] 3. ["Joe", "Jim", "Betsy", "Shelly", 2] 4. ["Joe", "Jim", "Betsy", "Shelly"] Section 6.2 List Operations Title Given the following code snippet, what are the contents of the list names? type mc section 6.2 List Operations id testbank-py-1-ch06-34 33. Which statement(s) allows us to initialize the list numbers with 10 elements all set to zero? 1. numbers = [0] 2. numbers[10] = 0 3. numbers = [0] * 10 4. numbers[10] = [0] * 10 Section 6.2 List Operations Title Which statement(s) allows us to initialize the list numbers with 10 elements all set to zero? type mc section 6.2 List Operations id testbank-py-1-ch06-35 34. Given the following code snippet, what is printed? nums = [1, 2, 3, 4, 5] nums2 = [5, 4, 3, 2, 1] if nums == nums2 : print("lists are equal") else : print("lists are not equal") 1. lists are equal 2. lists are not equal 3. lists are equallists are not equal 4. an error occurs and nothing is printed Section 6.2 List Operations Title Given the following code snippet, what is printed? type mc section 6.2 List Operations id


34. testbank-py-1-ch06-36 35. What is the resulting value of this code snippet? sum([1, 2, 3, 4, 5]) 1. 121 2. 16 3. 15 4. 14 Section 6.2 List Operations Title What is the resulting value of this code snippet? type mc section 6.2 List Operations id testbank-py-1-ch06-38 36. What is the resulting value of this code snippet? max(["Roland", "Kent", "Ravi", "Amy"]) 1. Invalid Type Error 2. "Roland" 3. "Amy" 4. "Ravi" Section 6.2 List Operations Title What is the resulting value of this code snippet? type mc section 6.2 List Operations id testbank-py-1-ch06-39 37. What is the resulting content of the list after this code snippet? min(["Roland", "Kent", "Ravi", "Amy"]) 1. Invalid Type Error 2. "Roland" 3. "Amy" 4. "Ravi" Section 6.2 List Operations Title What is the resulting content of this code snippet? type mc section


37. 6.2 List Operations id testbank-py-1-ch06-40 38. What is the resulting content of the list values after this code snippet? values = [1991, 1875, 1980, 1965, 2000] values.sort() 1. [1991, 1875, 1980, 1965, 2000] 2. [2000, 1991, 1980, 1965, 1875] 3. [2000, 1991, 1875, 1980, 1965] 4. [1875, 1965, 1980, 1991, 2000] Section 6.2 List Operations Title What is the resulting contents of the list values after this code snippet? type mc section 6.2 List Operations id testbank-py-1-ch06-41 39. What is the resulting content of the list letters after this code snippet? letters = list("abcdefg") 1. letters contains a list with the contents: ["a", "b", "c", "d", "e", "f", "g"] 2. letters contains a list with the contents: ["abcdefg"] 3. Invalid Type Error 4. letters contains a list with the contents: ("abcdefg") Section 6.2 List Operations Title What is the resulting value of this code snippet? type mc section 6.2 List Operations id testbank-py-1-ch06-42 40. Which of the following code segments will result in values containing the list ["Hydrogen", "Helium", "Lithium"]? 1. values = [] values.append("Lithium") values.append("Helium") values.append("Hydrogen") 2. values = [] values.append("Hydrogen")


40.

2. values.append("Helium") values.append("Lithium") 3. values = ["Hydrogen"] values.append("Helium", "Lithium") 4. values = [] values.append(["Hydrogen", "Helium", "Lithium"]) Section 6.2 List Operations Title Use append to construct the desired list type mc section 6.2 List Operations id testbank-py-1-ch06-43

41. Which of the following code segments will result in values containing the list ["X", "Y", "Z"]? 1. values = "X" values.insert(1, Y) values.insert(1, Z) 2. values = ["X"] values.insert(1, "Y") values.insert(1, "Z") 3. values = ["X"] values.insert(1, "Y") values.insert(2, "Z") 4. values = [] values.insert(0, "X") values.insert(0, "Y") values.insert(0, "Z") Section 6.2 List Operations Title Use insert to construct the desired list type mc section 6.2 List Operations id testbank-py-1-ch06-44 42. What is stored in pos when the following code segment executes? values = ["J", "Q", "X", "Z"] pos = values.find("Y")


42.

1. -1 2. 0 3. 4 4. No value is stored because a runtime exception occurs Section 6.2 List Operations Title Trace code that finds an element in a list type mc section 6.2 List Operations id testbank-py-1-ch06-45

43. What is in grades after the follow code segment executes? grades = ["A", "B+", "C", "C+", "C", "B-"] grades.remove("C") 1. ["A", "B+", "B-"] 2. ["A", "B+", "C+", "B-"] 3. ["A", "B+", "C+", "C", "B-"] 4. ["A", "B+", "", "C+", "C", "B-"] Section 6.2 List Operations Title Trace code that removes an element form a list type mc section 6.2 List Operations id testbank-py-1-ch06-46 44. What is displayed by the following code segment? values = ["Q", "W", "E", "R", "T", "Y"] print(min(values)) 1. Q 2. W 3. E 4. R Section 6.2 List Operations Title Trace code that calls the min function type mc section 6.2 List Operations id testbank-py-1-ch06-48 45. What is output by the following code segment?


45. x = list("QWERTY") print(x) 1. Q 2. ["Q"] 3. ["QWERTY"] 4. ["Q", "W", "E", "R", "T", "Y"] Section 6.2 List Operations Title Trace code that calls the list function type mc section 6.2 List Operations id testbank-py-1-ch06-49 46. What is output by the following code segment? values = ["Q", "W", "E", "R", "T", "Y"] print(values[2 : 4]) 1. ["W", "E"] 2. ["W", "E", "R"] 3. ["E", "R"] 4. ["E", "R", "T"] Section 6.2 List Operations Title Trace code that uses a slice type mc section 6.2 List Operations id testbank-py-1-ch06-50 47. What is the value of names after the following code segment has run? names = [] names.append("Amy") names.append("Bob") names.append("Peg") names[0] = "Cy" names.insert(0, "Ravi") 1. ['Ravi', 'Cy', 'Amy', 'Bob', 'Peg'] 2. ['Cy', 'Amy', 'Bob', 'Peg'] 3. ['Ravi', 'Cy', 'Bob', 'Peg'] 4. ['Ravi', 'Amy', 'Bob', 'Peg'] Section 6.2 List Operations Title What is stored in a list after performing append and insert operations?


47.

type mc from testbank-py-1-ch06-24 section 6.2 List Operations id testbank-py-2-ch06-24

48. What is the value of names after the following code segment has run? names = [] names.append("Amy") names.append("Bob") names.append("Peg") names[0] = "Cy" names.insert(0, "Ravi") names.insert(4, "Savannah") 1. ['Ravi', 'Cy', 'Bob', 'Peg', 'Savannah'] 2. ['Ravi', 'Cy', 'Amy', 'Bob', 'Peg', 'Savannah'] 3. ['Cy', 'Amy', 'Bob', 'Peg', 'Savannah'] 4. IndexError: list assignment index out of range Section 6.2 List Operations Title What is stored in a list after performing several append and insert operations? type mc from testbank-py-1-ch06-25 section 6.2 List Operations id testbank-py-2-ch06-25 49. What is the value of the variable indexValue after the following code snippet runs? states = ["Alaska", "Hawaii", "Florida", "Maine", "Ohio", "Florida"] indexValue = states.index("Pennsylvania") 1. -1 2. 0 3. 6 4. A ValueError exception is raised. Section 6.2 List Operations Title What value is computed by a code segment that invokes the index method? type mc from testbank-py-1-ch06-27 section


49.

6.2 List Operations id testbank-py-2-ch06-27

50. What is the value of states after the following code segment has run? element = "Ohio" states = ["Alaska", "Hawaii", "Florida", "Maine", "Ohio", "Florida"] states.remove(element) 1. ["Alaska", "Hawaii", "Florida", "Maine"] 2. [] 3. ["Alaska", "Hawaii", "Florida", "Maine", "Ohio", "Florida"] 4. ["Alaska", "Hawaii", "Florida", "Maine", "Florida"] Section 6.2 List Operations Title What value is calculated by a code segment that invokes the remove method? type mc from testbank-py-1-ch06-32 section 6.2 List Operations id testbank-py-2-ch06-32 51. Which statement correctly compares these two lists for equality? nums = [1, 2, 3, 4, 5] nums2 = [5, 4, 3, 2, 1] 1. if nums == nums2 2. if nums equals nums2 3. if nums in nums2 4. None of the above. A loop is needed to compare each item individually. Section 6.2 List Operations Title Which statement correctly compares two lists for equality? type mc from testbank-py-1-ch06-37 section 6.2 List Operations id testbank-py-2-ch06-37 52. What is in values after the following code segment executes? values = [1, 2, 3] values = values * 4 1. [4, 8, 12]


52.

2. [1, 2, 3, 4] 3. [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] 4. Nothing because a runtime error occurs Section 6.2 List Operations Title Trace code that attempts to multiply a list by an integer type mc from testbank-py-1-ch06-47 section 6.2 List Operations id testbank-py-2-ch06-47

53. Consider the following code segment: x = [5, 3, 7] y = sorted(x) print(x) What is displayed when it executes? 1. [] 2. [3, 5, 7] 3. [5, 3, 7] 4. [7, 5, 3] Section 6.2 List Operations Title What output is generated by a code segment involving lists? type mc section 6.2 List Operations id testbank-py-2-ch06-88 54. Consider the following code segment: x = [5, 3, 7] y = x.pop() print(y) What is displayed when it executes? 1. 5 2. 7 3. [3, 7] 4. [5, 3] Section 6.2 List Operations Title What output is generated by a code segment involving lists? type mc


54. section 6.2 List Operations id testbank-py-2-ch06-89 55. Consider the following code segment: x = [5, 3, 7, 9, 1] y = x[2 : 4] print(y) What is displayed when it executes? 1. [3, 7] 2. [7, 9] 3. [3, 7, 9] 4. [7, 9, 1] Section 6.2 List Operations Title What output is generated by a code segment involving a slice? type mc section 6.2 List Operations id testbank-py-2-ch06-90 56. Consider the following code segment: x = [5, 3, 7, 9, 1] y = x[3 : ] print(y) What is displayed when it executes? 1. [9] 2. [9, 1] 3. [3, 7, 9, 1] 4. [5, 3, 7, 9] Section 6.2 List Operations Title What output is generated by a code segment involving a slice? type mc section 6.2 List Operations id testbank-py-2-ch06-91 57. Consider the following code segment: x = [5, 3, 7, 9, 1] y = x[ : 2] print(y)


57. What is displayed when it executes? 1. 7 2. [7] 3. [5, 3] 4. [5, 3, 7] Section 6.2 List Operations Title What output is generated by a code segment involving a slice? type mc section 6.2 List Operations id testbank-py-2-ch06-92 58. What is the resulting contents of the list values in this code snippet? values = [] for i in range(10) : values.append(i) 1. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 2. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 3. [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 4. [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] Section 6.3 Common List Algorithms Title What is the resulting contents of the list values in this code snippet? type mc section 6.3 Common List Algorithms id testbank-py-1-ch06-51 59. What is the resulting value of the variable sentence in this code snippet? words = ["Mary", "had", "a", "little", "lamb"] sentence = "" for word in words : sentence = sentence + word 1. Mary had a little lamb 2. Maryhadalittlelamb 3. "Mary had a little lamb" 4. Mary, had, a, little, lamb Section 6.3 Common List Algorithms Title What is the resulting value of the variable sentence in this code snippet? type mc


59.

section 6.3 Common List Algorithms id testbank-py-1-ch06-52

60. What is the resulting value of the variable sentence in this code snippet? words = ["Mary", "had", "a", "little", "lamb"] sentence = str(words) 1. Mary had a little lamb 2. Maryhadalittlelamb 3. ['Mary', 'had', 'a', 'little', 'lamb'] 4. Mary, had, a, little, lamb Section 6.3 Common List Algorithms Title What is the resulting value of the variable sentence in this code snippet? type mc section 6.3 Common List Algorithms id testbank-py-1-ch06-53 61. What is missing from this code snippet to find the largest value in the list? largest = values[0] for i in range(1, len(values)) : if values[i] > largest : ____________________ 1. i = i + 1 2. largest = values[i] 3. largest = values[0] 4. largest = values[i-1] Section 6.3 Common List Algorithms Title What is missing from this code snippet to find the largest value in the list? type mc section 6.3 Common List Algorithms id testbank-py-1-ch06-54 62. What code completes this code snippet to swap the first and last element in the list? states = ["Alaska", "Hawaii", "Florida", "Maine"] i=0 ________________________ temp = states[j]


62. states[j] = states[0] states[i] = temp 1. j = len(states) 2. j = len(states) - 1 3. j = len(states) + 1 4. j = 0 Section 6.3 Common List Algorithms Title What code completes this code snippet to swap the first and last element in the list? type mc section 6.3 Common List Algorithms id testbank-py-1-ch06-59 63. The following code segment is supposed to display all of the elements in a list with dashes between them. For example, if values contains [1, 2, 3, 4, 5] then the program should display 1-2-3-4-5. result = "" for i in range(len(values) : if i > 0 : _____________________ result = result + str(values[i]) print(result) What line of code should be placed in the blank to achieve this goal? 1. print("-") 2. result = "-" 3. values[i] = "-" 4. result = result + "-" Section 6.3 Common List Algorithms Title Complete the code segment for displaying a list type mc section 6.3 Common List Algorithms id testbank-py-1-ch06-60 64. Consider the following code segment: x = values[0] for i in range(1, len(values)) : if values[i] > x : x = values[i] Which of the following statements assigns the same value to x as the code segment above? 1. x = max(values) 2. x = min(values)


64.

3. x = sum(values) 4. x = sorted(values) Section 6.3 Common List Algorithms Title Which line of code is equivalent to this code segment? type mc section 6.3 Common List Algorithms id testbank-py-1-ch06-61

65. The following code segment is supposed to count the number of times that the number 5 appears in the list values. counter = 0 ____________________ if (element == 5) : counter = counter + 1 What line of code should be placed in the blank in order to achieve this goal? 1. for counter in element : 2. for counter in values : 3. for element in counter : 4. for element in values : Section 6.3 Common List Algorithms Title Complete the code segment for counting the number of occurrences of a value in a list type mc section 6.3 Common List Algorithms id testbank-py-1-ch06-62 66. What does the following code segment do? i=0 while i < len(values) : if values[i] >= 4 and values[i] <= 6 : values.pop(i) else : i=i+1 1. It removes all 5 from values 2. It removes all 4s, 5s and 6s from values 3. It removes the element at position 5 from values 4. It removes the elements at positions 4, 5 and 6 from values Section 6.3 Common List Algorithms Title What does this code segment involving lists do?


66. type mc section 6.3 Common List Algorithms id testbank-py-1-ch06-63 67. Which code segment swaps the elements at position 0 and position 2 within the values list? 1. values[0] = values[2] 2. values[0] = values[2] values[2] = values[0] 3. values[0] = temp values[0] = values[2] temp = values[2] 4. temp = values[2] values[2] = values[0] values[0] = temp Section 6.3 Common List Algorithms Title Which code segment swap two elements in a list? type mc section 6.3 Common List Algorithms id testbank-py-1-ch06-64 68. The following code segment is supposed to read all of the integers entered by the user until a blank line is entered and store them in values. values = [] inputStr = input("Enter a value (blank line to quit): ") ____________________ values.append(int(inputStr)) inputStr = input("Enter a value (blank line to quit): ") What line of code should be placed in the blank to achieve this goal? 1. for ch in inputStr : 2. for values in inputStr : 3. while inputStr != "" : 4. while inputStr in values : Section 6.3 Common List Algorithms Title Complete the code segment for reading a list of values from the user type mc


68. section 6.3 Common List Algorithms id testbank-py-1-ch06-65 69. What is missing from this code snippet to find the longest value in the list? colors = ["red", "purple", "blue", "green", "yellow", "light green"] longest = colors[0] for i in range(1, len(colors)) : _____________________ longest = colors[i] 1. if colors[i] > longest : 2. if len(colors[i]) > longest : 3. if len(colors[i]) > len(longest) : 4. if colors[i] > len(longest) : Section 6.3 Common List Algorithms Title What is missing from this code snippet to find the longest value in the list? type mc from testbank-py-1-ch06-55 section 6.3 Common List Algorithms id testbank-py-2-ch06-55 70. What type of search inspects every element sequentially? 1. binary search 2. linear search 3. simple search 4. recursive search Section 6.3 Common List Algorithms Title When type of search inspects every element sequentially? type mc from testbank-py-1-ch06-56 section 6.3 Common List Algorithms id testbank-py-2-ch06-56 71. What is printed by the following code snippet? words = ["Today", "is", "Wednesday", "tomorrow", "is", "Thursday"] for i in range(len(words)) : word = words[i] if len(word) < 8 :


71.

words.pop(i) print(words) 1. Nothing, this code snippet causes an IndexError: list index out of range error. 2. ["Today", "is", "Wednesday", "tomorrow", "is", "Thursday"] 3. ["Wednesday", "tomorrow", "Thursday"] 4. ["Today", "is", "is"] Section 6.3 Common List Algorithms Title What is printed by a code snippet that includes lists, loops and the pop method? type mc from testbank-py-1-ch06-57 section 6.3 Common List Algorithms id testbank-py-2-ch06-57

72. What is printed by the following code snippet? words = ["Today", "is", "Wednesday", "tomorrow", "is", "Thursday"] i=0 while i < (len(words)) : word = words[i] if len(word) < 8 : words.pop(i) else : i=i +1 print(words) 1. Nothing, this code snippet causes an IndexError: list index out of range error. 2. ["Today", "is", "Wednesday", "tomorrow", "is", "Thursday"] 3. ["Wednesday", "tomorrow", "Thursday"] 4. ["Today", "is", "is"] Section 6.3 Common List Algorithms Title What is printed by a code snippet that includes lists, loops and the pop method? type mc from testbank-py-1-ch06-58 section 6.3 Common List Algorithms id testbank-py-2-ch06-58 73. Which of the following statements is NOT true about functions and lists: 1. a function can return a list 2. a function can be called with a list as an argument 3. when calling a function with a list argument, the function receives a copy of the list 4. when calling a function with a list argument, the function receives a reference to the list not a copy of the list


73. Section 6.4 Using Lists with Functions Title Which of the following statements is NOT true about functions and lists: type mc section 6.4 Using Lists with Functions id testbank-py-1-ch06-66 74. The following function is supposed to add 1 to every element in a list of integers. def addOne(values) : for i in range(len(values)) : values[i] = values[i] + 1 What is wrong with the following function? 1. The statement print(values) must be added to the end of the function. 2. The statement return values must be added to the end of the function. 3. The for loop must be replaced with a while loop. 4. There is nothing wrong with the function. It works as intended. Section 6.4 Using Lists with Functions Title Identify the error in a function that adds 1 to every element in a list of integers type mc section 6.4 Using Lists with Functions id testbank-py-1-ch06-67 75. Given a list containing prices, how do you find the highest priced item and remove it from the list: 1. find the minimum, remove it from the list 2. find the maximum, remove it from the list 3. find the maximum, create a second list without this value 4. find the minimum, create a second list without this value Section 6.5 Problem Solving: Adapting Algorithms Title Given a list containing prices, how do you find the highest priced item and remove it from the list: type mc section 6.5 Problem Solving: Adapting Algorithms id testbank-py-1-ch06-68 76. What does the following code segment do? x=0 for i in range(1, len(values)) : if values[i] > values[x] : x=i


76.

1. It finds the largest item in values and stores it in x 2. It finds the position of the largest item in values and stores the position in x 3. It finds the smallest item in values and stores it in x 4. It finds the position of the smallest item in values and stores it in x Section 6.5 Problem Solving: Adapting Algorithms Title What does this code segment involving lists do? type mc section 6.5 Problem Solving: Adapting Algorithms id testbank-py-1-ch06-69

77. What does the following code segment do? x=0 for i in range(1, len(values)) : if values[i] < values[x] : x=i 1. It finds the largest item in values and stores it in x 2. It finds the position of the largest item in values and stores it in x 3. It finds the smallest item in values and stores it in x 4. It finds the position of the smallest item in values and stores it in x Section 6.5 Problem Solving: Adapting Algorithms Title What does this code segment involving lists do? type mc from testbank-py-1-ch06-76 section 6.5 Problem Solving: Adapting Algorithms id testbank-py-2-ch06-76 78. What library is used to read and write sound files? 1. scipy.file.sound 2. scipy.file.wavfile 3. scipy.io.sound 4. scipy.io.wavfile Section 6.5 Problem Solving: Adapting Algorithms Title What library is used to read and write sound files? type mc section 6.5 Problem Solving: Adapting Algorithms id testbank-py-2-ch06-85


79. What is stored in contents when a sound file is read by the scipy library using the following statement? contents = scipy.io.wavfile.read("meow.wav") 1. A list of integers 2. A numPy array 3. A tuple containing the sample rate and a NumPy array 4. A tuple containing the sample rate and a list of integers Section 6.5 Problem Solving: Adapting Algorithms Title What is returned when a sound file is read by the scipy library? type mc section 6.5 Problem Solving: Adapting Algorithms id testbank-py-2-ch06-86 80. Which of the following items would not be a good object to use while solving algorithms such as swapping the first half of a list with the second half: 1. deck of cards 2. dice 3. coins 4. toothpicks Section 6.6 Problem Solving: Discovering Algorithms Manipulating Physical Objects Title Which of the following items would not be a good object to use while solving algorithms: type mc section 6.6 Problem Solving: Discovering Algorithms by Manipulating Physical Objects id testbank-py-1-ch06-71 81. What is the purpose of the following pseudocode: i=0 j = length / 2 While i < length / 2 # Swap elements at positions i and j temp = a[i] a[i] = a[j] a[j] = temp i=i+1 j=j+1 1. flip the first half of a list with the second half 2. sort the list from smallest to largest 3. sort the list from largest to smallest 4. reverse the entire list Section 6.6 Problem Solving: Discovering Algorithms Manipulating Physical Objects Title


81. What is the purpose of some pseudocode? type mc from testbank-py-1-ch06-70 section 6.6 Problem Solving: Discovering Algorithms by Manipulating Physical Objects id testbank-py-2-ch06-70 82. What does the following code segment do? x = [] for i in range(5) : x.append([]) for j in range(3) : x[i].append(0) 1. It creates a table with 3 columns and 5 rows and stores it in x. 2. It creates a table with 5 columns and 3 rows and stores it in x. 3. It creates a list of 15 elements and stores it in x. 4. It creates an empty list and stores it in x. Section 6.7 Tables Title What does this code segment involving lists do? type mc section 6.7 Tables id testbank-py-1-ch06-77 83. What output is generated by the following code segment? table = [["T", "U", "V"], ["W", "X", "Y"]] print(table[0]) 1. T 2. ["T", "W"] 3. ["T", "U", "V"] 4. [["T", "U", "V"], ["W", "X", "Y"]] Section 6.7 Tables Title Trace the output for a code segment involving a table type mc section 6.7 Tables id testbank-py-1-ch06-78 84. What output is generated by the following code segment?


84. table = [["T", "U", "V"], ["W", "X", "Y"]] print(table[1][1]) 1. T 2. U 3. W 4. X Section 6.7 Tables Title Trace the output for a code segment involving a table type mc section 6.7 Tables id testbank-py-1-ch06-79 85. Consider the following table: table = [["T", "U", "V"], ["W", "X", "Y"]] Which statement will display Y? 1. print(table[len(table) - 1][len(table[1]) - 1]) 2. print(table[len(table) - 1][len(table[1])]) 3. print(table[len(table)][len(table[1])] - 1) 4. print(table[len(table)][len(table[1])]) Section 6.7 Tables Title Which statement involving tables will display the letter Y? type mc section 6.7 Tables id testbank-py-1-ch06-80 86. Which of the following statements best represents a deck of cards? 1. suits = ["Hearts", "Spades", "Diamonds", "Clubs"] faceValues = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"] 2. suits = ["Hearts", "Spades", "Diamonds", "Clubs] faceValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 3. cards = [["Ace of Hearts", "Ace of Spades", "Ace of Diamonds", "Ace of Clubs"], ["2 of Hearts", "2 of Spades", "2 of Diamonds", "2 of Clubs"], etc.] 4. suits = ["Hearts", "Spades", "Diamonds", "Clubs] faceValues = [2, 3, 4, 5, 6, 7, 8, 9, 10] faceValues2 = ["Ace", "Jack", "Queen", "King"] Section 6.7 Tables


86. Title Which of the following statements best represents a deck of cards? type mc from testbank-py-1-ch06-72 section 6.7 Tables id testbank-py-2-ch06-72 87. What is printed from the following code snippet? prices = [[ 1.0, 3.50, 7.50 ], [ 10.0, 30.50, 70.50 ], [ 100.0, 300.50, 700.50 ], [ 1000.0, 3000.50, 7000.50 ]] print(prices[1][2]) 1. 30.5 2. 70.5 3. 700.5 4. 10.0 Section 6.7 Tables Title What is printed by a code snippet involving a table? type mc from testbank-py-1-ch06-73 section 6.7 Tables id testbank-py-2-ch06-73 88. Given the list values = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], which statement fills the list with these numbers: 1 4 9 16 25 36 49 64 81 100 1. for i in range(10) : values[i] = (i + 1) * (i + 1) 2. for i in range(10) : values[i] = i * i 3. for i in range(0, 10) : values[i] = i + i 4. for i in range(1, 10) : values[i] = (i + 1) * (i + 1) Section


88.

6.7 Tables Title Which statement stores 10 numbers into an existing list? type mc from testbank-py-1-ch06-75 section 6.7 Tables id testbank-py-2-ch06-75

89. What list is stored in x after this code segment has run? x = [] for i in range(3) : x.append([]) for j in range(i) : x[j].append(0) 1. [[0, 0], [0], []] 2. [[0, 0], [0, 0], []] 3. [[0, 0], [0, 0], [0, 0]] 4. [[0, 0, 0], [0, 0, 0], [0, 0, 0]] Section 6.7 Tables Title What does this code segment involving lists do? type mc from testbank-py-1-ch06-81 section 6.7 Tables id testbank-py-2-ch06-81 90. How many values does a stereo sound file have for each sample? 1. 1 2. 2 3. 16 4. 44,100 Section 6.7 Tables Title How many values does a stereo sound file have for each sample? type mc section 6.7 Tables id testbank-py-3-ch6-93 91. What is returned when scipi.io.wavfile.read is called? 1. A list of integer values


91.

2. A numpy array of integer values 3. A tuple containing the sample rate and the sound data 4. The sample rate for the sound file Section 6.7 Tables Title What is returned when scipi.io.wavfile.read is called? type mc section 6.7 Tables id testbank-py-3-ch6-94


1. When reading a file in Python, you must specify two items: 1. a file name and file properties 2. a file name and mode 3. a file name and size 4. a file name and data type Section 7.1 Reading and Writing Text Files Title When reading a file in Python, what information must be provided? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-01 2. Before accessing a file, the program must: 1. name the file 2. read the file 3. open the file 4. close the file Section 7.1 Reading and Writing Text Files Title Before accessing a file, what must be done to allow access to the file? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-02 3. After executing the following code snippet, what part is the file object? infile = open("input.txt", "r") 1. infile 2. "input.txt" 3. "r" 4. input Section 7.1 Reading and Writing Text Files Title After executing the following code snippet, what part is the file object? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-03 4. In the following code snippet, what does the "r" represent? infile = open("input.txt", "r") 1. replace 2. recursive


4.

3. random 4. read Section 7.1 Reading and Writing Text Files Title In the following code snippet, what does the "r" represent? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-04

5. In the following code snippet, what does the "w" represent? outfile = open("output.txt", "w") 1. wrapper 2. write 3. width 4. web Section 7.1 Reading and Writing Text Files Title In the following code snippet, what does the "w" represent? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-05 6. In the following code snippet, what happens if the "output.txt" file does not exist? outfile = open("output.txt", "w") 1. An error message is displayed 2. An empty file is created 3. Nothing, this statement is ignored 4. A new file is created with at least one record Section 7.1 Reading and Writing Text Files Title In the following code snippet, what happens if the "output.txt" file does not exist? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-06 7. In the following code snippet, what happens if the "output.txt" file already exists? outfile = open("output.txt", "w") 1. Any new data is appended to the end 2. The existing file is emptied 3. Nothing, this statement is ignored


7.

4. An error message is displayed Section 7.1 Reading and Writing Text Files Title In the following code snippet, what happens if the "output.txt" file already exists? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-07

8. What method ensures that the output has been written to the disk file? 1. commit() 2. write() 3. close() 4. complete() Section 7.1 Reading and Writing Text Files Title What method ensures that the output has been written to the disk file? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-08 9. The readline method reads text until an end of line symbol is encountered, how is an end of line character represented? 1. \r 2. \t 3. "" 4. \n Section 7.1 Reading and Writing Text Files Title The readline method reads text until an end of line symbol is encountered, how is an end of line character represented? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-10


10. What is returned when the readline method reaches the end of the file? 1. \r 2. \t 3. "" 4. \n Section 7.1 Reading and Writing Text Files Title What is returned when the readline method reaches the end of the file? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-11 11. When using the readline method, what data type is returned? 1. integer 2. float 3. character 4. string Section 7.1 Reading and Writing Text Files Title When using the readline method, what data type is returned? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-12 12. What method(s) can be used to write to a file? 1. write, print 2. out, print 3. write, out 4. post, write Section 7.1 Reading and Writing Text Files Title What method(s) can be used to write to a file? type mc section 7.1 Reading and Writing Text Files


12. id testbank-py-1-ch07-13 13. What happens in the following code snippet? infile = open("", "r") 1. a new file object is created 2. a run-time error occurs because the file does not exist 3. nothing, the statement is ignored 4. a default file name is used "inputfile" Section 7.1 Reading and Writing Text Files Title What happens in the following code snippet? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-14 14. Which of the following statements opens a text file for reading? 1. infile = open("myfile.txt", "r") 2. infile = open("myfile.txt", "rw") 3. infile = open("myfile.txt", "read") 4. infile = open("myfile.txt", "reading") Section 7.1 Reading and Writing Text Files Title Which statement opens a text file for reading? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-15 15. What is the name of the file object variable in the following code segment? a = open("b.txt", "r") 1. a 2. b 3. b.txt 4. r Section 7.1 Reading and Writing Text Files Title Identify the file object variable in a code segment type mc section 7.1 Reading and Writing Text Files id


15. testbank-py-1-ch07-16 16. What happens when the following code segment executes if test.txt does not exist? infile = open("test.txt", "r") 1. The file test.txt is created as a new empty file 2. The program raises an exception 3. All attempts to read from the file return an empty string 4. All attempts to read from the file return random values Section 7.1 Reading and Writing Text Files Title What happens when opening a file that doesn't exist for reading? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-17 17. What happens when the following code segment executes if test.txt does not exist? outfile = open("test.txt", "w") 1. The file test.txt is created as a new empty file 2. The program ends with an exception 3. All attempts to write to the file succeed but do not save any data 4. The program continues executing until the first write statement Section 7.1 Reading and Writing Text Files Title What happens when opening a file that doesn't exist for writing? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-18 18. Which statement is used to close the file object opened with the following statement? infile = open("test.txt", "r") 1. close(infile) 2. close("test.txt") 3. infile.close() 4. infile.close("test.txt") Section 7.1 Reading and Writing Text Files Title Which statement correctly closes a file? type mc section


18. 7.1 Reading and Writing Text Files id testbank-py-1-ch07-19 19. Which statement(s) writes the sentence "Today is the first day of the rest of your life" to a file with one word on each line? 1. outfile.write("Today is the first day of the rest of your life") 2. outfile.write("Today \nis \nthe \nfirst \nday \nof \nthe \nrest \nof \nyour \nlife") 3. outfile.write(Today is the first day of the rest of your life) 4. outfile.writeline("Today \nis \nthe \nfirst \nday \nof \nthe \nrest \nof \nyour \nlife") Section 7.1 Reading and Writing Text Files Title Which statement(s) writes the sentence "Today is the first day of the rest of your life" to a file with one word on each line? type mc section 7.1 Reading and Writing Text Files id testbank-py-1-ch07-71 20. Consider a program that wants to read a file from the absolute path c:\users\user1\states.dat. What statement allows you to read this file? 1. file = open("c:\\\users\\\user1\\\states.dat", "r") 2. file = open("c:\users\user1\states.dat", "r") 3. file = open("..\\states.dat", "r") 4. file = open("c:\\users\\user1\\states.dat", "r") Section 7.1 Reading and Writing Text Files Title What statement allows you to ready a file from its absolute path? type mc from testbank-py-1-ch07-70 section 7.1 Reading and Writing Text Files id testbank-py-2-ch07-70 21. What happens if you try to open a file for reading that doesn't exist? 1. A new file is created and opened. 2. A run-time error occurs because the file does not exist.


21.

3. The statement is ignored. 4. An environment error occurs. Section 7.1 Reading and Writing Text Files Title What happens if you try to open a file for reading that doesn't exist? type mc from testbank-py-1-ch07-75 section 7.1 Reading and Writing Text Files id testbank-py-2-ch07-75

22. Once a file has been opened, what method is used to read data from a file? 1. readline() 2. readfile() 3. readln() 4. open() Section 7.1 Reading and Writing Text Files Title Once a file has been opened, what method is used to read data from a file? type mc from testbank-py-1-ch07-09 section 7.1 Reading and Writing Text Files id testbank-py-2-ch07-09 23. In the code snippet below, if the file contains the following words: apple, pear, and banana stored one per line, what would be the output? infile = open("input.txt", "r") for word in infile : word = word.rstrip() print(word) 1. apple pear banana 2. apple pear banana 3. apple pear banana 4. apple, pear, banana Section 7.2 Text Input and Output Title


23.

In the code snippet below, if the file contains the following words: apple, pear, and banana stored one per line, what would be the output? type mc section 7.2 Text Input and Output id testbank-py-1-ch07-22

24. In the code snippet below, if the file contains the following words: Monday! Tuesday. Wednesday? stored one per line, what would be the output? infile = open("input.txt", "r") for word in infile : word = word.rstrip(".!\n") print(word) 1. Monday Tuesday Wednesday 2. Monday Tuesday Wednesday 3. Monday! Tuesday. Wednesday 4. Monday Tuesday Wednesday? Section 7.2 Text Input and Output Title In the code snippet below, if the file contains the following words: Monday! Tuesday. Wednesday? stored one per line, what would be the output? type mc section 7.2 Text Input and Output id testbank-py-1-ch07-23 25. Which of the following methods strips specified punctuation from the front or end of each string (s)? 1. s.lstrip(".!?;:") 2. s.rstrip(".!?;:") 3. s.strip(".!?;:") 4. s.strip()


25.

Section 7.2 Text Input and Output Title Which of the following methods strips specified punctuation from the front or end of each string (s)? type mc section 7.2 Text Input and Output id testbank-py-1-ch07-25

26. Which statement below can be used to read data from a file one character at a time? 1. inputFile.get(1) 2. inputFile.read(1) 3. inputFile.split(1) 4. inputFile.open(1) Section 7.2 Text Input and Output Title Which statement below can be used to read data from a file one character at a time? type mc section 7.2 Text Input and Output id testbank-py-1-ch07-29 27. Given a text file quote.txt that contains this sentence: Home computers are being called upon to perform many new functions, including the consumption of homework formerly eaten by the dog. ~Doug Larson What is the result of this code snippet: inputFile = open("quote.txt", "r") char = inputFile.read(1) while char != "" : print(char) char = inputFile.read(1) inputFile.close() 1. Home computers are being called upon to perform many new functions, including the consumption of homework formerly eaten by the dog. ~Doug Larson 2. each character of the quote is printed on a separate line 3. H 4. o Section 7.2 Text Input and Output


27.

Title What is the result of the code snippet that reads a text file using the read method? type mc section 7.2 Text Input and Output id testbank-py-1-ch07-31

28. Assume that outfile is a file object that has been opened for writing. Which of the following code segments stores Hello World in the file? 1. outfile.print("Hello\n", "World\n") 2. outfile.write("Hello\n", "World\n") 3. outfile.print("Hello\nWorld\n") 4. outfile.write("Hello\nWorld\n") Section 7.2 Text Input and Output Title Which statement saves "Hello World" in a file? type mc section 7.2 Text Input and Output id testbank-py-1-ch07-33 29. The following code segment is supposed to read all of the lines from test.txt and save them in copy.txt. infile = open("test.txt", "r") outfile = open("copy.txt", "w") line = infile.readline() ____________________ outfile.write(line) line = infile.readline() infile.close() outfile.close() Which line of code should be placed in the blank to achieve this goal? 1. while line == "" : 2. while line != "" : 3. while line == "\n" : 4. while line != "\n" : Section 7.2 Text Input and Output Title Complete the code for copying a file


29.

type mc section 7.2 Text Input and Output id testbank-py-1-ch07-34

30. The following code segment is supposed to read and display the contents of a file. What problem does it have in its current form? infile = open("test.txt", "r") line = infile.readline() while line != "" : print(line) line = infile.readline() infile.close() 1. The program displays all of the lines, except for the first one 2. The program displays all of the lines, except for the last one 3. The program displays the contents of the file, but it is double spaced 4. There is no problem -- the program works as desired Section 7.2 Text Input and Output Title What is wrong with the program for displaying a text file? type mc section 7.2 Text Input and Output id testbank-py-1-ch07-35 31. The following program opens test.txt and displays its contents. If nothing is placed in the blank, then the contents of the file is displayed double spaced. What should be placed on the blank so that the contents of the file is displayed without the extra blank lines? infile = open("test.txt", "r") line = infile.readline() while line != "" : ____________________ print(line) line = infile.readline() infile.close() 1. infile = infile.lstrip() 2. infile = infile.rstrip() 3. line = line.lstrip() 4. line = line.rstrip() Section


31.

7.2 Text Input and Output Title What code should be added so that extra blank lines are removed? type mc section 7.2 Text Input and Output id testbank-py-1-ch07-36

32. Consider the following code segment: line = "hello world!" parts = line.split() print(parts) What is displayed when this code segment runs? 1. hello,world! 2. hello world! 3. "hello", "world!" 4. ["hello", "world!"] Section 7.2 Text Input and Output Title Trace code involving the split method type mc section 7.2 Text Input and Output id testbank-py-1-ch07-38 33. Assume that a line has just been read from a file and stored in a variable named line. The line contains several words, each of which is separated by one or more spaces. Which of the following statements will store a list of all the words in wordList? 1. wordList = line.split() 2. wordList = line.splitlines() 3. wordList = line.strip() 4. wordList = line.words() Section 7.2 Text Input and Output Title Which statement produces a list of words from a line in a file? type mc section 7.2 Text Input and Output id testbank-py-1-ch07-39 34. What type of value is returned by the expression ord("A")? 1. Integer 2. Floating Point Number 3. String


34.

4. List Section 7.2 Text Input and Output Title What type of value is returned by the ord function? type mc section 7.2 Text Input and Output id testbank-py-1-ch07-40

35. Which of the following statements is NOT valid for reading from a file: 1. inputFile.readline() 2. inputFile.read() 3. inputFile.readline(5) 4. inputFile.read(5) Section 7.2 Text Input and Output Title Which of the following statements is NOT valid for reading from a file: type mc section 7.2 Text Input and Output id testbank-py-1-ch07-67 36. Which of the following file operations is NOT valid for reading a binary file? 1. fileName = open("input.dat", "r") 2. fileName.close() 3. fileName.write("Good Bye") 4. fileName = open("input.dat", "rw") Section 7.2 Text Input and Output Title Which of the following file operations is NOT valid? type mc section 7.2 Text Input and Output id testbank-py-1-ch07-73 37. What is wrong with the following code snippet that is supposed to print the contents of the file twice?


37. infile = open("input.txt", "r") for sentence in infile : print(sentence) for sentence in infile : print(sentence) 1. Python cannot iterate over the file twice without closing and reopening the file 2. A run-time error occurs because the file does not exist 3. Nothing, the code prints the contents two times 4. The program cannot use the variable sentence twice Section 7.2 Text Input and Output Title What is wrong with a code snippet that is supposed to print the contents of the file twice? type mc section 7.2 Text Input and Output id testbank-py-1-ch07-20 38. What is output by the following code segment when input.txt contains the following words: apple, pear, and banana stored one per line? infile = open("input.txt", "r") for word in infile : print(word) 1. apple pear banana 2. apple pear banana 3. apple pear banana 4. apple, pear, banana Section 7.2 Text Input and Output Title What is output by a code segment that reads data from a file? type mc from testbank-py-1-ch07-21 section 7.2 Text Input and Output id testbank-py-2-ch07-21 39. In the code snippet below, if the file contains the following words: Monday! Tuesday. Wednesday? stored one per line, what would be the output?


39. infile = open("input.txt", "r") for word in infile : word = word.lstrip(".!") print(word) 1. Monday Tuesday Wednesday 2. Monday Tuesday Wednesday 3. Monday! Tuesday. Wednesday? 4. Monday Tuesday Wednesday? Section 7.2 Text Input and Output Title What is output by a code segment that reads data from a file? type mc from testbank-py-1-ch07-24 section 7.2 Text Input and Output id testbank-py-2-ch07-24 40. Which of the following methods provides a way to split the contents of the string sentence into a list of individual words? 1. sentence.split() 2. sentence.strip() 3. sentence.splice() 4. sentence.separate() Section 7.2 Text Input and Output Title Which statement splits a string into a list of individual words? type mc from testbank-py-1-ch07-26 section 7.2 Text Input and Output id testbank-py-2-ch07-26 41. What will be stored in substrings after the following code snippet has run?


41. states = "Michigan,Maine,Minnesota,Montana,Mississippi" substrings = states.split(",") 1. "Michigan,Maine,Minnesota,Montana,Mississippi" 2. ["Michigan", "Maine", "Minnesota", "Montana", "Mississippi"] 3. ["Michigan,Maine,Minnesota,Montana,Mississippi"] 4. "Michigan" Section 7.2 Text Input and Output Title What is returned when the split method is called? type mc from testbank-py-1-ch07-27 section 7.2 Text Input and Output id testbank-py-2-ch07-27 42. What is stored in substrings after the following code snippet has run? states = "Michigan,Maine,Minnesota,,Montana,Mississippi" substrings = states.split(",") 1. "Michigan,Maine,Minnesota,Montana,Mississippi" 2. ["Michigan"] 3. ["Michigan,Maine,Minnesota,Montana,Mississippi"] 4. ["Michigan","Maine","Minnesota","","Montana","Mississippi"] Section 7.2 Text Input and Output Title What is returned when the split method is called? type mc from testbank-py-1-ch07-28 section 7.2 Text Input and Output id testbank-py-2-ch07-28 43. Given a text file quote.txt that contains this sentence: Home computers are being called upon to perform many new functions, including the consumption of homework formerly eaten by the dog. ~Doug Larson What will be printed by this code snippet? letterCounts = [0] * 26 inputFile = open("quote.txt", "r") char = inputFile.read(1) while char != "" : char = char.upper() if char >= "A" and char <= "Z" :


43.

code = ord(char) - ord("A") letterCounts[code] = letterCounts[code] + 1 char = inputFile.read(1) inputFile.close() print(letterCounts[1]) 1. 0 2. 2 3. 1 4. 5 Section 7.2 Text Input and Output Title What is printed by a code snippet that reads a text file using the read method? type mc from testbank-py-1-ch07-30 section 7.2 Text Input and Output id testbank-py-2-ch07-30

44. Suppose the input file contains a person's last name and age on the same line separated by a space. Which statements extract this information correctly? 1. record = inputFile.readline() data = record.split() name = data[0].rstrip() age = int(data[1]) 2. record = inputFile.readline() data = record.split() age = int(data[0]) name = data[1].rstrip() 3. record = inputFile.read(1) data = record.split() name = data[0].rstrip() age = int(data[1]) 4. record = inputFile.readline() name = record[0].rstrip() age = int(record[1]) Section 7.2 Text Input and Output Title Which statement reads data from a file correctly? type mc from testbank-py-1-ch07-32 section


44. 7.2 Text Input and Output id testbank-py-2-ch07-32 45. Which of the following code segments will display all of the lines in the file object named infile, assuming that it has successfully been opened for reading? 1. for infile in line : print(line) 2. for line in infile : print(line) 3. while infile in line : print(line) 4. while line in infile : print(line) Section 7.2 Text Input and Output Title Which code segment displays all of the lines in a file? type mc from testbank-py-1-ch07-37 section 7.2 Text Input and Output id testbank-py-2-ch07-37 46. What is wrong with the following code snippet: file = open("lyrics.txt", "w") line = file.readline() words = line.split() print(words) file.close() 1. The file has only been opened for writing, not reading. 2. The file name is invalid. 3. The program cannot run without a try/catch statement. 4. The split method has not been used correctly. Section 7.2 Text Input and Output Title What is wrong with a code segment that reads from a file? type mc from testbank-py-1-ch07-68 section 7.2 Text Input and Output


46. id testbank-py-2-ch07-68 47. Suppose an input file contains a grocery list. Each line contains the item name followed by its cost. The item name and cost are separated by a comma. Which statements extract this information correctly? 1. record = inputFile.read(1) data = record.split(,) groceryItem = data[0].rstrip() cost = int(data[1]) 2. record = inputFile.readline() data = record.split() groceryItem = int(data[0]) cost = data[1].rstrip() 3. record = inputFile.readline() data = record.split(",") groceryItem = data[0].rstrip() cost = float(data[1]) 4. record = inputFile.readline() groceryItem = record[0].rstrip() cost = int(record[1]) Section 7.2 Text Input and Output Title Which statements extract information from a file correctly? type mc from testbank-py-1-ch07-72 section 7.2 Text Input and Output id testbank-py-2-ch07-72 48. What portable file format is commonly used to export data from a spreadsheet so that it can be read and processed by a Python program? 1. Comma-Separated Values (CSV) 2. Graphics Interchange Format (GIF) 3. Hypertext Markup Language (HTML) 4. Portable Spreadsheet Format (PSF) Section 7.2 Text Input and Output Title What portable file format is commonly used to export data from a spreadsheet so that it can be read and processed by a Python program? type mc section 7.2 Text Input and Output


48. id testbank-py-2-ch07-76 49. Consider the following code segment: from csv import writer outfile = open("newdata.csv", "w") csvWriter = writer(outfile) What statement should be added to the end of this code segment so that it will write a row of values to the file? 1. csvWriter.writerow(1, 2, 3, 4) 2. csvWriter.writerow([1, 2, 3, 4]) 3. outf.write(1, 2, 3, 4) 4. outf.write([1, 2, 3, 4]) Section 7.2 Text Input and Output Title Which statement is used to write a row of data to a CSV file? type mc section 7.2 Text Input and Output id testbank-py-2-ch07-77 50. Which statement imports all of the functions in Python's regular expression library? 1. from re import * 2. from regex import * 3. from reg_exp import * 4. from regular_expression import * Section 7.2 Text Input and Output Title Which statement imports Python's regular expression library? type mc section 7.2 Text Input and Output id testbank-py-2-ch07-78 51. Which character encoding standard uses sequences of between 1 and 4 bytes to represent a huge number of different characters? 1. ASCII 2. CSV 3. Extended ASCII 4. UTF-8 Section 7.2 Text Input and Output Title Which character encoding standard uses sequences of between 1 and 4 bytes to represent a huge number of different characters? type


51. mc section 7.2 Text Input and Output id testbank-py-2-ch07-79 52. Which of the following statements should be used to open a file that might contain special characters (such as accents, Greek letters or musical symbols) for reading? 1. inf = open("input.txt") 2. inf = open("input.txt", "r") 3. inf = open("input.txt", "r", "utf-8") 4. inf = open("input.txt", "r", encoding="utf-8") Section 7.2 Text Input and Output Title Which statement will open a file containing special characters for reading? type mc section 7.2 Text Input and Output id testbank-py-2-ch07-80 53. Given the following command line, where are the arguments stored? python program.py -v input.dat 1. user defined list 2. argv list 3. input.dat 4. program.py Section 7.3 Command Line Arguments Title Given the following command line, where are the arguments stored? type mc section 7.3 Command Line Arguments id testbank-py-1-ch07-42 54. Assume that your program is started with the following command: python myProgram.py -z 100 What will be displayed by the following statement? print(sys.argv[0]) 1. python 2. myProgram.py 3. -z 4. 100 Section


54. 7.3 Command Line Arguments Title Trace the code involving command line arguments type mc section 7.3 Command Line Arguments id testbank-py-1-ch07-44 55. Assume that your program is started with the following command: python myProgram.py the quick brown fox What will be displayed by the following statement? print(sys.argv[5]) 1. brown 2. fox 3. A blank line 4. The program will raise an exception Section 7.3 Command Line Arguments Title Trace the code involving several command line arguments type mc section 7.3 Command Line Arguments id testbank-py-1-ch07-45 56. Which statement must appear in a program before the command line arguments can be accessed? 1. from commandline import argv 2. from argv import commandline 3. from sys import argv 4. from argv import sys Section 7.3 Command Line Arguments Title Which statement must appear in a program before the command line arguments can be accessed? type mc section 7.3 Command Line Arguments id testbank-py-1-ch07-46 57. How is a program executed or started from the command line? 1. Selecting "Run" in the development environment 2. Clicking an icon 3. Typing the name of the program at the prompt in a terminal window 4. Python programs cannot be started from the command line Section


57. 7.3 Command Line Arguments Title How is a program executed or started from the command line? type mc from testbank-py-1-ch07-41 section 7.3 Command Line Arguments id testbank-py-2-ch07-41 58. If a program is invoked with python program.py -r input.dat output.dat, what are the elements of argv? 1. argv[0]: "-r input.dat output.dat" 2. argv[1]: "-r" argv[2]: "input.dat" argv[3]: "output.dat" 3. argv[0]: "program.py" argv[1]: "-r" argv[2]: "input.dat" argv[3]: "output.dat" 4. argv[0]: "-r" argv[1]: "input.dat" argv[2]: "output.dat" Section 7.3 Command Line Arguments Title What elements will be stored in argv for a given program invocation? type mc from testbank-py-1-ch07-43 section 7.3 Command Line Arguments id testbank-py-2-ch07-43 59. Which of the following is not a function that resides in Python's os module? 1. chdir 2. open 3. remove 4. rename Section 7.3 Command Line Arguments Title Which of the following is not a function that resides in Python's os module? type mc


59.

section 7.3 Command Line Arguments id testbank-py-2-ch07-81

60. Consider the following code segment: import os filename = input("Enter the name of a file: ") if ____________________ : print("That file exists!") else: print("That file does not exist.") This code segment is supposed to print an appropriate message indicating whether or not the file specified by the user exists. What code should be placed in the blank so that the code segment performs its intended task? 1. filename != "" 2. os.path.exists() 3. os.path.exists() == filename 4. os.path.exists(filename) Section 7.3 Command Line Arguments Title Which statement will check if a file exists? type mc section 7.3 Command Line Arguments id testbank-py-2-ch07-82 61. What modes are used to read and write a binary file? 1. "r", "w" 2. "-r", "-w" 3. "rb", "wb" 4. "-rb", "-wb" Section 7.4 Binary Files and Random Access (Optional) Title What modes are used to read and write a binary file? type mc section 7.4 Binary Files and Random Access (Optional) id testbank-py-1-ch07-47 62. If a Byte consists of 8 Bits, what is the min and max values of one Byte?


62.

1. 0 - 255 2. 1 - 256 3. 0 - 256 4. 1 - 255 Section 7.4 Binary Files and Random Access (Optional) Title If a Byte consists of 8 Bits, what is the min and max values of one Byte? type mc section 7.4 Binary Files and Random Access (Optional) id testbank-py-1-ch07-48

63. What is the result of the variable position after the following code snippet is executed? inFile.seek(0) inFile.seek(8, SEEK_CUR) inFile.seek(-3, SEEK_CUR) position = inFile.tell() 1. 0 2. 8 3. 5 4. -3 Section 7.4 Binary Files and Random Access (Optional) Title What is the result of the variable position after the following code snippet is executed? type mc section 7.4 Binary Files and Random Access (Optional) id testbank-py-1-ch07-49 64. Which of the following statements opens a binary file for reading? 1. inFile = open("test.dat", "r") 2. inFile = open("test.dat", "rb") 3. inFile = open("test.dat", "binary") 4. inFile = open("test.dat", "readbinary") Section 7.4 Binary Files and Random Access (Optional) Title


64. Which statement opens a binary file for reading? type mc section 7.4 Binary Files and Random Access (Optional) id testbank-py-1-ch07-52 65. Which of the following statements moves the file marker 4 bytes earlier in a binary file with its file object stored in inFile? 1. inFile.seek(-4, SEEK_CUR) 2. inFile.seek(4, SEEK_CUR) 3. inFile.reverse(-4, SEEK_CUR) 4. inFile.reverse(4, SEEK_CUR) Section 7.4 Binary Files and Random Access (Optional) Title Which statement moves the file marker 4 bytes earlier in a file? type mc section 7.4 Binary Files and Random Access (Optional) id testbank-py-1-ch07-53 66. Which of the following statements stores the current position of the file marker for inFile into x? 1. x = inFile.currentPos() 2. x = inFile.position() 3. x = inFile.read() 4. x = inFile.tell() Section 7.4 Binary Files and Random Access (Optional) Title Which statement stores the current position of the file marker in a variable? type mc section 7.4 Binary Files and Random Access (Optional) id testbank-py-1-ch07-54 67. How can you read from a file starting at a designated position in it? 1. Open the file for sequential access. 2. Move the file marker prior to a read or write operation. 3. You can't. Python only allows you to start reading at the beginning of a file. 4. Use the readline(position) method. Section 7.4 Binary Files and Random Access (Optional) Title How can you read a file starting at a designated position in the file? type mc from


67. testbank-py-1-ch07-69 section 7.4 Binary Files and Random Access (Optional) id testbank-py-2-ch07-69 68. Consider the following code segment: print("W", end="") try : inFile = open("test.txt", "r") line = inFile.readline() value = int(line) print("X", end="") except IOError : print("Y", end="") except ValueError : print("Z", end="") What output is generated when this program runs if test.txt is opened successfully and its first line contains the number 5? 1. W 2. WX 3. WXY 4. WXYZ Section 7.5 Exception Handling Title Trace code involving files and exceptions type mc section 7.5 Exception Handling id testbank-py-1-ch07-59 69. Consider the following code segment: print("W", end="") try : inFile = open("test.txt", "r") line = inFile.readline() value = int(line) print("X", end="") except IOError : print("Y", end="") except ValueError : print("Z", end="")


69. What output is generated when this program runs if test.txt is not opened successfully? 1. WX 2. WY 3. WZ 4. WXY Section 7.5 Exception Handling Title Trace code involving files and exceptions type mc section 7.5 Exception Handling id testbank-py-1-ch07-60 70. Consider the following code segment: print("W", end="") try : inFile = open("test.txt", "r") line = inFile.readline() value = int(line) print("X", end="") except IOError : print("Y", end="") except ValueError : print("Z", end="") What output is generated when this program runs if test.txt is opened successfully and its first line contains the hello world? 1. WX 2. WY 3. WZ 4. WXZ Section 7.5 Exception Handling Title Trace code involving files and exceptions type mc section 7.5 Exception Handling id testbank-py-1-ch07-61 71. What exception is raised by the following code segment? data = ["A", "B", "C", "D"] print(data[4]) 1. IndexError


71.

2. IOError 3. ValueError 4. No exception is raised by the code segment Section 7.5 Exception Handling Title What exception is raised by this code segment? type mc section 7.5 Exception Handling id testbank-py-1-ch07-62

72. What code should be added to the end of the following code segment to ensure that inFile is always closed, even if an exception is thrown in the code represented by . . . ? inFile = open("test.txt", "r") try : line = inFile.readline() ... 1. inFile.close() 2. always : inFile.close() 3. ensure : inFile.close() 4. finally : inFile.close() Section 7.5 Exception Handling Title What code ensures that a file is always closed, even if an exception occurs? type mc section 7.5 Exception Handling id testbank-py-1-ch07-63 73. It is good programming practice to plan for possible exceptions and provide code to handle the exception. Which exception must be handled to prevent a divide by zero logic error? 1. ValueError 2. TypeError 3. ArithmeticError 4. ZeroDivisionError Section 7.5 Exception Handling Title


73. Which exception must be handled to prevent a divide by zero logic error? type mc from testbank-py-1-ch07-55 section 7.5 Exception Handling id testbank-py-2-ch07-55 74. Consider the following code segment: try : inputFile = open("lyrics.txt", "r") line = inputFile.readline() print(line) _____________________ print("Error") What should be placed in the blank so that the program will print Error instead of crashing if an exception occurs while opening or reading from the file? 1. except RuntimeError : 2. except EnvironmentError : 3. except IOError : 4. except IndexError : Section 7.5 Exception Handling Title What should be added to a code segment to prevent it from crashing when an exception occurs? type mc from testbank-py-1-ch07-56 section 7.5 Exception Handling id testbank-py-2-ch07-56 75. Consider the following code segment: try : inputFile = open("lyrics.txt", "r") line = inputFile.readline() words = line.split() print(words[len(words)]) _____________________ print("Error.")


75. The statement print(words[len(words)]) will raise an exception. What should be placed in the blank so that this exception will be caught and the error message will be displayed? 1. except RuntimeError : 2. except EnvironmentError : 3. except IOError : 4. except IndexError : Section 7.5 Exception Handling Title What should be added to a code segment to prevent it from crashing when an exception occurs? type mc from testbank-py-1-ch07-57 section 7.5 Exception Handling id testbank-py-2-ch07-57 76. Python's error handling process includes the finally clause. In the following code snippet, when is the finally clause executed? inputFile = open("lyrics.txt", "r") try : line = inputFile.readline() words = line.split() print(words) finally : inputfile.close() 1. Only when there is an error opening the file. 2. Only when there is an error reading the file. 3. The finally clause is always executed in this example. 4. The finally clause is never executed in this example. Section 7.5 Exception Handling Title When is the finally clause executed? type mc from testbank-py-1-ch07-58 section 7.5 Exception Handling id testbank-py-2-ch07-58 77. Which of the following is NOT a valid exception in Python? 1. OverflowError 2. TryError 3. IOError


77.

4. IndexError Section 7.5 Handling Exceptions Title Which of the following is NOT a valid exception in Python? type mc from testbank-py-1-ch07-74 section 7.5 Exception Handling id testbank-py-2-ch07-74

78. When your program contains logic to read one or more files, which of the following statements is NOT true about the error handling logic needed: 1. The file might not exist 2. The file name might be too long 3. The file might contain invalid data 4. All files must be opened and closed prior to program termination Section 7.6 Application: Handling Input Errors Title When your program contains logic to read one or more files, which of the following statements is NOT true about the error handling logic? type mc section 7.6 Application: Handling Input Errors id testbank-py-1-ch07-65 79. Consider the following code segment: done = False while not done : try : filename = input("Enter the file name: ") inFile = open(filename, "r") ____________________ except IOError : print("Error: File not found.") It is supposed to keep on prompting the user for file names until the user provides the name of a file that can be opened successfully. What line of code should be placed in the blank to achieve this goal? 1. done = False 2. done = True 3. done = inFile 4. done = not inFile Section 7.6 Application: Handling Input Errors Title Complete the code segment for reading a valid file name from the user type mc


79. section 7.6 Application: Handling Input Errors id testbank-py-1-ch07-66 80. Consider the following function call for computing a linear regression: result = scipy.stats.linregress(data1, data2) What is stored in result when this function call completes? 1. A Boolean value indicating whether or not the regression was completed successfully. 2. A floating point number between -1 and 1 that indicates the amount of correlation between the data sets. 3. A list containing the mean and median values of both data sets. 4. A tuple containing the slope, intercept and correlation coefficient for the data sets. Section 7.6 Application: Handling Input Errors Title What is returned when computing a linear regression? type mc section 7.6 Application: Handling Input Errors id testbank-py-2-ch07-50 81. Which type of chart can be used to represent the relationship between three dimensional data? 1. A bar chart 2. A bubble chart 3. A histogram 4. A pie chart Section 7.6 Application: Handling Input Errors Title Which type of chart can be used to represent the relationship between three dimensional data? type mc section 7.6 Application: Handling Input Errors id testbank-py-2-ch07-51 82. Consider the following code segment: line = input() try: ... if line == "": ____________________ ... except RuntimeError: print("A blank line was encountered.") This code segment is supposed to print out A blank line was encountered when a blank line is entered by the user. What code should be placed in the blank so that it will accomplish this goal?


82.

1. except RuntimeError 2. raise RuntimeError 3. RuntimeError(raise) 4. RuntimeError(except) Section 7.6 Application: Handling Input Errors Title Which statement raises an exception? type mc section 7.6 Application: Handling Input Errors id testbank-py-2-ch07-64

83. Which function is not part of the Python statistics module? 1. mean 2. median 3. stdev 4. average Section 7.6 Application: Handling Input Errors Title Which function is not part of the Python statistics module? type mc section 7.6 Application: Handling Input Errors id testbank-py-2-ch07-83


1. A set is a container that stores a collection of: 1. lists 2. unique values 3. models 4. operations Section 8.1 Sets Title What is stored in a set? type mc section 8.1 Sets id testbank-py-1-ch08-01 2. One key difference between a set and a list is: 1. Set elements are not stored in any particular order 2. List elements are not stored in any particulary order 3. Set elements can be accessed directly using their position 4. List elements only contain string values Section 8.1 Sets Title What is an example of a difference between list and set? type mc section 8.1 Sets id testbank-py-1-ch08-02 3. Which statement correctly creates a set named colors that contains the 7 colors in a rainbow? 1. colors = ["red", "orange", "yellow" "green", "blue", "indigo", "violet"] 2. colors = {red, orange, yellow, green, blue, indigo, violet} 3. colors = [red, orange, yellow, green, blue, indigo, violet] 4. colors = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"} Section 8.1 Sets Title Which statement correctly creates a set named colors that contains the 7 colors in a rainbow? type mc section 8.1 Sets id testbank-py-1-ch08-03 4. Which statement correctly creates a set named rainbow that contains the 7 colors in a rainbow? 1. colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]


4.

1. rainbow = set(colors) 2. colors = {red, orange, yellow, green, blue, indigo, violet} rainbow = colors 3. colors = [red, orange, yellow, green, blue, indigo, violet] rainbow = set(colors) 4. colors = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"} rainbow = colors.set Section 8.1 Sets Title Which statement correctly creates a set named rainbow that contains the 7 colors in a rainbow? type mc section 8.1 Sets id testbank-py-1-ch08-04

5. Which statement correctly creates an empty set flags? 1. flags = {} 2. flags = set{} 3. flags = set() 4. flags = null Section 8.1 Sets Title Which statement correctly creates an empty set flags? type mc section 8.1 Sets id testbank-py-1-ch08-05 6. Which statement correctly identifies the number of elements in the set flags? 1. numflags = flags.size() 2. numflags = flags.len() 3. numflags = len(flags) 4. numflags = size(flags) Section


6.

8.1 Sets Title Which statement correctly identifies the number of elements in the set flags? type mc section 8.1 Sets id testbank-py-1-ch08-06

7. How can you print all the elements in the set colors each on a separate line? 1. for i in range(len(colors)) : print(colors[i]) 2. for color in colors : print(color) 3. print(colors) 4. for i in range(0, len(colors)) : print(colors[i]) Section 8.1 Sets Title How can you print all elements in a set, each on a separate line? type mc section 8.1 Sets id testbank-py-1-ch08-08 8. In what order are the elements of a set visited when the set is traversed using a for loop? 1. sorted in ascending order 2. sorted in descending order 3. the order in which they were added 4. random order Section 8.1 Sets Title In what order are the elements of a set visited when the set is traversed using a for loop? type mc section 8.1 Sets id testbank-py-1-ch08-09 9. Which statement(s) below print the set colors in sorted order? 1. for i in range(len(colors)) : print(colors[i])


9.

2. for color in sorted(colors) : print(color) 3. for color in colors.sorted() : print(color) 4. for i in range(len(colors)) : print(sorted(colors[i])) Section 8.1 Sets Title How can you make sure the elements in a set are printed in sorted order? type mc section 8.1 Sets id testbank-py-1-ch08-11

10. Which of the following is a possible output after the following code snippet is executed? names = set(["Jane", "Joe", "Amy", "Lisa"]) names.add("Amber") names.add("Zoe") names.discard("Joe") print(names) 1. {'Amy', 'Lisa', 'Jane', 'Zoe', 'Amber'} 2. {'Jane', 'Joe', 'Amy', 'Lisa', 'Amber', 'Zoe'} 3. {'Jane', 'Joe', 'Amy', 'Lisa'} 4. {'Jane', 'Joe', 'Amy', 'Lisa', 'Amber'} Section 8.1 Sets Title What is printed after the following code snippet is executed? type mc section 8.1 Sets id testbank-py-1-ch08-12 11. Which of the following is a possible output after the following code snippet is executed? names = set(["Jane", "Joe", "Amy", "Lisa"]) names.add("Amber") names.add("Zoe") names.discard("Jim")


11. print(names) 1. An exception is raised 2. {'Jane', 'Lisa', 'Joe', 'Amy', 'Amber', 'Zoe'} 3. {'Amy', 'Lisa', 'Jane', 'Zoe', 'Amber'} 4. {'Jane', 'Joe', 'Amy', 'Lisa', 'Amber', 'Zoe', 'Jim'} Section 8.1 Sets Title What is printed after the following code snippet is executed? type mc section 8.1 Sets id testbank-py-1-ch08-13 12. What is printed after the following code snippet is executed? names = set(["Jane", "Joe", "Amy", "Lisa"]) names.add("Amber") names.add("Zoe") names.remove("Jim") print(names) 1. An exception is raised 2. {'Jane', 'Lisa', 'Joe', 'Amy', 'Amber', 'Zoe'} 3. {'Amy', 'Lisa', 'Jane', 'Zoe', 'Amber'} 4. {'Jane', 'Joe', 'Amy', 'Lisa', 'Amber', 'Zoe', 'Jim'} Section 8.1 Sets Title What is printed after the following code snippet is executed? type mc section 8.1 Sets id testbank-py-1-ch08-14 13. In the following code snippet, what is true about these sets? names = set(["Jane", "Joe", "Amy", "Lisa"]) names1 = set(["Joe", "Amy", "Lisa"]) names2 = set(["Jane", "Joe"]) 1. names2 is a subset of names 2. names2 is not a subset of names


13.

3. names2 is an intersection of the set names and names1 4. names2 is a union of names and names1 Section 8.1 Sets Title In the following code snippet, what is true about these sets? type mc section 8.1 Sets id testbank-py-1-ch08-16

14. Given the following code snippet, which statement tests to see if all three sets are equal? fruit = set(["apple", "banana", "grapes", "kiwi"]) fruit2 = set(["apple", "banana", "grapes", "kiwi"] fruit3 = set(["apple", "banana", "pears", "kiwi"]) 1. if fruit.equal(fruit2) and fruit.equal(fruit3) : 2. if fruit == fruit2 and fruit == fruit3 : 3. if fruit != fruit2 and fruit != fruit3 : 4. if fruit == fruit2 or fruit == fruit3 : Section 8.1 Sets Title Given the following code snippet, which statement tests to see if all three sets are equal? type mc section 8.1 Sets id testbank-py-1-ch08-18 15. What is printed by the following code snippet? fruit = set(["apple", "banana", "grapes", "kiwi"]) fruit2 = set(["apple", "banana", "grapes"]) fruit3 = set(["apple", "banana", "pears", "kiwi"]) if fruit2.issubset(fruit) : print("fruit2 is a subset of fruit") if fruit == fruit3 : print("fruit and fruit3 are equal") if fruit != fruit2 : print("fruit and fruit2 are not equal") 1. fruit2 is a subset of fruit fruit and fruit3 are equal fruit and fruit2 are not equal


15.

2. fruit2 is a subset of fruit 3. fruit2 is a subset of fruit fruit and fruit2 are not equal 4. fruit and fruit2 are not equal Section 8.1 Sets Title What is printed by the following code snippet? type mc section 8.1 Sets id testbank-py-1-ch08-19

16. What is in the set fruit after the following code snippet? fruit2 = set(["blueberry", "lemon", "grapes"]) fruit3 = set(["apple", "banana", "pears", "kiwi"]) fruit = fruit2.union(fruit3) 1. {'blueberry', 'lemon', 'grapes', 'apple', 'banana', 'pears', 'kiwi'} 2. {'blueberry', 'lemon', 'grapes'} 3. {} 4. {'apple', 'banana', 'pears', 'kiwi'} Section 8.1 Sets Title What is in the set fruit after the following code snippet? type mc section 8.1 Sets id testbank-py-1-ch08-21 17. What method can be used to combine two sets in Python? 1. subset() 2. union() 3. join() 4. both()


17. Section 8.1 Sets Title What method can be used to combine two sets in Python? type mc section 8.1 Sets id testbank-py-1-ch08-22 18. What method is used to test if one set is contained entirely within another set in Python? 1. issubset() 2. isintersection() 3. inboth() 4. difference() Section 8.1 Sets Title What method is used to test if one set is contained entirely within another set in Python? type mc section 8.1 Sets id testbank-py-1-ch08-23 19. What method is used to produce a new set with the elements that are contained in both sets? 1. subset() 2. intersection() 3. inboth() 4. difference() Section 8.1 Sets Title What method is used to produce a new set with the elements that are contained in both sets? type mc section 8.1 Sets id testbank-py-1-ch08-24 20. What method is used to produce a new set with the elements that belong to the first set but not the second? 1.


20.

1. subset() 2. intersection() 3. inboth() 4. difference() Section 8.1 Sets Title What method is used to produce a new set with the elements that belong to the first set but not the second? type mc section 8.1 Sets id testbank-py-1-ch08-25

21. What is the output of the following code snippet? fibonacci = {1, 1, 2, 3, 5, 8} primes = {2, 3, 5, 7, 11} both = fibonacci.intersection(primes) print(both) 1. {1, 2, 3, 5, 8} 2. {1, 2, 3, 5, 7, 8, 11} 3. {2, 3, 5} 4. {} Section 8.1 Sets Title What is the output of the following code snippet? type mc section 8.1 Sets id testbank-py-1-ch08-26 22. What is the output of the following code snippet? fibonacci = {1, 1, 2, 3, 5, 8} primes = {2, 3, 5, 7, 11} both = fibonacci.union(primes) print(both) 1. {1, 2, 3, 5, 8} 2.


22.

2. {1, 2, 3, 5, 7, 8, 11} 3. {2, 3, 5} 4. {} Section 8.1 Sets Title What is the output of the following code snippet? type mc section 8.1 Sets id testbank-py-1-ch08-27

23. Which statement creates an empty set and stores it in x? 1. x = () 2. x = [] 3. x = {} 4. x = set() Section 8.1 Sets Title Which statement creates an empty set? type mc section 8.1 Sets id testbank-py-1-ch08-29 24. What is the value of x after the following code segment executes? x = {1, 2, 3} x.add(1) 1. {1, 2, 3} 2. {1, 1, 2, 3} 3. {} 4. x has no value because a runtime error occurs Section 8.1 Sets Title Trace code that adds to a set type mc section 8.1 Sets id testbank-py-1-ch08-31 25. Assume that x is initially the set {1, 2, 3}. Which statement results in x being the empty set? 1. x.discard()


25.

2. x.remove(1, 2, 3) 3. x.clear() 4. x.empty() Section 8.1 Sets Title What statement results in an empty set? type mc section 8.1 Sets id testbank-py-1-ch08-32

26. What is the value of x after the following code segment executes? x = {1, 2, 3} x.discard(4) 1. {} 2. {1, 2, 3} 3. {1, 2, 3, 4} 4. The program terminates with a runtime error Section 8.1 Sets Title Trace code that involving the discard method type mc section 8.1 Sets id testbank-py-1-ch08-33 27. Consider the following code segment: primes = {2, 3, 5, 7} odds = {1, 3, 5, 7} Which line of code will result in x containing {1, 2, 3, 5, 7}? 1. x = primes.difference(odds) 2. x = primes.intersection(odds) 3. x = primes.merge(odds) 4. x = primes.union(odds) Section 8.1 Sets Title Which line of code stores the desired set into x? type mc section 8.1 Sets id testbank-py-1-ch08-35


28. What is stored in x at the end of this code segment? primes = {2, 3, 5, 7} odds = {1, 3, 5, 7} x = primes.intersection(odds) 1. {} 2. {1, 2} 3. {3, 5, 7} 4. {1, 2, 3, 5, 7} Section 8.1 Sets Title Trace code involving set intersection type mc section 8.1 Sets id testbank-py-1-ch08-36 29. Consider the following code segment: primes = {2, 3, 5, 7} odds = {1, 3, 5, 7} Which line of code will result in x containing {1}? 1. x = odds.difference(primes) 2. x = odds.intersection(primes) 3. x = primes.difference(odds) 4. x = primes.intersection(odds) Section 8.1 Sets Title Which line of code stores the desired set into x? type mc section 8.1 Sets id testbank-py-1-ch08-37 30. What method is used to remove elements from a set? 1. clear() 2. delete() 3. discard() 4. drop() Section 8.1 Sets Title


30. What method is used to remove elements from a set? type mc section 8.1 Sets id testbank-py-1-ch08-69 31. Which of the following is NOT true about sets? 1. a set has operations available for use such as union, difference, and intersection 2. in a set, elements cannot be accessed by position 3. in a set, elements are stored in the order they are added 4. set operations are much faster than the equivalent list operations Section 8.1 Sets Title Which of the following is NOT true about sets? type mc section 8.1 Sets id testbank-py-1-ch08-71 32. What method is used to remove all elements from a set? 1. clear() 2. delete() 3. discard() 4. drop() Section 8.1 Sets Title What method is used to remove all elements from a set? type mc section 8.1 Sets id testbank-py-1-ch08-72 33. Which statement determines if set x is a proper subset of set y? 1. x.issubset(y) 2. x.issubset(y) and x != y 3. x.issubset(y) and x == y 4. x == y


33.

Section 8.1 Sets Title Which statement determines if set x is a proper subset of set y? type mc section 8.1 Sets id testbank-py-1-ch08-73

34. How can you make sure the elements in a set will be printed in sorted order? 1. Add the elements to the set in sorted order before printing the set 2. Use the in operator before printing the set 3. Use the sort method before printing the set 4. Use the sorted function when printing the set Section 8.1 Sets Title How can you make sure the elements in a set are printed in sorted order? type mc from testbank-py-1-ch08-10 section 8.1 Sets id testbank-py-2-ch08-10 35. What is printed when the following code snippet executes? names = set(["Jane", "Joe", "Amy", "Lisa"]) names.add("Amber") names.add("Zoe") names.clear() print(names) 1. An error message indicating that an exception was raised. 2. {'Jane', 'Lisa', 'Joe', 'Amy', 'Amber', 'Zoe'} 3. {'Amy', 'Lisa', 'Jane', 'Zoe', 'Amber'} 4. set() Section 8.1 Sets Title What is printed by a code snippet involving sets? type mc from testbank-py-1-ch08-15 section 8.1 Sets


35. id testbank-py-2-ch08-15 36. Given the following code snippet, which statement tests to see if names2 is a subset of names? names = set(["Jane", "Joe", "Amy", "Lisa"]) names2 = set(["Jane", "Joe"]) 1. if names2.issubset(names) : print(names2) 2. if names2 isA subset(names) : print(names2) 3. if names2.subset(names) : print(names2) 4. if names.subset(names2) : print(names2) Section 8.1 Sets Title Which statement tests to see if one set is a subset of another set? type mc from testbank-py-1-ch08-17 section 8.1 Sets id testbank-py-2-ch08-17 37. Consider the following code segment: names = set(["Jane", "Joe", "Amy", "Lisa"]) names1 = set(["Joe", "Amy", "Lisa", "Bob"]) names2 = set(["Joe", "Amy", "Lisa"]) Which of the following statements is true? 1. names1 is a subset of names 2. names2 is a subset of names 3. names is the intersection of the sets names1 and names2 4. names is the union of names1 and names2 Section 8.1 Sets Title Which of the follow statements about sets is true? type mc from testbank-py-1-ch08-20 section


37. 8.1 Sets id testbank-py-2-ch08-20 38. What values will be in the set both after the following code snippet runs? fibonacci = {1, 1, 2, 3, 5, 8} primes = {2, 3, 5, 7, 11} both = fibonacci.difference(primes) print(both) 1. 2, 3, 5, 7, 11 2. 1, 2, 3, 5, 7, 8, 11 3. 1, 8 4. None (the set is empty) Section 8.1 Sets Title What is the output of the following code snippet involving a set difference operation? type mc from testbank-py-1-ch08-28 section 8.1 Sets id testbank-py-2-ch08-28 39. Which statement creates a set of 3 elements and stores it in x? 1. x = [1, 2, 3] 2. x = {1, 2, 3} 3. x = (1, 2, 3) 4. x = set(1, 2, 3) Section 8.1 Sets Title Which statement creates a set of 3 elements? type mc from testbank-py-1-ch08-30 section 8.1 Sets id testbank-py-2-ch08-30 40. Consider the following code segment: primes = {2, 3, 5, 7} odds = {1, 3, 5, 7} x = primes.issubset(odds) What value will be stored in x after it has executed? 1. 0


40.

2. 1 3. False 4. True Section 8.1 Sets Title Trace code involving the issubset method type mc from testbank-py-1-ch08-34 section 8.1 Sets id testbank-py-2-ch08-34

41. Which statement about lists and sets is correct? 1. In a list the elements are stored in order. In a set they are not stored in any particular order. 2. In both a set and a list, the elements can be accessed by position. 3. Both sets and lists have methods for computing the union, difference and intersection of two containers. 4. List operations are much faster than the equivalent set operations. Section 8.1 Sets Title Which statement about lists and sets is correct? type mc from testbank-py-1-ch08-70 section 8.1 Sets id testbank-py-2-ch08-70 42. Which of the following code segments prints red is a color of the rainbow when the set colors contains the string "red"? 1. if colors contains "red" : print("red is a color of the rainbow") 2. if "red" in colors : print("red is a color of the rainbow") 3. if "red" not in colors : print("red is a color of the rainbow") 4. if colors includes "red" : print("red is a color of the rainbow") Section 8.1 Sets Title How can you search for an element in a set? type


42.

mc from testbank-py-1-ch08-07 section 8.1 Sets id testbank-py-2-ch08-07

43. Which of the following statements creates a dictionary of favorite foods? 1. favoriteFoods = {"burgers", "hotdogs", "apple pie"} 2. favoriteFoods = {"Peg": "burgers", "Cy": "hotdogs", "Bob": "apple pie"} 3. favoriteFoods = {"Peg", "Cy", "Bob" : "burgers", "hotdogs", "apple pie"} 4. favoriteFoods = {"Peg", "burgers", "Cy", "hotdogs", "Bob", "apple pie"} Section 8.2 Dictionaries Title Which of the following statements creates a dictionary of favorite foods? type mc section 8.2 Dictionaries id testbank-py-1-ch08-39 44. Which operator tests to see if a key exists in a dictionary? 1. in 2. contains 3. has 4. issubset Section 8.2 Dictionaries Title Which operator tests to see if a key exists in a dictionary? type mc section 8.2 Dictionaries id testbank-py-1-ch08-44 45. How do you add items to a dictionary? 1. add method 2. [] operator 3. {} operator 4. insert method Section 8.2 Dictionaries Title


45. How do you add items to a dictionary? type mc section 8.2 Dictionaries id testbank-py-1-ch08-46 46. How do you remove items from a dictionary? 1. remove method 2. pop method 3. delete method 4. get method Section 8.2 Dictionaries Title How do you remove items from a dictionary? type mc section 8.2 Dictionaries id testbank-py-1-ch08-48 47. What is printed by the following code segment? x = dict() print(x) 1. {} 2. dict() 3. Nothing is printed 4. The program terminates with a runtime error Section 8.2 Dictionaries Title Trace code involving a dictionary type mc section 8.2 Dictionaries id testbank-py-1-ch08-51 48. Which of the following statements creates a dictionary with 4 entries? 1. x = {4} 2. x = dict(4) 3. x = {"A": 1, "B": 2} 4. x = {"A": 1, "B": 2, "C": 3, "D": 4} Section 8.2 Dictionaries Title Which statement creates a dictionary with 4 keys? type


48. mc section 8.2 Dictionaries id testbank-py-1-ch08-52 49. What are the keys in the following dictionary? fruit = {"Apple": "Green", "Banana": "Yellow"} 1. Apple and Banana 2. Green and Yellow 3. Apple, Green, Banana and Yellow 4. The dictionary does not have any keys Section 8.2 Dictionaries Title What are the keys in a dictionary? type mc section 8.2 Dictionaries id testbank-py-1-ch08-53 50. What are the values in the following dictionary? numbers = {1: 5.5, 2.0: 77, 3: 33} 1. 1, 2.0 and 3 2. 5.5, 77 and 33 3. 1, 77, 3 and 33 4. 1, 5.5, 2.0, 77, 3 and 33 Section 8.2 Dictionaries Title What are the values in a dictionary? type mc section 8.2 Dictionaries id testbank-py-1-ch08-54 51. Consider the following code segment: fruit = {"Apple": "Green", "Banana": "Yellow"} fruit["Plum"] = "Purple" After it executes, what is the value of fruit? 1. {"Apple": "Green", "Banana": "Yellow"} 2. {"Apple": "Green", "Banana": "Yellow", "Plum": "Purple"} 3. {"Apple": "Green", "Banana": "Yellow", "Purple": "Plum"} 4. The fruit dictionary has no value because the program terminates with a runtime error Section 8.2 Dictionaries


51. Title Trace code that uses the subscript operator on a dictionary type mc section 8.2 Dictionaries id testbank-py-1-ch08-55 52. Consider the following code segment: fruit = {"Apple": "Green", "Banana": "Yellow"} fruit["Apple"] = "Red" After it executes, what is the value of fruit? 1. {"Apple": "Green", "Banana": "Yellow"} 2. {"Apple": "Red", "Banana": "Yellow"} 3. {"Apple": "Green", "Banana": "Yellow", "Apple": "Red"} 4. The fruit dictionary has no value because the program terminates with a runtime error Section 8.2 Dictionaries Title Trace code that uses the subscript operator on a dictionary type mc section 8.2 Dictionaries id testbank-py-1-ch08-56 53. Which of the following statements checks to see if the key Apple is already in the dictionary fruit? 1. if "Apple" in fruit : 2. if "Apple".in(fruit) : 3. if fruit in "Apple" : 4. if fruit.contains("Apple") : Section 8.2 Dictionaries Title Which statement checks to see if a key is in the dictionary? type mc section 8.2 Dictionaries id testbank-py-1-ch08-57 54. Assume that a dictionary has been initialized as shown below: fruit = {"Apple": "Green", "Banana": "Yellow", "Plum": "Purple"} Which statement prints the color of a banana? 1. print(fruit."Banana") 2. print(fruit["Banana"]) 3. print(fruit{"Banana"})


54.

4. print(fruit("Banana")) Section 8.2 Dictionaries Title Which statement displays a value in the dictionary? type mc section 8.2 Dictionaries id testbank-py-1-ch08-58

55. What is in the fruit dictionary after the following code segment executes? fruit = {"Apple": "Green", "Banana": "Yellow", "Plum": "Purple"} fruit.pop("Banana") 1. {"Apple": "Green", "Plum": "Purple"} 2. {"Apple": "Green", "Banana", "Plum": "Purple"} 3. {"Apple": "Green", "Yellow", "Plum": "Purple"} 4. There is no value in fruit because the program terminates with a runtime error Section 8.2 Dictionaries Title Removing an element from a dictionary type mc section 8.2 Dictionaries id testbank-py-1-ch08-59 56. Which code segment prints only the values stored in the fruit dictionary? 1. for item in fruit : print(item) 2. for item in fruit.items() : print(item) 3. for item in fruit.keys() : print(item) 4. for item in fruit.values() : print(item) Section 8.2 Dictionaries Title Which code segment prints only the values stored in a dictionary? type mc section 8.2 Dictionaries


56.

id testbank-py-1-ch08-60

57. Which statement correctly creates a dictionary for converting numbers 1 through 5 to roman numerals? 1. numerals = {[1, "I"], [2, "II"], [3, "III"], [4, "IV"], [5, "V"]} 2. numerals = [1: "I", 2: "II", 3: "III", 4: "IV", 5: "V"] 3. numerals = (1: "I", 2: "II", 3: "III", 4: "IV", 5: "V") 4. numerals = {1: "I", 2: "II", 3: "III", 4: "IV", 5: "V"} Section 8.2 Dictionaries Title Which statement correctly creates a dictionary for converting numbers 1 through 5 to roman numerals? type mc section 8.2 Dictionaries id testbank-py-1-ch08-74 58. What is the difference between a list and a dictionary? 1. a list is a subset of a dictionary 2. a dictionary can access elements by position 3. a list stores individual elements but a dictionary stores key/value pairs 4. list operations are much faster than the equivalent dictionary operations Section 8.2 Dictionaries Title What is the difference between a list and a dictionary? type mc section 8.2 Dictionaries id testbank-py-1-ch08-75 59. Which statement is most correct? 1. A Python dictionary contains a list of all of Python's reserved words. 2. A Python dictionary stores associations between keys and values. 3. Each value in a Python dictionary must be unique. 4. Every value in a Python dictionary must have the same data type. Section 8.2 Dictionaries Title Which statement about Python dictionaries is most correct? type mc from testbank-py-1-ch08-38 section 8.2 Dictionaries


59. id testbank-py-2-ch08-38 60. Which of the following statements creates a duplicate copy of the favoriteFoods dictionary? 1. favoriteFoods2 = copy(favoriteFoods) 2. favoriteFoods2 = dict(favoriteFoods) 3. favoriteFoods2 = duplicate(favoriteFoods) 4. favoriteFoods2 = favoriteFoods Section 8.2 Dictionaries Title Which statement creates a duplicate copy of a dictionary? type mc from testbank-py-1-ch08-40 section 8.2 Dictionaries id testbank-py-2-ch08-40 61. Consider the following dictionary: favoriteFoods = {"Peg": "burgers", "Cy": "hotdogs", "Bob": "apple pie"} What statement will print Peg's favorite food? 1. print("Peg's favorite food is: ", favoriteFoods.get(1)) 2. print("Peg's favorite food is: ", favoriteFoods(Peg)) 3. print("Peg's favorite food is: ", favoriteFoods["Peg"]) 4. print("Peg's favorite food is: ", favoriteFoods[1]) Section 8.2 Dictionaries Title What statement prints a value stored in a dictionary? type mc from testbank-py-1-ch08-41 section 8.2 Dictionaries id testbank-py-2-ch08-41 62. How can you access a value stored in a dictionary? 1. A value can only be accessed using a sequential search 2. A value can only be accessed using its associated key 3. A value can only be accessed using its index 4. A value can only be accessed using the in operator Section 8.2 Dictionaries Title How can you access a value stored in a dictionary? type mc


62. from testbank-py-1-ch08-42 section 8.2 Dictionaries id testbank-py-2-ch08-42 63. Consider the following code segment: data = {"A": 65, "B": 66, "C": 67} print(data["Z"]) What will be displayed when this code segment executes? 1. -1 2. 0 3. {} 4. An error message indicating that an exception was raised. Section 8.2 Dictionaries Title What happens when you try to read from a key that is not present in a dictionary? type mc from testbank-py-1-ch08-43 section 8.2 Dictionaries id testbank-py-2-ch08-43 64. Which of the following statements stores seafood in the food variable if Joe is not a key in the favoriteFoods dictionary? 1. food = favoriteFoods.get("Joe", "seafood") 2. food = favoriteFoods.get(["Joe"], "seafood") 3. food = favoriteFoods(["Joe"], "seafood") 4. food = favoriteFoods.get("seafood", "Joe") Section 8.2 Dictionaries Title Which statement returns a default value when attempting to retrieve a value for a key that is not present in a dictionary? type mc from testbank-py-1-ch08-45 section 8.2 Dictionaries id testbank-py-2-ch08-45 65. You are creating a program that includes a dictionary where the keys are people's names and the values are their favorite foods. Which of the following statements adds an entry to the dictionary that indicates that Ravi's favorite food is chocolate? 1. favoriteFoods["Ravi"] = "chocolate"


65.

2. favoriteFoods.add("Ravi", "chocolate") 3. favoriteFoods = {"Ravi", "chocolate"} 4. favoriteFoods["Ravi"] = "chocolate" Section 8.2 Dictionaries Title How do you add an item to a dictionary? type mc from testbank-py-1-ch08-47 section 8.2 Dictionaries id testbank-py-2-ch08-47

66. Which of the following code segments displays the favoriteFoods dictionary in alphabetical order by name? favoriteFoods = {"Peg": "burgers", "Cy": "hotdogs", "Bob": "apple pie"} 1. print(favoriteFoods) 2. for name in sorted(favoriteFoods) : print(name, favoriteFoods[name]) 3. for name in (favoriteFoods) : print(name, favoriteFoods[name]) 4. for name in favoriteFoods.sort() : print(name, favoriteFoods[name]) Section 8.2 Dictionaries Title Which of the code segments displays a dictionary in alphabetical order by key? type mc section 8.2 Dictionaries id testbank-py-1-ch08-49 67. Which code segment creates a dictionary with keys that are integers and values that are lists? 1. cards = dict() cards.add("Ace", "Spades", 1) cards.add("Two", "Spades", 2) 2. cards = dict() cards[1] = ["Ace", "Spades"] cards[2] = ["Two", "Spades"] 3. cards = dict()


67.

3. cards = {"Ace", "Spades", 1) cards = {"Two", "Spades", 2) 4. cards = dict() cards.put("Ace", "Spades", 1) cards.put("Two", "Spades", 2) Section 8.2 Dictionaries Title Which code segment creates a dictionary with keys that are integers and values that are lists? type mc from testbank-py-1-ch08-50 section 8.2 Dictionaries id testbank-py-2-ch08-50

68. What is returned by a dictionary's items method? 1. A list of integers 2. A sequence of tuples 3. A set of floating point numbers 4. A string Section 8.2 Dictionaries Title What is returned by a dictionary's items method? type mc section 8.2 Dictionaries id testbank-py-2-ch08-80 69. Consider the following code segment: data = {"A": 65, "B": 66, "C": 67} data["D"] = 68 print(len(data)) What is displayed when this code segment is executed? 1. 3 2. 4 3. 6 4. 8 Section 8.2 Dictionaries Title What is displayed by a code segment involving a dictionary and the len function? type mc section 8.2 Dictionaries id


69. testbank-py-2-ch08-81 70. What structure should be used to store a collection of unique values when the order of the elements is not important? 1. A dictionary 2. A list 3. A set 4. A string Section 8.2 Dictionaries Title What structure should be used to store a collection of unique values when the order of the elements is not important? type mc section 8.2 Dictionaries id testbank-py-2-ch08-81 71. Which of the following code segments creates a dictionary of lists? 1. days = {} days["February"] = 28, 29 2. days = {} days["February"] = (28, 29) 3. days = {} days["February"] = [28, 29] 4. days = {} days["February"] = {28, 29} Section 8.3 Complex Structures Title Which code segment creates a dictionary of lists? type mc section 8.3 Complex Structures id testbank-py-1-ch08-63 72. What does the following code segment display? data = {"Jan": 31, "Feb": [28, 29], "Mar", 31} print(data["Jan"][0]) 1. 3 2. 31 3. J 4. The program raises an exception


72. Section 8.3 Complex Structures Title Trace code involving a complex structure type mc section 8.3 Complex Structures id testbank-py-1-ch08-64 73. What does the following code segment display? data = {"Jan": 31, "Feb": [28, 29], "Mar", 31} print(data["Feb"][0]) 1. 2 2. 28 3. 29 4. The program raises an exception Section 8.3 Complex Structures Title Trace code involving a complex structure type mc section 8.3 Complex Structures id testbank-py-1-ch08-65 74. Assume that you have created a function named drawBarGraph for displaying bar graphs, and that you have stored it in a source file named bargraph.py. How should you import this function into another program so that it can be used as shown below: bargraph.drawBarGraph(data) 1. import bargraph 2. import bargraph.py 3. from bargraph import drawBarGraph 4. from bargrapy.py import drawBarGraph Section 8.3 Complex Structures Title How do you import a function from another source file? type mc section 8.3 Complex Structures id testbank-py-1-ch08-66 75. Consider the following code segment: pets = {}


75. pets["Snowball"] = {77, 4.5, "Cat"} pets["Spike"] = {132, 23.1, "Dog"} The complex structure pets would best be characterized as: 1. A dictionary of dictionaries 2. A dictionary of lists 3. A dictionary of sets 4. A dictionary of strings Section 8.3 Complex Structures Title Characterize a complex structure type mc section 8.3 Complex Structures id testbank-py-1-ch08-67 76. Consider the following code segment: x = {} x["Hello"] = [4, 5] x["Hello"].append("World") print(x["Hello"]) What is displayed when it is executed? 1. Hello 2. HelloWorld 3. [4, 5] 4. [4, 5, "World"] Section 8.3 Complex Structures Title Trace code involving appending to a complex structure type mc section 8.3 Complex Structures id testbank-py-1-ch08-68 77. Consider the following scenario. You have many friends, each of whom has several phone numbers (home, work, cell, and perhaps others). You want to create a phone book program that stores all of this data. Which of the following data structures would be best suited to this task? 1. a dictionary of lists 2. a list of lists 3. a list of strings 4. a set of integers Section 8.3 Complex Structures Title What type of container or structure best solves the given scenario? type mc section


77. 8.3 Complex Structures id testbank-py-1-ch08-61

78. Consider the following problem: A grocery store carries a wide variety of products that fall into broad categories such as fruit, milk and toys. Each category contains many items. For example, the fruit category contains items like apples, oranges and bananas while the milk category contains items like skim, 2% and chocolate, and the toys category includes items like balls, dolls and trucks. A program for the grocery store needs to be able to add new items to a category, remove items from a category and display all of the items in a category. The order in which the items are displayed is not important. Which container or structure best solves this problem? 1. a dictionary of sets 2. a dictionary of strings 3. a list of strings 4. a set of strings Section 8.3 Complex Structures Title What type of container or structure best solves the given scenario? type mc from testbank-py-1-ch08-62 section 8.3 Complex Structures id testbank-py-2-ch08-62 79. What can specify the address of a web application and the arguments that must be supplied to get it to produce the desired result? 1. The Application Programming Interface (API) 2. The Computing Resource Allocator (CRA) 3. The Global Representation of External Programs (GREP) 4. The Python Programming Principles (PPP) Section 8.3 Complex Structures Title What specifies the address of a web application and the arguments that must be supplied to get it to produce the desired result? type mc section 8.3 Complex Structures id testbank-py-2-ch08-76 80. What plain text format is commonly used to exchange data between a Python program and a web application? 1. BitMap Protocol (BMP) 2. Internet Handshake Format (IHF) 3. JavaScript Object Notation (JSON) 4. Python to Python Protocol (PPP)


80. Section 8.3 Complex Structures Title What plain text format is commonly used to exchange data between a Python program and a web application? type mc section 8.3 Complex Structures id testbank-py-2-ch08-77 81. What is the purpose of the loads function in the json module? 1. The loads function converts from JSON format to a Python dictionary. 2. The loads function creates a string that can be sent to the web application to request additional data. 3. The loads function reads data from a file stored on the same computer as the Python program. 4. The loads function retrieves data from a web application. Section 8.3 Complex Structures Title What is the purpose of the loads function in the json module? type mc section 8.3 Complex Structures id testbank-py-2-ch08-78 82. What character is used to separate the address from the arguments in a URL? 1. + 2. ? 3. , 4. : Section 8.3 Complex Structures Title What character is used to separate the address from the arguments in a URL? type mc section 8.3 Complex Structures id testbank-py-2-ch08-79 83. Which of the following statements is not true? 1. Splitting a large program into multiple files can make it easier to debug the program. 2. Splitting a large program into multiple files can make the program run more quickly. 3. Splitting a large program into multiple files can make it easier for multiple programmers to work on the program at the same time. 4. Splitting a large program into multiple files can make it easier to test the program. Section 8.3 Complex Structures Title


83. Why is it beneficial to split a large program into multiple files? type mc section 8.3 Complex Structures id testbank-py-2-ch08-81


1. Which of the following is considered by the text to be the most important consideration when designing a class? 1. Each class should represent an appropriate mathematical concept. 2. Each class should represent a single concept or object from the problem domain. 3. Each class should represent no more than three specific concepts. 4. Each class should represent multiple concepts only if they are closely related. Section 9.1 Object-Oriented Programming Title Which of the following is considered by the text to be the most important consideration when designing a class? type mc section 9.1 Object-Oriented Programming id testbank-py-1-ch09-01 2. Which of the following questions should you ask yourself in order to determine if you have named your class properly? 1. Does the class name contain 8 or fewer characters? 2. Is the class name a verb? 3. Can I visualize an object of the class? 4. Does the class name describe the tasks that this class will accomplish? Section 9.1 Object-Oriented Programming Title How do I ensure I have named a class properly? type mc section 9.1 Object-Oriented Programming id testbank-py-1-ch09-02 3. Which statement is NOT a description of encapsulation? 1. The act of hiding the implementation details 2. A collection of methods through which the objects of the class can be manipulated 3. Enables changes in the implementation without affecting users of a class 4. Mechanism for restricting access to some of the object's components Section 9.1 Object-Oriented Programming Title Which statement best describes the public interface for a class? type mc section 9.1 Object-Oriented Programming id testbank-py-1-ch09-06 4. Which of the following statements is not legal? 1. ["Hello", "World"].lower() 2. "Hello, World".lower() 3. ["Hello", "World"].pop() 4. ["Hello, World"].pop()


4. Section 9.1 Object Oriented Programming Title Which statement is not legal? type mc section 9.1 Object-Oriented Programming id testbank-py-1-ch09-07 5. Which of the following is NOT a true statement regarding object-oriented programming? 1. Object oriented programming views the program as a list of tasks to perform. 2. Object oriented programs usually contain different types of objects, each corresponding to a particular kind of complex data, real-world object or concept. 3. Object oriented programming is a style where tasks are solved by collaborating objects. 4. Object oriented programs are organized around "objects" rather than "actions" and "data" rather than "logic". Section 9.1 Object-Oriented Programming Title Which of the following is NOT a true statement regarding object-oriented programming? type mc from testbank-py-1-ch09-03 section 9.1 Object-Oriented Programming id testbank-py-2-ch09-03 6. Which statement about classes is true? 1. A class contains data and methods that act upon that data. 2. A class decomposes tasks into functions. 3. A class describes a set of objects with different behaviors. 4. A class describes a set of objects that all have the same behavior. Section 9.1 Object-Oriented Programming Title Which statement about classes is true? type mc from testbank-py-1-ch09-04 section 9.1 Object-Oriented Programming id testbank-py-2-ch09-04 7. Which statement is correct about the public interface for a class? 1. The public interface for a class is a description of its class variables, and the types of information they are supposed to store. 2. The public interface for a class is the set of all methods provided by a class, together with a description of their behavior. 3. The public interface for a class is the set of all its methods, along with the code in the method bodies. 4. The public interface for a class is the name of the class without any additional information.


7. Section 9.1 Object-Oriented Programming Title Which statement is correct about the public interface for a class? type mc from testbank-py-1-ch09-05 section 9.1 Object-Oriented Programming id testbank-py-2-ch09-05 8. What is the purpose of an object's instance variables? 1. Store the data required for executing its methods 2. Store the data for all objects created by the same class 3. To provide access to the data of an object 4. To create variables with public visibility Section 9.2 Implementing a Simple Class Title What is the purpose of an object's instance variables? type mc section 9.2 Implementing a Simple Class id testbank-py-1-ch09-08 9. Naming conventions for Python dictate that instance variables should start with an underscore to represent: 1. public visibility 2. private visibility 3. encapsulation 4. public interface Section 9.2 Implementing a Simple Class Title Why do instance variables start with an underscore? type mc section 9.2 Implementing a Simple Class id testbank-py-1-ch09-09 10. What is the purpose of a method? 1. Enables changes in the implementation without affecting users of a class 2. To access the instance variables of the object on which it acts 3. Store the data for all objects created by the same class 4. Provide comments about the program implementation Section 9.2 Implementing a Simple Class Title What is the purpose of a method? type


10. mc section 9.2 Implementing a Simple Class id testbank-py-1-ch09-11 11. What is the purpose of the self parameter? 1. Enables changes in the implementation without affecting users of a class 2. To create variables with public visibility 3. Store the data for all objects created by the same class 4. Refers to the object on which the method was invoked Section 9.2 Implementing a Simple Class Title What is the purpose of the self parameter? type mc section 9.2 Implementing a Simple Class id testbank-py-1-ch09-13 12. According to the textbook, what is the best practice for updating instance variables? 1. Directly access the variables 2. Restrict access to instance variables, only allow updates through methods 3. Restrict access to instance variables, only allow updates through functions 4. Provide both direct and indirect access to instance variables Section 9.2 Implementing a Simple Class Title According to the textbook, what is the best practice for updating instance variables? type mc section 9.2 Implementing a Simple Class id testbank-py-1-ch09-14 13. Assume a class exists named Fruit. Which of the follow statements constructs an object of the Fruit class? 1. def Fruit() : 2. class Fruit() : 3. x = Fruit() 4. x = Fruit.create() Section 9.2 Implementing a Class Title Which statement creates an object? type mc section 9.2 Implementing a Simple Class id testbank-py-1-ch09-16


14. Which of the following statements is used to begin the implementation of a new class named Fruit? 1. class Fruit : 2. def Fruit : 3. object Fruit : 4. x = Fruit() Section 9.2 Implementing a Simple Class Title Which statement is used to begin the implementation of a new class? type mc section 9.2 Implementing a Simple Class id testbank-py-1-ch09-17 15. What is the name of the instance variable in the following code segment? class Fruit : def getColor(self) : return self._color 1. _color 2. Fruit 3. getColor 4. self Section 9.2 Implementing a Simple Class Title What is the name of the instance variable in the following code segment? type mc section 9.2 Implementing a Simple Class id testbank-py-1-ch09-18 16. What is the name of the method in the following code segment? class Fruit : def getColor(self) : return self._color 1. _color 2. Fruit 3. getColor 4. self Section 9.2 Implementing a Simple Class Title What is the name of the method in the following code segment? type mc section 9.2 Implementing a Simple Class


16. id testbank-py-1-ch09-19 17. How many methods are there in the following class? class Person : def getName(self) : return self._name def getSalary(self) : return self._salary def giveRaise(self, howMuch) : self._salary = self._salary + howMuch 1. 0 2. 1 3. 2 4. 3 Section 9.2 Implementing a Simple Class Title How many methods are there in a class? type mc section 9.2 Implementing a Simple Class id testbank-py-1-ch09-20 18. Consider the following class: class Counter : def getValue(self) : return self._value def click(self) : self._value = self._value + 1 def unClick(self) : self._value = self._value - 1 def reset(self) : self._value = 0 Which method creates a new instance variable? 1. click 2. getValue 3. reset 4. unClick Section 9.2 Implementing a Simple Class


18. Title Which method creates a new instance variable? type mc section 9.2 Implementing a Simple Class id testbank-py-1-ch09-21 19. The following two objects are created from the Counter class: studentCounter, and teacherCounter to represent the total number of students and the total number of teachers respectively. If the Counter class contains an instance variable, _num, that is initialized to zero and increases every time the user executes the add method, what is stored in each object's instance variable after the following code snippet executes? studentCounter.add() teacherCounter.add() studentCounter.add() 1. studentCounter : 3, teacherCounter : 3 2. studentCounter : 2, teacherCounter : 1 3. studentCounter : 1, teacherCounter : 2 4. studentCounter : 1, teacherCounter : 1 Section 9.2 Implementing a Simple Class Title What are the values of two instance variables after the given code snippet is executed? type mc from testbank-py-1-ch09-10 section 9.2 Implementing a Simple Class id testbank-py-2-ch09-10 20. Which of the following is NOT a difference between methods and functions? 1. A method is defined within a class. A function is defined outside of a class. 2. A function is defined within a class. A method is defined outside of a class. 3. The first parameter variable for a method is self. Functions do not have a self parameter variable. 4. A method can access the instance variables of an object. A function cannot. Section 9.2 Implementing a Simple Class Title Which of the following is NOT a difference between methods and functions? type mc from testbank-py-1-ch09-12 section 9.2 Implementing a Simple Class id testbank-py-2-ch09-12 21. Suppose you have a class ShoppingList, with instance variables _quantity, _cost, and _itemName. How


21. should you access these variables when writing code that is not contained within the ShoppingList class? 1. Directly access the instance variables by using the object and the instance variables' names. 2. Use methods provided by the ShoppingList class. 3. It is not possible to access the instance variables outside of the ShoppingList class. 4. Use the self parameter followed by the instance variables' names. Section 9.2 Implementing a Simple Class Title How should you access instance variables in your program? type mc section 9.2 Implementing a Simple Class id testbank-py-1-ch09-15 22. When designing a class, what is one of the first tasks that need to be done? 1. Defining the instance variables 2. Writing the method headers 3. Specifying the public interface 4. Adding comments to your program Section 9.3 Specifying the Public Interface of a Class Title When designing a class, what is one of the first tasks that need to be done? type mc section 9.3 Specifying the Public Interface of a Class id testbank-py-1-ch09-28 23. What items should be considered when creating the public interface? 1. Method headers and method comments 2. Instance variables 3. Data and method bodies 4. Method implementations Section 9.3 Specifying the Public Interface of a Class Title What items should be considered when creating the public interface? type mc section 9.3 Specifying the Public Interface of a Class id testbank-py-1-ch09-29 24. Before invoking a method on an object, what must be done first? 1. Initialize all instance variables 2. Invoke the accessor and mutator methods 3. Create a public interface 4. Construct the object Section 9.3 Specifying the Public Interface of a Class


24. Title Before invoking a method on an object, what must be done first? type mc section 9.3 Specifying the Public Interface of a Class id testbank-py-1-ch09-30 25. Which method below would be considered an accessor method? 1. getCount() 2. addItem() 3. clearCount() 4. updateItem() Section 9.3 Specifying the Public Interface of a Class Title Which method below would be considered an accessor method? type mc section 9.3 Specifying the Public Interface of a Class id testbank-py-1-ch09-31 26. Which method below would be considered a mutator method? 1. getCount() 2. addItem() 3. getTotal() 4. printItem() Section 9.3 Specifying the Public Interface of a Class Title Which method below would be considered an mutator method? type mc section 9.3 Specifying the Public Interface of a Class id testbank-py-1-ch09-32 27. Consider the following class: class Fruit :

# Line 1


27.

def getColor(self) : # Line 2 retval = self._color # Line 3 return retval # Line 4 Which line(s) are part of the public interface for the class? 1. Only line 1 2. Only line 2 3. Only lines 2 and 3 4. Only lines 3 and 4 Section 9.3 Specifying the Public Interface of a Class Title Which line(s) are part of the public interface of a class? type mc section 9.3 Specifying the Public Interface of a Class id testbank-py-1-ch09-35

28. Consider the following class: class Counter : def getValue(self) : return self._value def click(self) : self._value = self._value + 1 def unClick(self) : self._value = self._value - 1 def reset(self) : self._value = 0 Which method is an accessor? 1. getValue 2. click 3. unClick 4. reset Section 9.3 Specifying the Public Interface of a Class Title Which method is an accessor? type mc section 9.3 Specifying the Public Interface of a Class id testbank-py-1-ch09-36 29. Consider the following class: class Counter : def getValue(self) :


29.

return self._value def click(self) : self._value = self._value + 1 def unClick(self) : self._value = self._value - 1 def reset(self) : self._value = 0 Which method(s) are mutators? 1. Only reset 2. Only click and unClick 3. Only click, unClick and reset 4. All four methods are mutators Section 9.3 Specifying the Public Interface of a Class Title Which method(s) are mutators? type mc section 9.3 Specifying the Public Interface of a Class id testbank-py-1-ch09-37

30. Assume that the class ShoppingList has already been defined with the following public interface: ## A simulated grocery list # class ShoppingList : ## Adds an item to this shopping list. # @param cost the cost of this item # @param quantity the number of items # @param itemName the name of the item # def addItem(self, cost, quantity, itemName) : # implementation hidden ## Gets the number of items in the list. # @return the item count # def getCount(self) : # implementation hidden ## Clears the list. # def clear(self) : # implementation hidden What is wrong with the following code segment?


30. list.clear() list = ShoppingList() list.addItem(2.95, 1, "milk") list.addItem(.50, 3, "cucumber") print(list.getCount()) 1. Nothing, the program prints 2 for the number of items in the list. 2. The list object has not been created before invoking the clear method. 3. The addItem method does not take three arguments. 4. There is no print method defined for the ShoppingList class. Section 9.3 Specifying the Public Interface of a Class Title What is wrong with the following code segment that invokes methods on an object? type mc section 9.3 Specifying the Public Interface of a Class id testbank-py-1-ch09-33 31. Assume that the class ShoppingList has already been defined with the following public interface: ## A simulated grocery list # class ShoppingList : ## Adds an item to this shopping list. # @param cost the cost of this item # @param quantity the number of items # @param itemName the name of the item # def addItem(self, cost, quantity, itemName) : # implementation hidden ## Gets the number of items in the list. # @return the item count # def getCount(self) : # implementation hidden ## Clears the list. # def clear(self) : # implementation hidden What is wrong with the following code segment? list = ShoppingList() list.clear() list.addItem(2.95, 1, "milk") list.addItem(.50, 3, "cucumber")


31. print(list.getItems()) 1. Nothing, the program prints 2 for the number of items in the list. 2. The list object has not been created before invoking the clear method. 3. The addItem method does not take three values. 4. There is no getItems method defined for the ShoppingList class. Section 9.3 Specifying the Public Interface of a Class Title What is wrong with the following code segment that invokes methods on an object? type mc section 9.3 Specifying the Public Interface of a Class id testbank-py-1-ch09-34 32. In the following example, which data is considered instance data? You are assigned the task of writing a program that calculates payroll for a small company. To get started the program should do the following: Add new employees including their first and last name and hourly wage Ask for the number of hours worked Calculate payroll (applying 1.5 for any hours greater than 40) Print a report of all employees' salary for the week, total of all hours and total of all salaries 1. firstName, lastName, hoursWorked, hourlyWage 2. firstName, lastName, hoursWorked, hourlyWage, payrollAmount 3. firstName, lastName, hoursWorked, hourlyWage, totalHours, totalSalary 4. firstName, lastName, hoursWorked, hourlyWage, payrollAmount, totalHours, totalSalary Section 9.4 Designing the Data Representation Title In the following example, which data should be considered instance data? type mc section 9.4 Designing the Data Representation id testbank-py-1-ch09-38 33. Which name would be best for a private instance variable? 1. _confidential 2. HIDDEN 3. private 4. Secret Section 9.4 Designing the Data Representation Title Which name would be best for a private instance variable?


33. type mc section 9.4 Designing the Data Representation id testbank-py-1-ch09-39 34. What is the purpose of a constructor? 1. To specify the public interface 2. To identify the accessor and mutator methods 3. To define and initialize the instance variables of an object 4. To print the contents of an object Section 9.5 Constructors Title What is the purpose of a constructor? type mc section 9.5 Constructors id testbank-py-1-ch09-40 35. When is a constructor invoked? 1. When an object is created 2. When instance data is modified 3. When a method is invoked 4. When multiple arguments are required to create an object Section 9.5 Constructors Title When is a constructor invoked? type mc section 9.5 Constructors id testbank-py-1-ch09-41 36. Which of the following method headers represent a constructor? 1. def init(self) : 2. def __init__(self) : 3. def _init(self) : 4. def init() : Section 9.5 Constructors Title Which of the following method headers represent a constructor? type mc


36. section 9.5 Constructors id testbank-py-1-ch09-42 37. Consider the class Employee: class Employee : def __init__(self, firstName, lastName, employeeId) : self._name = lastName + "," + firstName self._employeeId = employeeId ... If an object is contructed as: sam = Employee("Sam", "Fisher", 54321) What is the contents of the instance variable _name? 1. Sam 2. Sam Fisher 3. Fisher, Sam 4. Fisher, Sam, 54321 Section 9.5 Constructors Title Given the constructor for the class Employee, what is the contents of one of the instance variables? type mc section 9.5 Constructors id testbank-py-1-ch09-43 38. Which of the following method headers represent a constructor for an Employee class? 1. def Employee(self) : 2. def __init()__ : 3. def __Employee__(self) : 4. def __init__(self) : Section 9.5 Constructors Title Which of the following method headers represent a constructor? type mc section


38.

9.5 Constructors id testbank-py-1-ch09-44

39. How many constructors can be defined for each class? 1. At least one must be defined 2. Only one may be defined 3. At least one, but as many as needed 4. At least one, but no more than five Section 9.5 Constructors Title How many constructors can be defined for each class? type mc section 9.5 Constructors id testbank-py-1-ch09-45 40. What method name is used for a constructor? 1. __begin__ 2. __construct__ 3. __create__ 4. __init__ Section 9.5 Constructors Title What method name is used for a constructor? type mc section 9.5 Constructors id testbank-py-1-ch09-48 41. What is wrong with the following constructor? def __init__() : self._weight = 0.0 self._color = "None" 1. The constructor must have a different name 2. The constructor must take the self parameter 3. The constructor must not initialize private instance variables 4. The constructor must initialize _color before _weight Section 9.5 Constructors Title What is wrong with this constructor? type mc section 9.5 Constructors


41. id testbank-py-1-ch09-49 42. Consider the following code segment which constructs two objects of type Fruit: x = Fruit() y = Fruit("Banana", "Yellow") Which constructor header will construct both objects successfully? 1. def __init__(name, color) : 2. def __init__(name="", color="") : 3. def __init__(self, name, color) : 4. def __init__(self, name="", color="") : Section 9.5 Constructors Title Which constructor head will allow two objects to be constructed successfully? type mc section 9.5 Constructors id testbank-py-1-ch09-50 43. Which of the following is NOT true about constructors? 1. A constructor initializes the instance variables of an object 2. The constructor is automatically called when an object is created 3. The constructor is defined using the special method name __default__ 4. Default arguments can be used with a constructor to provide different ways of creating an object Section 9.5 Constructors Title Which of the following is NOT true about constructors? type mc section 9.5 Constructors id testbank-py-1-ch09-73 44. Consider the following code segment: class PhoneNumber : def __init__(self, lName, phone = "215-555-1212") : self._name = lName self._phone = phone def getName(self): return self._name def getPhone(self): return self._phone


44. Jones = PhoneNumber("Jones") print(Jones.getName(), Jones.getPhone()) What will be printed when it executes? 1. Jones 215-555-1212 2. AttributeError: 'PhoneNumber' object has no attribute 3. Jones 4. Jones 000-000-0000 Section 9.5 Constructors Title What is printed by a code segment that creates an object? type mc section 9.5 Constructors id testbank-py-1-ch09-46 45. What change needs to be made in the following code segment so that lName will have a default value of "unknown"? class PhoneNumber : def __init__(self, lName, phone = "215-555-1212") : self._name = lName self._phone = phone 1. Replace self._name = lName with self._name = "unknown" 2. Replace the lName parameter with lName = "unknown" 3. Add name = "unknown" to the end of the constructor 4. Add self._lName = "unknown" to the end of the constructor Section 9.5 Constructors Title What change should be made to a code segment so that the constructor includes a default value for a parameter? type mc section 9.5 Constructors id testbank-py-1-ch09-47 46. How do you access instance variables in a method? 1. Using the constructor 2. Using the public interface 3. Using a default value 4. Using the self reference Section 9.6 Implementing Methods Title How do you access instance variables in a method? type


46. mc section 9.6 Implementing Methods id testbank-py-1-ch09-51 47. Given the following code snippet, what statement completes the code to add several items to one grocery list: def addItems(self, price, quantity, itemName) : for i in range(quantity) : ________________________ def addItem(self, price, itemName) : self._itemCount = self._ItemCount + 1 self._totalPrice = self._totalPrice + price ... 1. self.addItem(price, itemName) 2. addItem(price, itemName) 3. self._addItem(price, itemName) 4. _addItem(price, itemName) Section 9.6 Implementing Methods Title Given the following code snippet, what statement completes the code to add several items to one grocery list: type mc section 9.6 Implementing Methods id testbank-py-1-ch09-52 48. Consider the following code segment: def mutate(self, newType) : self._type = newType self._mutations = self._mutations + 1 What is the name of the local variable in it: 1. mutate 2. _mutations 3. newType 4. _type Section 9.6 Implementing Methods Title Identify the local variable in a method type mc


48. section 9.6 Implementing Methods id testbank-py-1-ch09-53 49. Consider the following code segment: class Fruit : _type = "Fruit" def __init__(self, color) : self._color = color What is the name of the class variable? 1. color 2. _color 3. self 4. _type Section 9.6 Implementing Methods Title What is the name of the class variable? type mc section 9.6 Implementing Methods id testbank-py-1-ch09-54 50. Which of the following is NOT true about instance methods for a class? 1. The object on which a method is applied is automatically passed to the self parameter variable of the method 2. In a method, you access instance variables through the self parameter variable 3. A class variable belongs to the class, not to any instance of the class 4. The accessor and mutator methods are automatically called when an object is created Section 9.6 Implementing Methods Title Which of the following is NOT true about instance methods for a class? type mc section 9.6 Implementing Methods id testbank-py-1-ch09-74 51. Consider the following class: class Pet: def __init__(self, name): self._name = name self._owner = "<unknown>"


51. def setOwner(self, owner): ____________________ What line of code should be placed in the blank to complete the setOwner mutator method that is supposed to update the pet owner's name? 1. self._name = name 2. self._name = owner 3. self._owner = owner 4. self.owner = _owner Section 9.6 Implementing Methods Title What code is needed to complete a mutator method? type mc section 9.6 Implementing Methods id testbank-py-2-ch09-82 52. Class variables are also known as: 1. global variables 2. interface variables 3. local variables 4. static variables Section 9.6 Implementing Methods Title Which term is a synonym for "class variable"? type mc section 9.6 Implementing Methods id testbank-py-2-ch09-83 53. Where should instance variables be defined? 1. In accessor methods 2. In constructors 3. In functions 4. In mutator methods Section 9.6 Implementing Methods Title Where should instance variables be defined? type mc section 9.6 Implementing Methods id testbank-py-2-ch09-84 54. Consider the following class: class Pet: ____________________


54. def __init__(self, name): self._name = name Pet._lastID = Pet._lastID + 1 self._registrationID = Pet._lastID What line of code should be placed in the blank to create a class variable that keeps track of the most recently used registration identifier? 1. _lastID = 0 2. Pet.append(_lastID) 3. Pet._lastID = 0 4. self._lastID = 0 Section 9.6 Implementing Methods Title What code is needed to add a class variable to an existing class? type mc section 9.6 Implementing Methods id testbank-py-2-ch09-85 55. Which of the following is NOT considered part of unit testing for a class? 1. Construct an object 2. Identify syntax errors 3. Call methods 4. Verify the program returns the expected values Section 9.7 Testing a Class Title Which of the following is NOT considered part of unit testing for a class? type mc section 9.7 Testing a Class id testbank-py-1-ch09-56 56. Which of the following is NOT a step carried out by a tester program? 1. Construct one or more objects of the class 2. Invoke one or more methods 3. Print out one or more results 4. Identify syntax errors Section 9.7 Testing a Class Title Which of the following is NOT a step carried out by a tester program? type mc section 9.7 Testing a Class id testbank-py-1-ch09-57


57. Which of the follow code segments could be used to help test the getColor method from the Fruit class? 1. print(f.getColor()) print("Expected: Yellow") 2. print("Yellow") print("Expected: Yellow") 3. print(f.getColor()) print("Expected:", f.getColor()) 4. print("Yellow") print("Expected:", f.getColor()) Section 9.7 Testing a Class Title Which code segment helps test a class? type mc section 9.7 Testing a Class id testbank-py-1-ch09-59 58. What is the purpose of unit testing? 1. To verify that the constructor works correctly. 2. To verify that the entire program works correctly. 3. To verify that a class works correctly in isolation, outside a complete program. 4. To verify that one method works correctly. Section 9.7 Testing a Class Title What is the purpose of unit testing? type mc section 9.7 Testing a Class id testbank-py-1-ch09-55 59. What term is used to describe the process of verifying that a class works correctly in isolation, outside of a complete program? 1. Function testing 2. Interface testing 3. Method testing 4. Unit testing Section 9.7 Testing a Class Title What term is used to describe the process of verifying that a class works correctly in isolation? type mc section 9.7 Testing a Class


59. id testbank-py-2-ch09-86 60. When using the process of tracing objects for problem solving, which types of methods update the values of the instance variables? 1. Accessor methods 2. Mutator methods 3. Constructors 4. Both B and C Section 9.8 Problem Solving: Tracing Objects Title When using the process of tracing objects for problem solving, which types of methods update the values of the instance variables? type mc section 9.8 Problem Solving: Tracing Objects id testbank-py-1-ch09-58 61. Consider the following class: class Contact : def __init__(self, name, phone="") self._name = name self._phone = phone def getName(self) : return self._name def setName(self, new_name) : self._name = new_name def getPhone(self) : return self._phone def setPhone(self, new_phone) : self._phone = new_phone What is output by the following code segment? p1 = Contact("Bob", "555-123-4567") p2 = Contact("Joe", "555-000-0000") p1.setName(p2.getName()) print(p1.getPhone()) 1. Bob 2. Joe 3. 555-000-0000 4. 555-123-4567 Section


61. 9.8 Problem Solving: Tracing Objects Title Trace code involving objects and classes type mc section 9.8 Problem Solving: Tracing Objects id testbank-py-1-ch09-60 62. Which of the following patterns can be used for designing your class to help keep track of the number of fees charged by a bank? 1. Keeping a total 2. Counting events 3. Collecting values 4. Managing properties of an object Section 9.9 Problem Solving: Patterns for Object Data Title Which of the following patterns can be used for designing your class to help track of the number of fees charged by a bank? type mc section 9.9 Problem Solving: Patterns for Object Data id testbank-py-1-ch09-61 63. Which of the following patterns can be used for designing your class to update the balance of a bank account? 1. Keeping a total 2. Counting events 3. Collecting values 4. Managing properties of an object Section 9.9 Problem Solving: Patterns for Object Data Title Which of the following patterns can be used for designing your class to update the balance of a bank account? type mc section 9.9 Problem Solving: Patterns for Object Data id testbank-py-1-ch09-62 64. Which of the following patterns can be used for designing your class to add error checking such as not allowing a blank name for a bank account? 1. Describing the Position of an Object 2. Modeling Objects with Distinct States 3. Managing Properties of an Object 4. Collecting Values Section 9.9 Problem Solving: Patterns for Object Data Title Which of the following patterns can be used for designing your class to add error checking such as not


64. allowing a blank name for a bank account? type mc section 9.9 Problem Solving: Patterns for Object Data id testbank-py-1-ch09-63 65. Which of the following patterns can be used for designing your class for a train object that drives along a track and keeps track of the distance from the terminus? 1. Describing the Position of an Object 2. Modeling Objects with Distinct States 3. Managing Properties of an Object 4. Collecting Values Section 9.9 Problem Solving: Patterns for Object Data Title Which of the following patterns can be used for designing your class for a train object that drives along a track and keeps track of the distance from the terminus? type mc section 9.9 Problem Solving: Patterns for Object Data id testbank-py-1-ch09-64 66. Consider the following class which is used to represent a polygon consisting of an arbitrary number of (x, y) points: class Polygon : def __init__(self) : self._x_points = [] self._y_points = [] Which of the following code segments is the correct implementation for the addPoint method that adds another point to the polygon? 1. def addPoint(self, x, y) : self._points.append(x, y) 2. def addPoint(self, x, y) : self._x_points.append(x) self._y_points.append(y) 3. def addPoint(self, x, y) : self._x_points = x self._y_points = y 4. def addPoint(self, x, y) : self._x_points = [x] self._y_points = [y] Section 9.9 Problem Solving: Patterns for Object Data


66.

Title Implement a new method in a class type mc section 9.9 Problem Solving: Patterns for Object Data id testbank-py-1-ch09-65

67. Consider a class that represents a hardware device. The device can be in one of two states: Plugged in, or unplugged. Which of the following class definitions is best for this situation? 1. PLUGGED_IN = 0 UNPLUGGED = 1 class Device : def __init__(self) : ... 2. class Device : PLUGGED_IN = 0 UNPLUGGED = 1 def __init__(self) : ... 3. class Device : def __init__(self) : PLUGGED_IN = 0 UNPLUGGED = 1 ... 4. class Device : def __init__(self) : self.PLUGGED_IN = 0 self.UNPLUGGED = 1 ... Section 9.9 Problem Solving: Patterns for Object Data Title Which class best represents a device with 2 possible states? type mc section 9.9 Problem Solving: Patterns for Object Data id testbank-py-1-ch09-66 68. Which of the following is NOT a pattern used to help design the data representation of a class? 1. An instance variable for thte total is updated in methods that increase or decrease the total amount 2. An object reference specifies the location of an object 3. An object can collect other objects in a list


68.

4. To model a moving object, you need to store and update its position Section 9.9 Problem Solving: Patterns for Object Data Title Which of the following is NOT true about instance methods for a class? type mc section 9.9 Problem Solving: Patterns for Object Data id testbank-py-1-ch09-75

69. What is the value of the variable bankAcct after the following code snippet is executed? bankAcct = BankAccount("Fisher", 1000.00) 1. "Fisher", 1000.00 2. A memory location 3. "Fisher" 4. 1000.00 Section 9.10 Object References Title What is the value of the variable bankAcct after the following code snippet is executed? type mc section 9.10 Object References id testbank-py-1-ch09-67 70. Given the following code snippet, how can you test if they reference the same object (or does not refer to any object)? bankAcct2 = bankAcct 1. if bankAcct == bankAcct2 : print("The variables are aliases") 2. if bankAcct is bankAcct2 : print("The variables are aliases") 3. if bankAcct is not bankAcct2 : print("The variables are aliases") 4. if bankAcct.equals(bankAcct2) : print("The variables are aliases") Section 9.10 Object References Title


70. Given the following pre snippet, how can you test if they reference the same object? type mc section 9.10 Object References id testbank-py-1-ch09-69 71. Which statement determines if the middleInit variable is empty or does not refer to any object? 1. if middleInit is None : print("No middle initial") 2. if middleInit is not None : print("No middle initial") 3. if middleInit == None : print("No middle initial") 4. if middleInit != None : print("No middle initial") Section 9.10 Object References Title Which statement determines if the middleInit variable is empty or does not refer to any object? type mc section 9.10 Object References id testbank-py-1-ch09-70 72. What happens when an object is no longer referenced? 1. Nothing until the problem terminates 2. The garbage collector removes the object 3. The address is saved for future instances of the object 4. Creates a None reference Section 9.10 Object References Title What happens when an object is no longer referenced? type mc section 9.10 Object References id testbank-py-1-ch09-71 73. Which of the following is NOT true about objects? 1. An object reference specifies the location of an object 2. Multiple object variables can contain references to the same object 3. The == and != operators test whether two variables are aliases 4. The None reference refers to no object


73. Section 9.10 Object References Title Which of the following is NOT true about objects? type mc section 9.10 Object References id testbank-py-1-ch09-72 74. Given the variable assignment sentence = "", what is the value of len(sentence)? 1. 1 2. -1 3. an exception is raised 4. 0 Section 9.10 Objects and Classes Title Given the variable assignment sentence = "", what is the value of len(sentence)? type mc section 9.10 Object References id testbank-py-1-ch09-76 75. Which of the following statements sets x so that it refers to no object at all? 1. x = 2. x = () 3. x = "" 4. x = None Section 9.10 Object References Title Which statement gives a variable a variable that refers to no object at all? type mc section 9.10 Object References id testbank-py-1-ch09-77 76. Recall the Cash Register class developed in the textbook. What is output by the following code segment? from cashregister2 import CashRegister reg1 = CashRegister() reg1.addItem(3.00) reg2 = reg1 reg1.addItem(5.00) print(reg2.getCount()) 1. 0


76.

2. 1 3. 2 4. The program terminates with a runtime error Section 9.10 Object References Title Trace code involving object references type mc section 9.10 Object References id testbank-py-1-ch09-78

77. Recall the Cash Register class developed in the textbook. What is output by the following code segment? from cashregister2 import CashRegister reg1 = CashRegister() reg2 = reg1 reg1.addItem(3.00) reg1.addItem(5.00) reg2.clear() print(reg1.getCount()) 1. 0 2. 1 3. 2 4. The program terminates with a runtime error Section 9.10 Object References Title Trace code involving object references type mc section 9.10 Object References id testbank-py-1-ch09-79 78. Consider the following code segment: bankAcct = BankAccount("Fisher", 1000.00) bankAcct2 = bankAcct What is the relationship between bankAcct and bankAcct2? 1. bankAcct and bankAcct2 are self references 2. bankAcct and bankAcct2 are aliases for the same object reference 3. bankAcct and bankAcct2 are NONE references 4. bankAcct and bankAcct2 are separate references Section 9.10 Object References Title What is the relationship between two object references in a code segment? type mc


78. from testbank-py-1-ch09-68 section 9.10 Object References id testbank-py-2-ch09-68 79. What does an object reference specify? 1. The hashcode of an object 2. The location of an object 3. The name of an object 4. The size of an object Section 9.10 Object References Title What does an object reference specify? type mc section 9.10 Object References id testbank-py-2-ch09-87 80. What part of the virtual machine is responsible for removing objects that are no longer referenced? 1. The allocator 2. The garbage collector 3. The recycler 4. The regenerator Section 9.10 Object References Title What part of the virtual machine is responsible for removing objects that are no longer referenced? type mc section 9.10 Object References id testbank-py-2-ch09-88 81. Assume that x is a variable containing an object reference. Which special method is invoked when the following statement executes? print(x) 1. __init__ 2. __print__ 3. __repr__ 4. __str__ Section 9.11 Application: Writing a Fraction Class Title Which special method is invoked when an object is printed? type mc section


81.

9.11 Application: Writing a Fraction Class id testbank-py-1-ch09-80

82. Which of the following statements determines if x currently refers to an object containing an integer? 1. if int(x) : 2. if x == int : 3. if x is int : 4. if isinstance(x, int) : Section 9.11 Application: Writing a Fraction Class Title Which statement determines if x refers to an integer? type mc section 9.11 Application: Writing a Fraction Class id testbank-py-1-ch09-81 83. Consider the following class which will be used to represent complex numbers: class Complex: def __init__(self, real, imaginary): self._real = real self._imaginary = imaginary def ____________________: real = self._real + rhsValue._real imaginary = self._imaginary + rhsValue._imaginary return Complex(real, imaginary) What code should be placed in the blank so that two complex numbers can be added using the + operator? 1. +(self, rhsValue) 2. __+__(self, rhsValue) 3. add 4. __add__(self, rhsValue) Section 9.11 Application: A Fraction Class Title What statement should be added to a class so that two instances of the class can be added using a plus sign? type mc section 9.11 Application: Writing a Fraction Class id testbank-py-2-ch09-89


1. A class that represents the most general entity in an inheritance hierarchy is called a/an ______. 1. Default class 2. Superclass 3. Subclass 4. Inheritance class Section 10.1 Inheritance Hierarchies Title A class that represents the most general entity in an inheritance hierarchy is called a/an ______. type mc section 10.1 Inheritance Hierarchies id testbank-py-1-ch10-01 2. A class that represents a more specific entity in an inheritance hierarchy is called a/an _______. 1. Default class 2. Superclass 3. Subclass 4. Inheritance class Section 10.1 Inheritance Hierarchies Title A class that represents a more specific entity in an inheritance hierarchy is called a/an _______. type mc section 10.1 Inheritance Hierarchies id testbank-py-1-ch10-02 3. You are creating a class inheritance hierarchy about motor vehicles that will contain classes named Vehicle, Auto, and Motorcycle. Which of the following statements is correct? 1. Vehicle should be the subclass, while Auto, and Motorcycle should be the default classes 2. Vehicle should be the subclass, while Auto, and Motorcycle should be the superclasses 3. Vehicle should be the default class, while Auto, and Motorcycle should be the subclasses 4. Vehicle should be the superclass, while Auto, and Motorcycle should be the subclasses Section 10.1 Inheritance Hierarchies Title Creating a class inheritance hierarchy type mc section 10.1 Inheritance Hierarchies id testbank-py-1-ch10-03 4. Which of the following statements about inheritance is correct? 1. You can always use a superclass object in place of a subclass object. 2. You can always use a subclass object in place of a superclass object. 3. A superclass inherits data and behavior from a subclass. 4. A superclass inherits only behavior from a subclass. Section


4. 10.1 Inheritance Hierarchies Title Which statement about inheritance is correct? type mc section 10.1 Inheritance Hierarchies id testbank-py-1-ch10-04 5. Assume that you are creating a new Python class named Vehicle, as shown below: class Vehicle : ... What is Vehicle's superclass? 1. dict 2. None 3. object 4. set Section 10.1 Inheritance Hierarchies Title Identify the superclass of a class type mc section 10.1 Inheritance Hierarchies id testbank-py-1-ch10-05 6. What is the substitution principle? 1. A subclass inherits data and behavior from a superclass 2. You can create an object from a concrete class, but not from an abstract class. 3. You can always use a superclass object when a subclass object is expected 4. You can always use a subclass object when a superclass object is expected Section 10.1 Inheritance Hierarchies Title What is the substitution principle? type mc section 10.1 Inheritance Hierarchies id testbank-py-1-ch10-64 7. What is the purpose of using an inheritance hierarchy? 1. To share common code among the classes 2. To create objects from concrete classes 3. To create objects from abstract classes 4. To create objects using constructors Section 10.1 Inheritance Hierarchies


7. Title What is the purpose of using an inheritance hierarchy? type mc section 10.1 Inheritance Hierarchies id testbank-py-1-ch10-65 8. What would be the inhertiance relationships between classes Apples, Pears, and Fruit? 1. Apples inherit from Pears 2. Apples and Pears inherit from Fruit 3. Fruit inherits from Apples and Pears 4. Pears inherits from Apples Section 10.1 Inheritance Hierarchies Title What would be the inhertiance relationships between classes Apples, Pears, and Fruit? ` type mc section 10.1 Inheritance Hierarchies id testbank-py-1-ch10-66 9. Identify the list of superclasses from the list of pairs below: Manager, Employee GraduateStudent, Student BankAccount, CheckingAccount Vehicle, Minivan 1. Employee, Student, BankAccount, Vehicle 2. Manager, GraduateStudent, CheckingAccount, Minivan 3. Employee, Student, CheckingAccount, Minivan 4. Manager, GraduateStudent, BankAccount, Vehicle Section 10.1 Inheritance Hierarchies Title Identify the list of superclasses. type mc section 10.1 Inheritance Hierarchies id testbank-py-1-ch10-73 10. Which class is the direct or indirect superclass of every class in Python? 1. default


10.

2. None 3. object 4. super Section 10.1 Inheritance Hierarchies Title Which class is the direct or indirect superclass of every class in Python? type mc section 10.1 Inheritance Hierarchies id testbank-py-2-ch10-75

11. A subclass object can always be used when a superclass object is expected. This fact is referred to as: 1. generalized interoperability 2. method overriding 3. the replacement policy 4. the substitution principle Section 10.1 Inheritance Title What term is used to describe the notion that a subclass object can always be used when a superclass object is expected? type mc section 10.1 Inheritance Hierarchies id testbank-py-2-ch10-79 12. Consider the following code segment: class Animal : # The body of the class has been omitted class Dinosaur(Animal) : # The body of the class has been omitted class Triceratops(Dinosaur) : # The body of the class has been omitted class Pterodactyl(Dinosaur) : # The body of the class has been omitted Which class is at the root of the inheritance hierarchy? 1. Animal 2. Dinosaur 3. Pterodactyl 4. Triceratops Section 10.1 Inheritance Title Which class is at the root of the inheritance hierarchy? type


12. mc section 10.1 Inheritance Hierarchies id testbank-py-2-ch10-80 13. What does the subclass inherit from a superclass? 1. Data and behavior 2. Only behaviors 3. Only data 4. Nothing Section 10.2 Implementing Subclasses Title What does the subclass inherit from a superclass? type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-06 14. Insert the missing code in the following code fragment. This fragment is intended to call the Vehicle class's method. class Vehicle : def setVehicleClass(self, numberAxles) : ... class Motorcycle(Vehicle) : def __init__(self) : __________________ harley = Motorcycle() 1. self.setVehicleClass(2) 2. setVehicleClass(2) 3. Motorcycle.setVehicleClass(2) 4. Vehicle.setVehicleClass(2) Section 10.2 Implementing Subclasses Title Complete the code to call a superclass method type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-07


15. Insert the missing code in the following code fragment. This fragment is intended to call the Vessel class's method. class Vessel : def setVesselClass(self, vesselLength) : ... class JetSki(Vessel) : def __init__(self) : __________________ mySki = JetSki() 1. JetSki.setVessel(12) 2. setVesselClass(12) 3. self.setVesselClass(12) 4. Vessel.setVessel(12) Section 10.2 Implementing Subclasses Title Complete the code to call a superclass method type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-08 16. You are creating a Motorcycle class which is supposed to inherit from the Vehicle class. Which of the following class declaration statements will accomplish this? 1. class Motorcycle(self) : 2. class Motorcycle extends Vehicle : 3. class Motorcycle is Vehicle : 4. class Motorcycle(Vehicle) : Section 10.2 Implementing Subclasses Title Which class declaration statement indicates inheritance? type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-11 17. Which of the following is true regarding subclasses? 1. A subclass inherits methods from its superclass but not instance variables.


17.

2. A subclass inherits instance variables from its superclass but not methods. 3. A subclass inherits methods and instance variables from its superclass. 4. A subclass does not inherit methods or instance variables from its superclass. Section 10.2 Implementing Subclasses Title Which is true regarding subclasses? type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-13

18. Which of the following is true regarding subclasses? 1. A subclass that inherits methods from its superclass may not override the methods. 2. A subclass that inherits instance variables from its superclass may not declare additional instance variables. 3. A subclass may inherit methods or instance variables from its superclass but not both. 4. A subclass may inherit methods and instance variables from its superclass, and may also implement its own methods and declare its own instance variables. Section 10.2 Implementing Subclasses Title Which is true regarding subclasses? type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-14 19. Which of the following is true regarding subclasses? 1. A subclass has access to private instance variables of its superclass. 2. A subclass does not have access to public instance variables of its superclass. 3. A subclass must specify the implicit parameter to use methods inherited from its superclass. 4. A subclass has no access to private instance variables of its superclass. Section 10.2 Implementing Subclasses Title Which is true regarding subclasses? type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-15 20. What must a subclass do to modify a private superclass instance variable? 1. The subclass must simply use the name of the superclass instance variable. 2. The subclass must declare its own instance variable with the same name as the superclass instance variable. 3. The subclass must use a public method of the superclass (if it exists) to update the superclass's private instance variable. 4. The subclass must have its own public method to update the superclass's private instance variable. Section


20. 10.2 Implementing Subclasses Title How to modify a private superclass instance variable type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-17 21. Consider the following class hierarchy: class Vehicle : def __init__(self, type) : self._type = type class LandVehicle(Vehicle) : def __init__(self, type) : super().__init__(type) class Auto(Vehicle) : def __init__(self, type) : ____________________________ Complete the code in the Auto class constructor to store the type data. 1. super(type) 2. super().super().__init__(type) 3. super().__init__(type) 4. This cannot be done unless the Auto class declares an instance variable named type. Section 10.2 Implementing Subclasses Title Complete the code to use a subclass type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-18 22. Which statement is correct about the following code segment: class Pizza : ... class Food(Pizza) : ... 1. Pizza is a subclass of Food


22.

2. Food is a subclass of Pizza 3. Food and Pizza do not have a superclass / subclass relationship 4. The code segment does not allow one to determine what the superclass / subclass relationship is between the classes Section 10.2 Implementing Subclasses Title Identify the relationship between the classes in a code segment type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-19

23. What is the name of the superclass in the following code segment? class Triceratops(Dinosaur) : def eat(self, what) : ... 1. Dinosaur 2. eat 3. Triceratops 4. what Section 10.2 Implementing Subclasses Title What is the name of the superclass in a code segment? type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-20 24. What is the name of the subclass in the following code segment? class Apple(Fruit) : def getCalories(self) : ... 1. Apple 2. Fruit 3. getCalories 4. self Section 10.2 Implementing Subclasses Title What is the name of the subclass in a code segment? type mc section 10.2 Implementing Subclasses id


24. testbank-py-1-ch10-21 25. Which set of classes represents the relationship that all circles are ovals? 1. class Circle(Oval) : ... 2. class Oval(Circle) : ... 3. class Circle : ... class Oval : ... 4. class Shape : ... class Circle(Shape) : ... class Oval(Shape) : ... Section 10.2 Implementing Subclasses Title Which classes correctly model the relationship between two types of entities? type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-22 26. You have been asked to write a program that involves animals. Some animals are herbivores. Within this program, any animal that is not a herbivore is a carnivore. Which set of class definitions is most appropriate for this program? 1. class Animal : ... class Herbivore(Animal) : ... class Carnivore(Herbivore) : ... 2. class Animal : ... class Carnivore(Animal) : ... class Herbivore(Carnivore) : ...


26.

2. 3. class Animal : ... class Herbivore(Animal) : ... class Carnivore(Animal) : ... 4. class Animal(Herbivore, Carnivore) : ... class Herbivore : ... class Carnivore : ...

Section 10.2 Implementing Subclasses Title Which collection of classes represents a particular scenario? type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-23 27. Which group of classes is poorly designed? 1. class Vegetable : ... class Dog : ... 2. class Pet : ... class Dog(Pet) : ... 3. class Fruit : ... class Vegetable : ... 4. class Dog : ... class Cat(Dog) : ...


27. Section 10.2 Implementing Subclasses Title Which set of classes is poorly designed? type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-25 28. Which set of classes is poorly designed? 1. class Pet : ... class Cat(Pet) : ... class Dog(Pet) : ... 2. class Pizza : ... class Food(Pizza) : ... class Apple(Food) : ... 3. class Vehicle : ... class Car(Vehicle) : ... class HatchBack(Car) : ... 4. class Pizza : ... class Employee : ... class Textbook : ... Section 10.2 Implementing Subclasses Title Which group of classes is poorly designed? type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-26


29. Consider the following code segment: class Fruit : def __init__(self, name) : ... class Apple : def __init__self(self, name) : ... Which statement successfully creates a new Apple object? 1. x = Fruit() 2. x = Fruit("Apple") 3. x = Apple() 4. x = Apple("McIntosh") Section 10.2 Implementing Subclasses Title Which statement successfully creates a new object? type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-27 30. Consider classes Oranges, Pears, Apples, Fruit. Which should be the superclass? 1. Oranges 2. Pears 3. Apples 4. Fruit Section 10.2 Implementing Subclasses Title Which should be the superclass? type mc section 10.2 Implementing Subclasses id testbank-py-1-ch10-60 31. Identify the subclass and superclass in the following code segment: class ChoiceQuestion(Question) : def __init__(self) : ... 1. The subclass is Question. The superclass is ChoiceQuestion. 2. The subclass is ChoiceQuestion. The superclass is Question. 3. The subclass is init. The superclass is self. 4. The subclass is ChoiceQuestion. The superclass is object. Section 10.2 Implementing Subclasses


31. Title Identify the subclass and superclass in a code segment type mc from testbank-py-1-ch10-10 section 10.2 Implementing Subclasses id testbank-py-2-ch10-10 32. Which of the following class declaration statements will create a class Dog that is a subclass of Pet? 1. class Dog is Pet : 2. class Dog(Pet) : 3. class Dog extends Pet : 4. class Dog(self) : Section 10.2 Implementing Subclasses Title Which class declaration creates a subclass of a specific superclass? type mc from testbank-py-1-ch10-12 section 10.2 Implementing Subclasses id testbank-py-2-ch10-12 33. Which of the following statements indicates that ClassA is a superclass of ClassB? 1. class ClassB(ClassA) : 2. class ClassA(ClassB) : 3. class ClassB extends ClassA : 4. class ClassA extends ClassB : Section 10.2 Implementing Subclasses Title Which statement indicates that on class is a superclass of another class? type mc from testbank-py-1-ch10-16 section 10.2 Implementing Subclasses id testbank-py-2-ch10-16 34. You are creating a Pen class that will be a subclass of a WritingImplement class. Which statement accomplishes this goal?


34.

1. class Pen(WritingImplement) : 2. class WritingImplement(Pen) : 3. subclass Pen(WritingImplement) : 4. subclass WritingImplement(Pen) : Section 10.2 Implementing Subclasses Title Which statement creates Pen as a subclass of WritingImplement? type mc from testbank-py-1-ch10-24 section 10.2 Implementing Subclasses id testbank-py-2-ch10-24

35. A class name inside parentheses in the class header indicates that the: 1. class inherits from a default class 2. class inherits from a superclass 3. class inherits from a subclass 4. class inherits from the object class Section 10.2 Implementing Subclasses Title What does a class name inside parentheses in the class header indicate? type mc from testbank-py-1-ch10-09 section 10.2 Implementing Subclasses id testbank-py-2-ch10-09 36. Which of the following statements about superclasses and subclasses is true? 1. A superclass is larger than its subclass. 2. A superclass inherits from a subclass. 3. A superclass extends a subclass. 4. A subclass extends a superclass. Section 10.3 Calling the Superclass Constructor Title Which of the following statements about superclasses and subclasses is true? type mc section 10.3 Calling the Superclass Constructor id testbank-py-1-ch10-28 37. Assume that you have a class Apple which is a subclass of Fruit. Which statement can be used in Apple's constructor to invoke Fruit's constructor? 1. __init__() 2. Apple().__init__()


37.

3. Fruit().__init__() 4. super().__init__() Section 10.3 Calling the Superclass Constructor Title Which statement invokes the superclass constructor? type mc section 10.3 Calling the Superclass Constructor id testbank-py-1-ch10-29

38. Consider the following classes: class Vehicle : def __init__(self, name) : self._name = name class LandVehicle(Vehicle) : def __init__(self, numWheels) : super().__init__("Land Vehicle") ____________________ def getWheels(self) : return self._numWheels What statement should be placed in the blank to complete the constructor for LandVehicle? 1. _numWheels = numWheels 2. self._numWheels = numWheels 3. super()._numWheels = numWheels 4. super().__init__(numWheels) Section 10.3 Title Which statement should be used to complete the implementation of the constructor? type mc section 10.3 Calling the Superclass Constructor id testbank-py-1-ch10-30 39. What must be included in the subclass constructor as the first statement? 1. Initialization of all instance variables 2. A call to the superclass constructor 3. A call to the accessor and mutator methods 4. A call to the subclass constructor Section 10.3 Calling the Superclass Constructor Title What must be included in the subclass constructor as the first statement? type mc section


39.

10.3 Calling the Superclass Constructor id testbank-py-1-ch10-67

40. Which of the following statements is true? 1. A method that is overridden in a subclass can perform a task that is totally different from the task performed by the same method in the superclass. 2. A method that is overridden in a subclass cannot invoke the method in the superclass with the same name. 3. A method that is overridden in a subclass must extend the functionality of the superclass by invoking the superclass method. 4. Every method in a subclass must override a superclass method. Section 10.3 Calling the Superclass Constructor Title What must be included in the subclass constructor as the first statement? type mc from testbank-py-1-ch10-69 section 10.3 Calling the Superclass Constructor id testbank-py-2-ch10-69 41. Consider the following code snippet: class BankAccount : ... def deposit(self, amount) : self._transactionCount = self._transactionCount + 1 super().deposit(amount)

Which of the following statements is correct? 1. This method will call itself. 2. This method calls a public method in its subclass. 3. This method calls a private method in its superclass 4. This method calls a public method in its superclass Section 10.4 Overriding Methods Title Which statement about using the super keyword is true? type mc section 10.4 Overriding Methods id testbank-py-1-ch10-32 42. Consider the following code segment: class Fruit : ...


42.

def getName(self) : ... class Apple(Fruit) : ... def getName(self) : ... Which statement is most correct? 1. The Apple class overrides the Fruit class 2. The Apple class overrides the getName method 3. The Fruit class overrides the Apple class 4. The Fruit class overrides the getName method Section 10.4 Overriding Methods Title What is being overridden? type mc section 10.4 Overriding Methods id testbank-py-1-ch10-35

43. Which method is being overridden in the following code segment? class Dinosaur : def __init__(self) : ... def getName(self) : ... def draw(self) : ... class Triceratops(Dinosaur) : def __init__(self) : ... def draw(self) : ... 1. Dinosaur 2. draw 3. getName 4. Triceratops Section 10.4 Overriding Methods Title Which method is overridden in a code segment? type mc section 10.4 Overriding Methods id testbank-py-1-ch10-36


44. Which method is being overridden in the following code segment? class Car : def __init__(self, make, model, color) : ... def getMake(self) : ... def getModel(self) : ... def getColor(self) : ... class Apple : def __init__(self, color) : ... def getColor(self) : ... 1. getMake 2. getModel 3. getColor 4. No method is being overridden in this code segment Section 10.4 Overriding Methods Title Which method is overridden in a code segment? type mc section 10.4 Overriding Methods id testbank-py-1-ch10-37 45. Consider the following classes: class Dinosaur : ... class Triceratops(Dinosaur) : ... class Pterodactyl(Dinosaur) : ... Which of the following statements is correct? 1. Methods in Dinosaur can call methods in Pterodactyl 2. Methods in Dinosaur can call methods in Triceratops 3. Methods in Triceratops can call methods in Dinosaur 4. Methods in Triceratops can call methods in Pterodactyl Section 10.4 Overriding Methods Title When can a class call methods from another class?


45. type mc section 10.4 Overriding Methods id testbank-py-1-ch10-38 46. Consider the following class definitions: class Vehicle : ... def __init__(self) : self._numAxles = 0 ... def setAxles(self, num) : self._numAxles = num ... class Motorcycle(Vehicle) : def __init__(self) : super().__init__() ________________________ Which statement should be placed in the blank so that all motorcycles have 2 axles? 1. setAxles(2) 2. self.setAxles(2) 3. super().setAxles(2) 4. Vehicle.setAxles(2) Section 10.4 Overriding Methods Title Which statement completes this code segment involving inheritance of methods? type mc section 10.4 Overriding Methods id testbank-py-1-ch10-39 47. Consider the following class definitions: class Dinosaur : ... def eat(self, what) : ... class Triceratops(Dinosaur) : ... ____________________ ... What statement should be placed in the blank to override the implementation of the eat method? 1. allow eat(self, what) :


47.

2. def eat(self, what) : 3. new eat(self, what) : 4. override eat(self, what) : Section 10.4 Overriding Methods Title What method declaration will override a method implementation? type mc section 10.4 Overriding Methods id testbank-py-1-ch10-40

48. Consider the following class definitions: class Fruit : ... def getColor(self) : ... class Apple(Fruit) : ... Which statement is most correct? 1. Apple cannot have a method named getColor 2. Apple inherits the getColor method from Fruit 3. Apple must override the getColor method from Fruit 4. Apple must call the getColor method from Fruit Section 10.4 Overriding Methods Title Which statement about methods is most correct? type mc section 10.4 Overriding Methods id testbank-py-1-ch10-41 49. To compute the salary of a manager, the program must first get the salary of the underlying Employee object and then add a bonus. class Manager(Employee) : ... def getSalary(self) : _________________________ return base + self._bonus Which statement correctly completes the code: 1. base = self.getSalary() 2. base = super().getSalary() 3. base = super().self.getSalary() 4. base = super(self.getSalary())


49.

Section 10.4 Overriding Methods Title Complete the code type mc section 10.4 Overriding Methods id testbank-py-1-ch10-61

50. What type of method is used to extend or replace the functionality of the superclass method? 1. Concrete method 2. Abstract method 3. Overriding method 4. Constructor method Section 10.4 Overriding Methods Title What type of method is used to extend or replace the functionality of the superclass method? type mc section 10.4 Overriding Methods id testbank-py-1-ch10-63 51. When you call a superclass method from a subclass method (without overriding the method), what keyword must replace the self reference? 1. super 2. base 3. reference 4. def Section 10.4 Overriding Methods Title When you call a superclass method from a subclass method (without overriding the method), what keyword must replace the self reference? type mc section 10.4 Overriding Methods id testbank-py-1-ch10-70 52. Consider the following code snippet: class Vehicle : ...


52.

def setVehicleAttributes(self) : ... class Auto(Vehicle) : ... def setVehicleAttributes(self) ... Which of the following statements is correct? 1. The subclass is overloading a superclass method. 2. The subclass is overriding a superclass method. 3. This subclass is referencing a superclass method. 4. The subclass is shadowing a superclass method. Section 10.4 Overriding Methods Title Which statement is correct about this code? type mc from testbank-py-1-ch10-31 section 10.4 Overriding Methods id testbank-py-2-ch10-31

53. Which function must be used to call a method of a superclass? 1. __init__ 2. parent 3. super 4. self Section 10.4 Overriding Methods Title Which function must be used to call a method of a superclass? type mc from testbank-py-1-ch10-33 section 10.4 Overriding Methods id testbank-py-2-ch10-33 54. To override a superclass method in a subclass, the subclass method must: 1. use a different method name than the superclass method. 2. use the same method name as the superclass method. 3. use the same list of parameter variables as the superclass method. 4. use a different list of parameter variables than the superclass method. Section 10.4 Overriding Methods Title What must be done to override a superclass method in a subclass? type


54. mc from testbank-py-1-ch10-34 section 10.4 Overriding Methods id testbank-py-2-ch10-34 55. If a method in a subclass carries out the action of the superclass method and also does some additional work then the method in the subclass is said to ____________________ the functionality of the superclass method. 1. extend 2. interpolate 3. reference 4. replace Section 10.4 Overriding Methods Title What term is used to describe a method that performs carries out the action of the superclass method and also does some additional work? type mc section 10.4 Overriding Methods id testbank-py-2-ch10-81 56. Consider the following code snippet: aVehicle = new Auto() aVehicle.moveForward(200) If the Auto class inherits from the Vehicle class, and both classes have an implementation of the moveForward method with the same set of parameters, which statement is correct? 1. The moveForward method of the Auto class will be executed. 2. The moveForward method of the Vehicle class will be executed. 3. You must specify in the code which class's moveForward method is to be used. 4. It is not possible to determine which class's method is called. Section 10.5 Polymorphism Title Which method will be executed? type mc section 10.5 Polymorphism id testbank-py-1-ch10-42 57. Consider the following program: class Dinosaur : def __init__(self, name="dinosaur") : self._name = name


57.

def display(self) : print(self._name) class Triceratops(Dinosaur) : def __init__(self) : super().__init__("triceratops") x = Triceratops() x.display() What is displayed when it executes? 1. dinosaur 2. triceratops 3. Nothing is displayed 4. The program crashes with a method not implemented error Section 10.5 Polymorphism Title Trace code involving multiple classes type mc section 10.5 Polymorphism id testbank-py-1-ch10-45

58. Consider the following program: class Dinosaur : def __init__(self, name="dinosaur") : self._name = name def display(self) : print(self._name) class Triceratops(Dinosaur) : def __init__(self) : super().__init__("triceratops") x = Dinosaur() x.display() What is displayed when it executes? 1. dinosaur 2. triceratops 3. Nothing is displayed 4. The program crashes with a method not implemented error Section 10.5 Polymorphism Title Trace code involving multiple classes type mc section


58. 10.5 Polymorphism id testbank-py-1-ch10-46 59. What is wrong with the following classes? class Person : ... def getName(self) : return self._name ... class Physician(Person) : ... def getName(self) : return "Dr. " + self.getName() ... 1. The return statement cannot include string concatenation 2. The Physician class cannot contain a method named getName 3. The body of the getName method in Physician contains a logic error 4. Physician is not a subclass of Person Section 10.5 Polymorphism Title What is wrong with these classes? type mc section 10.5 Polymorphism id testbank-py-1-ch10-47 60. Consider the following class: class Pet : def makeSound(self) : raise NotImplementedError This class is said to be: 1. an abstract class 2. a dynamic class 3. an iterator class 4. a method class Section 10.5 Polymorphism Title What type of class is this? type mc section 10.5 Polymorphism id testbank-py-1-ch10-48


61. Consider the following classes: class Vehicle : def __init__(self, type) : self._type = type def getType(self) : return self._type class LandVehicle(Vehicle) : def __init__(self, type) : super().__init__(type) class Auto(LandVehicle) : def __init__(self, type) : super().__init__(type) What is displayed by the following code segment? x = Auto("Sedan") print(x.getType()) 1. Auto 2. Sedan 3. Vehicle 4. A runtime error occurs Section 10.5 Polymorphism Title Trace a code segment involving several classes type mc section 10.5 Polymorphism id testbank-py-1-ch10-49 62. Consider the following code segment: class Employee : def __init__(self, name) : ... def getSalary(self) : ... ... class Programmer(Employee) : def __init__(self, name) : ... def writeProgram(self) : ... Which of the following code segments is not legal? 1. e = Employee("Bob")


62.

1. print(e.getSalary()) 2. e = Employee("Bob") e.writeProgram() 3. p = Programmer("Bob") print(p.getSalary()) 4. p = Programmer("Bob") p.writeProgram() Section 10.5 Polymorphism Title Which method invocation is not legal? type mc section 10.5 Polymorphism id testbank-py-1-ch10-50

63. What term describes the process of manipulating objects that share a set of tasks, even though the tasks are executed in different ways? 1. Inheritance 2. Polymorphism 3. Hierarchy 4. Overriding Section 10.5 Polymorphism Title What term describes the process of manipulating objects that share a set of tasks, even though the tasks are executed in different ways? type mc section 10.5 Polymorphism id testbank-py-1-ch10-54 64. Which of the following statements about abstract methods is true? 1. An abstract method has a name and parameters, but its implementation is not specified. 2. An abstract method has parameters and is fully implemented, but it has no defined name. 3. An abstract method has a name and is fully implemented, but it has no parameters. 4. An abstract method has only a name, but it implementation is not specified and it has no parameters. Section 10.5 Polymorphism Title Which of the following statements about abstract methods is true? type mc section 10.5 Polymorphism id testbank-py-1-ch10-55


65. If a class has an abstract method, which of the following statements is NOT true? 1. You cannot inherit from this class. 2. You cannot construct an object from this class. 3. You can construct an object from this class. 4. All non-abstract subclasses of this class must implement this method. Section 10.5 Polymorphism Title If a class has an abstract method, which of the following statements is NOT true? type mc section 10.5 Polymorphism id testbank-py-1-ch10-57 66. A class from which you cannot create objects is called a/an ____. 1. Concrete class. 2. Non-inheritable class. 3. Superclass. 4. Abstract class. Section 10.5 Polymorphism Title What statement about classes is true? type mc section 10.5 Polymorphism id testbank-py-1-ch10-59 67. Consider the following code snippet: anEmployee = new Programmer() anEmployee.increaseSalary(2500) If the Programmer class inherits from the Employee class, and both classes have an implementation of the increaseSalary method with the same set of parameters, which statement is correct? 1. An additional line of code must be added to the snippet shown previously to specify which method will execute. 2. It is not possible to determine which class's method will be executed without seeing the complete class definitions. 3. The increaseSalary method of the Employee class will be executed. 4. The increaseSalary method of the Programmer class will be executed. Section 10.5 Polymorphism Title Which method will be executed? type mc from testbank-py-1-ch10-43 section 10.5 Polymorphism id


67. testbank-py-2-ch10-43 68. Assume that a Programmer class inherits from an Employee class, and that both classes have an implementation of an increaseSalary method with the same set of parameters. Which class's increaseSalary method is to be executed is determined by: 1. checking whether or not the super function is called in the method body. 2. the number of instance variables in the class. 3. the order in which the programmer declared the classes. 4. the type of the object on which the method is invoked. Section 10.5 Polymorphism Title What does Python use to determine which method to execute? type mc from testbank-py-1-ch10-44 section 10.5 Polymorphism id testbank-py-2-ch10-44 69. Which of the following statements is true? 1. A programmer cannot create an instance a concrete class. 2. A programmer cannot create an instance of an abstract class. 3. Abstract classes are designed to force programmers to create subclasses. 4. Calling any method defined in an abstract class will raise a NotImplementedError exception. Section 10.5 Polymorphism Title Which of the following statements about classes is true? type mc from testbank-py-1-ch10-56 section 10.5 Polymorphism id testbank-py-1-ch10-56 70. What statement is commonly used to prevent a class's user from invoking an abstract method? 1. raise NotImplementedError 2. return NotImplementedError 3. self.NotImplementedError 4. set NotImplementedError Section 10.5 Polymorphism Title What statement is commonly used to prevent a class's user from invoking an abstract method? type mc from testbank-py-1-ch10-58 section


70. 10.5 Polymorphism id testbank-py-2-ch10-58 71. What is the role of polymorphism? 1. Polymorphism allows a programmer to manipulate objects that share a set of tasks, even though the tasks are executed in different ways. 2. Polymorphism allows a programmer to use a subclass object in place of a superclass object. 3. Polymorphism allows a subclass to override a superclass method by providing a completely new implementation. 4. Polymorphism allows a subclass to extend a superclass method by performing the superclass task plus some additional work. Section 10.5 Polymorphism Title What is the role of polymorphism? type mc from testbank-py-1-ch10-74 section 10.5 Polymorphism id testbank-py-2-ch10-74 72. What term is used for a class that does not include any abstract methods? 1. Cement class 2. Concrete class 3. Iron class 4. Steel class Section 10.5 Polymorphism Title What term is used for a class that does not include any abstract methods? type mc section 10.5 Polymorphism id testbank-py-2-ch10-76 73. What object oriented programming concept can often be used to eliminate explicit type tests? 1. Class variables 2. Encapsulation 3. Functions 4. Polymorphism Section 10.5 Polymorphism Title What object oriented programming concept can often be used to eliminate explicit type tests? type mc section 10.5 Polymorphism id


73. testbank-py-2-ch10-77 74. What is dynamic method lookup? 1. Dynamic method lookup is the process of determining, at runtime, what method will be invoked based on the type of the object. 2. Dynamic method lookup is the process of finding a method amongst a collection of classes that do not have a common superclass (other than object). 3. Dynamic method lookup is the process of finding a method in a superclass when it has not been overridden in a subclass. 4. Dynamic method lookup is the process of overriding a method in a subclass that has already been defined in the superclass. Section 10.5 Polymorphism Title What is dynamic method lookup? type mc section 10.5 Polymorphism id testbank-py-2-ch10-78 75. Given the following hierarchy, which class is considered the base class? class GeometricShape : ... class Line(GeometricShape) : ... class Rectangle(GeometricShape) : ... class Square(Rectangle) : ... 1. Square 2. Rectangle 3. Line 4. GeometricShape Section 10.6 Application: A Geometric Shape Class Hierarchy Title What is the base class? type mc section 10.6 Application: A Geometric Shape Class Hierarchy id testbank-py-1-ch10-51 76. Assuming that a class called Oval is already defined with a constructor __init__(self, x, y, width, height), how could this be used to make a circle?


76.

1. Use one value for x and y 2. Pass the same value for each width and height 3. Use one value for x, y, width, and height 4. It is not possible to make a circle using the Oval class Section 10.6 Application: A Geometric Shape Class Hierarchy Title How can you make a circle using the Oval class type mc section 10.6 Application: A Geometric Shape Class Hierarchy id testbank-py-1-ch10-53

77. Given the code snippet below, what instance variables does an object of the Rectangle class have? class GeometricShape : def __init__(self, x, y) : self._x = x self._y = y self._fill = None self._outline = "blue" ... class Rectangle(GeometricShape) : def __init__(self, x, y, width, height) : super().__init__(x, y) self._width = width self._height = height ... 1. _x, _y, _width, _height, _fill, _outline 2. _x, _y, _width, _height 3. _x, _y 4. _width, _height Section 10.6 Application: A Geometric Shape Class Hierarchy Title Given the code snippet below, what instance variables does an object of the Rectangle class have? type mc section 10.6 Application: A Geometric Shape Class Hierarchy id testbank-py-1-ch10-62 78. Given the code snippet below, what methods does an object of the Rectangle class have? class GeometricShape : def __init__(self, x, y) : self._x = x self._y = y


78.

self._fill = None self._outline = "blue" ... def getX(self) : return self._x def getY(self) : return self._y class Rectangle(GeometricShape) : def __init__(self, x, y, width, height) : super().__init__(x, y) self._width = width self._height = height def getWidth(self) : return self._width def getHeight(self) : return self._height 1. getWidth(), getHeight() 2. getX(), getY(), getWidth(), getHeight() 3. getX(), getY(), setColor() 4. getX(), getY(), getWidth(), getHeight() Section 10.6 Application: A Geometric Shape Class Hierarchy Title Given the code snippet below, what instance variables does an object of the Rectangle class have? type mc section 10.6 Application: A Geometric Shape Class Hierarchy id testbank-py-1-ch10-68

79. Assuming the Rectangle class is already designed with a constructor __init__(self, x, y, width, height), which code snippet creates a square in the top left corner? 1. square = Rectangle(0, 0, 100, 100) 2. square = Rectangle(100, 100, 0, 0) 3. square = Rectangle(0, 0, 0, 0) 4. square = Rectangle(100, 100, 100, 100)


79.

Section 10.6 Application: A Geometric Shape Class Hierarchy Title Assuming the Rectangle class is already designed with a constructor __init__(self, x, y, width, height), which code snippet creates a square in the top left corner? type mc section 10.6 Application: A Geometric Shape Class Hierarchy id testbank-py-1-ch10-71

80. Assuming the Rectangle class is already designed with a constructor __init__(self, x, y, width, height), which code snippet creates a square in the middle of a frame with FRAME_WIDTH = 400, FRAME_HEIGHT = 600? 1. square = Rectangle(FRAME_WIDTH/2, FRAME_HEIGHT/2, 100, 100) 2. square = Rectangle(FRAME_WIDTH, FRAME_HEIGHT, 100, 100) 3. square = Rectangle(FRAME_WIDTH-50, FRAME_HEIGHT - 50, 100, 100) 4. square = Rectangle(FRAME_WIDTH/2 - 50, FRAME_HEIGHT/2 - 50, 100, 100) Section 10.6 Application: A Geometric Shape Class Hierarchy Title Assuming the Rectangle class is already designed with a constructor __init__(self, x, y, width, height), which code snippet creates a square in the top left corner? type mc section 10.6 Application: A Geometric Shape Class Hierarchy id testbank-py-1-ch10-72 81. Consider a class hierarchy for representing shapes. The hierarchy includes a GeometricShape base class that defines and manages all of characteristics and operations that are common to all shapes. A portion of this class is shown below: class GeometricShape : def __init__(self, x, y): self._x = x self._y = y self._fill = None self._outline = "black" def setColor(self, color) : self._fill = color self._outline = color def getX(self) : return self._x


81.

def setPosition(self, newx, newy) : self._x = newx self._y = newy def draw(self, canvas) : raise NotImplementedError Which method must be overridden in a subclass of GeometricShape? 1. draw 2. getX 3. setColor 4. setPosition Section 10.6 Application: A Geometric Shape Class Hierarchy Title What methods must be overridden to create new shapes? type mc from testbank-py-1-ch10-52 section 10.6 Application: A Geometric Shape Class Hierarchy id testbank-py-2-ch10-52

82. Key presses and mouse clicks are referred to as: 1. actions. 2. activities. 3. events. 4. movements. Section 10.6 Application: A Geometric Shape Class Hierarchy Title Key presses and mouse clicks are referred to as: type mc section 10.6 Application: A Geometric Shape Class Hierarchy id testbank-py-3-ch10-82 83. Assume that framesPerSecond has previously been initialized to 30 and that clock and display have also been initialized appropriately. Which statement should be included at the bottom of the game loop so that game elements appear to move smoothly? 1. clock.tick(framesPerSecond) 2. clock.sleep(framesPerSecond) 3. display.fill(framesPerSecond) 4. display.update(framesPerSecond) Section 10.6 Application: A Geometric Shape Class Hierarchy Title Which statement should be included at the bottom of the game loop so that game elements appear to move smoothly? type mc


83.

section 10.6 Application: A Geometric Shape Class Hierarchy id testbank-py-3-ch10-83

84. An image that can be displayed efficiently in a game is referred to as a: 1. bitmap. 2. fairy. 3. graphic. 4. sprite. Section 10.6 Application: A Geometric Shape Class Hierarchy Title An image that can be displayed efficiently in a game is referred to as a: type mc section 10.6 Application: A Geometric Shape Class Hierarchy id testbank-py-3-ch10-84


1. Consider the triangleArea function from the textbook shown below: 1. def triangleArea(sideLength) : 2. if sideLength <= 0 : 3. return 0 4. if sideLength == 1 : 5. return 1 6. smallerSideLength = sideLength - 1 7. smallerArea = triangleArea(smallerSideLength) 8. area = smallerArea + sideLength 9. return area Where is/are the recursive call(s)? 1. line #3 2. line #5 3. lines #3 and #6 4. line #7 Section 11.1 Triangle Numbers Revisited Title Where is the recursive call? type mc section 11.1 Triangle Numbers Revisited id testbank-py-1-ch11-02 2. Consider the triangleArea function from the textbook shown below: 1. def triangleArea(sideLength) : 2. if sideLength <= 0 : 3. return 0 4. if sideLength == 1 : 5. return 1 6. smallerSideLength = sideLength - 1 7. smallerArea = triangleArea(smallerSideLength) 8. area = smallerArea + sideLength 9. return area Where is/are the terminating condition(s)? 1. line #3 2. line #5 3. lines #3 and #5 4. line #7 Section 11.1 Triangle Numbers Revisited Title Where is/are the terminating condition(s)? type mc section 11.1 Triangle Numbers Revisited id testbank-py-1-ch11-03


3. Consider the following code snippet for recursive addition: 1. def add(i, j) : 2. # assumes i >= 0 3. if i == 0 : 4. return j 5. else : 6. return add(i - 1, j + 1) Identify the terminating condition in this recursive function. 1. if i == 0 : 2. return j 3. return add(i - 1, j + 1) 4. There is no terminating condition Section 11.1 Triangle Numbers Revisited Title Identify the terminating condition in code for recursive addition. type mc section 11.1 Triangle Numbers Revisited id testbank-py-1-ch11-06 4. Consider the following code snippet for calculating Fibonacci numbers recursively: 1. def fib(n) : 2. # assumes n >= 0 3. if n <= 1 : 4. return n 5. else : 6. return fib(n - 1) + fib(n - 2) Identify the terminating condition in this recursive function. 1. n<1 2. n <= 1 3. fib(n - 1) 4. fib(n - 1) + fib(n - 1) Section 11.1 Triangle Numbers Revisited Title Identify the terminating condition in code for Fibonacci. type mc section 11.1 Triangle Numbers Revisited


4. id testbank-py-1-ch11-07 5. Consider the following recursive code snippet: 1. def mystery(n, m) : 2. if n <= 0 : 3. return 0 4. if n == 1 : 5. return m 6. return m + mystery(n - 1, m) Identify the terminating condition(s) of function mystery? 1. n <= 0 2. n == 1 3. n <= 0 or n == 1 4. n>0 Section 11.1 Triangle Numbers Revisited Title Identify the terminating condition(s) of function mystery type mc section 11.1 Triangle Numbers Revisited id testbank-py-1-ch11-08 6. Consider the following recursive code snippet: 1. def mystery(n, m) : 2. if n == 0 : 3. return 0 4. if n == 1 : 5. return m 6. return m + mystery(n - 1, m) What value is returned from a call to mystery(1, 5)? 1. 1 2. 5 3. 6 4. 11 Section 11.1 Triangle Numbers Revisited


6. Title Find the return value from the call to mystery(1, 5) type mc section 11.1 Triangle Numbers Revisited id testbank-py-1-ch11-09 7. Consider the following recursive code snippet: 1. def mystery(n, m) : 2. if n == 0 : 3. return 0 4. if n == 1 5. return m 6. return m + mystery(n - 1, m) What value is returned from a call to mystery(3,6) 1. 3 2. 6 3. 18 4. 729 Section 11.1 Triangle Numbers Revisited Title Find the return value from the call to mystery(3, 6). type mc section 11.1 Triangle Numbers Revisited id testbank-py-1-ch11-10 8. Consider the recursive function myPrint: 1. def myPrint(n) : 2. if n < 10 : 3. print(n) 4. else : 5. m = n % 10 6. print(m) 7. myPrint(n / 10) What is printed for the call myPrint(8)? 1. 10 2. 8 3. 4 4. 21


8.

Section 11.1 Triangle Numbers Revisited Title What is printed for the call myPrint(8)? type mc section 11.1 Triangle Numbers Revisited id testbank-py-1-ch11-11

9. Complete the code for the recursive function printSum shown in this code snippet, which is intended to return the sum of digits from 1 to n: 1. def printSum(n) : 2. if n == 0 : 3. return 0 4. else : 5. ________________________________ 1. return printSum(n - 1) 2. return n + printSum(n + 1) 3. return n + printSum(n - 1) 4. return n - printSum(n - 1) Section 11.1 Triangle Numbers Revisited Title Complete the code for the recursive function printSum type mc section 11.1 Triangle Numbers Revisited id testbank-py-1-ch11-13 10. Consider the code for the recursive function myPrint shown in this code snippet: 1. def myPrint(n) : 2. if n == 0 : 3. return 0 4. else : 5. return n + mysteryPrint(n - 1) To avoid infinite recursion, which of the following lines of code should replace the current terminating case? 1. if n == -1 2. if n <= 0 3.


10.

3. if n >= 0 4. The terminating case as shown will avoid infinite recursion Section 11.1 Triangle Numbers Revisited Title Complete the code for the recursive function myPrint type mc section 11.1 Triangle Numbers Revisited id testbank-py-1-ch11-16

11. Consider the following code segment: def fib(n) : # Line 1 if n <= 2 : return 1 # Line 2 else : return fib(n - 1) + fib(n - 2) # Line 3 print(fib(6)) # Line 4 Which line is the base case for this recursive function? 1. Line 1 2. Line 2 3. Line 3 4. Line 4 Section 11.1 Triangle Numbers Revisited Title Which line is the base case for a recursive function? type mc section 11.1 Triangle Numbers Revisited id testbank-py-1-ch11-19 12. The following function is supposed to use recursion to compute the area of a square from the length of its sides. For example, squareArea(3) should return 9. def squareArea(sideLength) : if sideLength == 1 : return 1 else : ____________________ What line of code should be placed in the blank to achieve this goal? 1. return squareArea(sideLength - 1) 2. return 2 * squareArea(sideLength - 1) 3. return 2 * sideLength + squareArea(sideLength - 1) 4. return 2 * (sideLength - 1) + squareArea(sideLength - 1) Section


12. 11.1 Triangle Numbers Revisited Title Which line of code completes this recursive function? type mc section 11.1 Triangle Numbers Revisited id testbank-py-1-ch11-20 13. Consider the following code segment: def triangleArea(sideLength) : if sideLength == 1: return 1 return triangleArea(sideLength - 1) + sideLength print(triangleArea(5)) How many times is the triangleArea function called when this code segment executes? 1. 1 2. 4 3. 5 4. 6 Section 11.1 Triangle Numbers Revisited Title How many times is a recursive function called? type mc section 11.1 Triangle Numbers Revisited id testbank-py-1-ch11-21 14. Consider the following recursive function: def myPrint(n) : if n < 10 : print(n) else : m = n % 10 print(m) myPrint(n // 10) What does this function do? 1. It prints a positive value forward, digit by digit 2. It prints a positive value backward, digit by digit 3. It divides the number by 10 and prints out its last digit 4. It divides the number by 10 and prints out the result Section 11.1 Triangle Numbers Revisited Title What does the recursive function do? type


14. mc from testbank-py-1-ch11-12 section 11.1 Triangle Numbers Revisited id testbank-py-2-ch11-12 15. Consider the following recursive function: def myPrint(n) : if n < 10 : print(n) else : m = n % 10 print(m, end="") myPrint(n // 10) What is printed for the call myPrint(821)? 1. 10 2. 12 3. 128 4. 821 Section 11.1 Triangle Numbers Revisited Title What is printed by a recursive function? type mc from testbank-py-1-ch11-14 section 11.1 Triangle Numbers Revisited id testbank-py-2-ch11-14 16. Consider the following code segment: def mysteryPrint(n) : if n == 0 : return 0 else : return n + mysteryPrint(n - 1) What is returned for the call mysteryPrint(-4)? 1. 0 2. -10 3. -22 4. Nothing. The program crashes with a runtime error. Section 11.1 Triangle Numbers Revisited Title Compute the result of a recursive function type mc


16. from testbank-py-1-ch11-15 section 11.1 Triangle Numbers Revisited id testbank-py-2-ch11-15 17. Consider the following function for computing the greatest common divisor of two integers greater than 0: def gcd(x, y): # Line 1 if x % y == 0: # Line 2 return y # Line 3 else: return gcd(y, x % y) # Line 4 Which line contains a recursive function call? 1. Line #1 2. Line #2 3. Line #3 4. Line #4 Section 11.1 Triangle Numbers Revisited Title Which line in the function contains the recursive function call? type mc from testbank-py-1-ch11-17 section 11.1 Triangle Numbers Revisited id testbank-py-2-ch11-17 18. This function is supposed to recursively compute x to the power n, where x and n are both non-negative integers: 1. def power(x, n) : 2. if n == 0 : 3. ________________________________ 4. else : 5. return x * power(x, n - 1) What code should be placed in the blank to accomplish this goal? 1. return 1 2. return x 3. return power(x, n - 1) 4. return x * power(x, n - 1) Section 11.1 Triangle Numbers Revisited Title Complete this code to recursively compute x to the power n. type mc section 11.1 Triangle Numbers Revisited id


18. testbank-py-1-ch11-18 19. What is required to make a recursive function successful? I. One or more special cases that handle the simplest computations directly II. A recursive call to a smaller or simpler version of the problem III. Mutually recursive calls 1. I only 2. II only 3. I and II only 4. I, II, and III Section 11.1 Triangle Numbers Revisited Title What is required in a recursive function? type mc from testbank-py-1-ch11-01 section 11.1 Triangle Numbers Revisited id testbank-py-2-ch11-01 20. Consider the triangleArea function from the textbook shown below: 1. def triangleArea(sideLength) : 2. if sideLength <= 0 : 3. return 0 4. if sideLength == 1 : 5. return 1 6. smallerSideLength = sideLength - 1 7. smallerArea = triangleArea(smallerSideLength) 8. area = smallerArea + sideLength 9. return area What will happen if line #6 is changed to: smallerSideLength = sideLength 1. Infinite recursion will occur when sideLength is equal to 0. 2. Infinite recursion will occur when sideLength is equal to 1. 3. Infinite recursion will occur when sideLength is greater than or equal to 2. 4. Infinite recursion will occur for any value of sideLength. Section 11.1 Triangle Numbers Revisited Title When will infinite recursion occur? type mc from testbank-py-1-ch11-04 section 11.1 Triangle Numbers Revisited id


20.

testbank-py-2-ch11-04

21. Consider the triangleArea function from the textbook shown below: 1. def triangleArea(sideLength) : 2. if sideLength <= 0 : 3. return 0 4. if sideLength == 1 : 5. return 1 6. smallerSideLength = sideLength - 1 7. smallerArea = triangleArea(smallerSideLength) 8. area = smallerArea + sideLength 9. return area What will happen if lines #2 and #3 are replaced with the following code segment? if sideLength <= 0 : return sideLength 1. The function will still return correct results for all triangles with non-negative side lengths. 2. The function will return incorrect results when the side length is equal to 0. 3. The function will return incorrect results when the side length is equal to 1. 4. The function will return an area value that is too large for all triangles with non-negative side lengths. Section 11.1 Triangle Numbers Revisited Title Determine the impact of changes made to a recursive function type mc from testbank-py-1-ch11-05 section 11.1 Triangle Numbers Revisited id testbank-py-2-ch11-05 22. A recursive computation solves a problem using the solution to the same problem with ____________________ inputs. 1. floating point 2. integer 3. more complex 4. simpler Section 11.1 Triangle Numbers Revisited Title How does a recursive solution solve a problem? type mc section 11.1 Triangle Numbers Revisited id testbank-py-2-ch11-79 23. Consider the following code segment:


23. ____________________ if x % y == 0: return y else: return gcd(y, x % y) Which statement should be placed in the blank to complete the recursive function definition? 1. def gcd(x, y) : 2. def gcd(x, y, z) : 3. def x(gcd, y) 4. def y(gcd, x) Section 11.1 Triangle Numbers Revisited Title Which statement completes the recursive function definition? type mc section 11.1 Triangle Numbers Revisited id testbank-py-2-ch11-81 24. What term is used to describe a function that keeps on calling itself until the program crashes? 1. Indefinite Recursion 2. Infinite Recursion 3. Interface Recursion 4. Mutual Recursion Section 11.1 Triangle Numbers Revisited Title What term is used to describe a function that keeps on calling itself until the program crashes? type mc section 11.1 Triangle Numbers Revisited id testbank-py-2-ch11-82 25. How many recursive calls to the fib function shown below would be made from an original call to fib(4)? (Do not count the original call) 1. def fib(n) : 2. # assumes n >= 0 3. if n <= 1 : 4. return n 5. else : 6. return fib(n - 1) + fib(n - 2) 1. 1 2. 2 3. 4 4. 8 Section 11.2 Problem Solving: Thinking Recursively Title


25.

Count the recursive calls to fib. type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-25

26. Which of the following options could be used as a terminating condition for a recursive function that finds the middle character of a String with any number of characters? 1. I. the length of the String is 1 2. II. first and last String characters match 3. III. the String is not empty 1. I 2. II 3. I, II, and III 4. I and III Section 11.2 Problem Solving: Thinking Recursively Title Identifying possible terminating conditions. type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-27 27. Consider the function powerOfTwo shown below: 1. def powerOfTwo(n) : 2. if n == 1 : 3. return True 4. elif n % 2 == 1 : 5. return False 6. else : 7. return powerOfTwo(n / 2) How many recursive calls are made from the original call powerOfTwo(63) (not including the original call)? 1. 6 2. 4 3. 1 4. 0 Section 11.2 Problem Solving: Thinking Recursively Title How many recursive calls are made from the original call of powerOfTwo(63)? type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-29 28. Consider the function powerOfTwo shown below:


28. 1. def powerOfTwo(n) : 2. if n == 1 : 3. return True 4. elif n % 2 == 1 : 5. return False 6. else : 7. return powerOfTwo(n / 2) How many recursive calls are made from the original call powerOfTwo(64) (not including the original call)? 1. 8 2. 6 3. 4 4. 2 Section 11.2 Problem Solving: Thinking Recursively Title How many recursive calls are made from the original call of powerOfTwo(64)? type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-30 29. Complete the code for the myFactorial recursive function shown below, which is intended to compute the factorial of the value passed to the function: 1. def myFactorial(n) : 2. if n == 1 : 3. return 1 4. else : 5. _______________________ 1. return n * myFactorial(n) 2. return (n - 1) * myFactorial(n) 3. return n * myFactorial(n - 1) 4. return (n - 1) * myFactorial(n - 1) Section 11.2 Problem Solving: Thinking Recursively Title Complete the code for the myFactorial recursive function. type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-31 30. Complete the code for the myFactorial recursive function shown below, which is intended to compute the factorial of the value passed to the function:


30. 1. def myFactorial(n) : 2. if _____________________________ : 3. return 1 4. else : 5. return n * myFactorial(n - 1) 1. n == 1 2. (n - 1) == 1 3. n * (n - 1) == 1 4. myFactorial(n) == 1 Section 11.2 Problem Solving: Thinking Recursively Title Complete the code for the myFactorial recursive function. type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-32 31. Complete the code for the myFactorial recursive function shown below, which is intended to compute the factorial of the value passed to the function: 1. def myFactorial(n) : 2. if n == 1 : 3. _____________________________ 4. else : 5. return n * myFactorial(n - 1) 1. return 0 2. return -n 3. return 1 4. return myFactorial(n) Section 11.2 Problem Solving: Thinking Recursively Title Complete the code for the myFactorial recursive function. type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-33


32. Complete the code for the calcPower recursive function shown below, which is intended to raise the base number passed into the function to the exponent power passed into the function: 1. def calcPower(base, exponent) : 2. answer = 0 3. if exponent == 0 : 4. answer = 1 5. else : 6. _____________________________ 7. return answer 1. answer = base * calcPower(base - 1, exponent) 2. answer = base * calcPower(base, exponent - 1) 3. answer = base * calcPower(base, exponent) 4. answer = base * calcPower(base - 1, exponent - 1) Section 11.2 Problem Solving: Thinking Recursively Title Complete the code for the calcPower recursive function. type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-34 33. Given the following code: def main() : recurse(3) def recurse(n) : total = 0 if n == 0 : return 0 else : total = 3 + recurse(n - 1) print(total) return total main() What values will be printed when this code is executed? 1. 1, 3, and 6 2. 1, 3, 6, and 9 3. 3, 6, and 9 4. 3, 6, 9, and 12 Section 11.2 Problem Solving: Thinking Recursively


33. Title What values will this recursive code sample print? type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-35 34. Given the following code: def main() : recurse(4) def recurse(n) : total = 0 if n == 0 : return 0 else : total = 4 + recurse(n - 2) print(total) return total main() What values will be printed when this code is executed? 1. 0, 4, and 8 2. 4 and 8 3. 4 4. 8 Section 11.2 Problem Solving: Thinking Recursively Title What values will this recursive code sample print? type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-36 35. The following code segment is supposed to sum the numbers from 1 up to and including n using recursion. def sumOneToN(n) : if n == 0 : return 0 ____________________ Which statement should be placed in the blank to achieve this goal? 1. return sumOneToN(n) 2. return n + sumOneToN(n) 3. return n + sumOneToN(n - 1) 4. return n + sumOneToN(n) - 1


35.

Section 11.2 Problem Solving: Thinking Recursively Title Which statement will complete a recursive function? type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-37

36. What is displayed by the following code segment? def mystery(n) : if n == 0 : return 0 else : return n % 10 + mystery(n // 10) print(mystery(0)) 1. 0 2. 1 3. 10 4. A runtime error is reported Section 11.2 Thinking Recursively Title Trace a call to a recursive function type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-38 37. What is displayed by the following code segment? def mystery(n) : if n == 0 : return 0 else : return n % 10 + mystery(n // 10) print(mystery(-1)) 1. 0 2. 1 3. 10 4. A runtime error is reported Section 11.2 Thinking Recursively Title


37. Trace a call to a recursive function type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-39 38. What is displayed by the following code segment? def mystery(n) : if n == 0 : return 0 else : return n % 10 + mystery(n // 10) print(mystery(123)) 1. 0 2. 1 3. 6 4. 123 Section 11.2 Thinking Recursively Title Trace a call to a recursive function type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-40 39. Consider the following code segment: def mystery(s, c) : if len(s) == 0 : return False elif s[i] == c : return True else : return mystery(s[1 : ], c) What does the mystery function do? 1. It removes the first character from s 2. It counts the number of times c is present in s 3. It determines whether or not c occurs in s 4. It removes all occurrences of c from s Section 11.2 Problem Solving: Thinking Recursively Title What does this recursive function do? type


39. mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-41 40. What is displayed when the following program executes? def mystery(s) : return s[len(s) - 1] + mystery(s[0 : len(s) - 1]) mystery("123") 1. 0 2. 6 3. 123 4. 321 Section 11.2 Problem Solving: Thinking Recursively Title Trace this recursive function type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-42 41. When a recursive function is called, and it does not perform recursion, what must be true? 1. The terminating condition was true. 2. One recursive case condition was true. 3. All recursive case conditions were true. 4. An exception occurred in the function. Section 11.2 Problem Solving: Thinking Recursively Title Why would a recursive function not perform recursion? type mc from testbank-py-1-ch11-22 section 11.2 Problem Solving: Thinking Recursively id testbank-py-2-ch11-22 42. Consider the triangleArea function from the textbook shown below: 1. def triangleArea(sideLength) : 2. if sideLength <= 0 : 3. return 0 4. if sideLength == 1 : 5. return 1 6. smallerSideLength = sideLength - 1


42. 7. smallerArea = triangleArea(smallerSideLength) 8. area = smallerArea + sideLength 9. return area What will happen if lines 4 and 5 are replaced with the following lines of code? if sideLength == 1 : return 2 1. It would increase the result calculated by the function for all calls except those where sideLength <= 0 2. It would not make any difference to any call 3. It would double the result calculated by the function for all calls 4. It would reduce the result calculated by the function by 1 for all calls Section 11.2 Problem Solving: Thinking Recursively Title What impact will a change have on a recursive function? type mc from testbank-py-1-ch11-23 section 11.2 Problem Solving: Thinking Recursively id testbank-py-2-ch11-23 43. Consider the triangleArea function from the textbook shown below: 1. def triangleArea(sideLength) : 2. if sideLength <= 0 : 3. return 0 4. if sideLength == 1 : 5. return 1 6. smallerSideLength = sideLength - 1 7. smallerArea = triangleArea(smallerSideLength) 8. area = smallerArea + sideLength 9. return area Assume that line #5 is changed to this: smallerArea = triangleArea(sideLength) This would cause infinite recursion for __________________________________ 1. triangles with sideLength equal to 0 2. triangles with sideLength equal to 1 3. triangles with sideLength greater than or equal to 1 4. triangles of any sideLength Section 11.2 Problem Solving: Thinking Recursively Title When will infinite recursion occur? type mc section 11.2 Problem Solving: Thinking Recursively id testbank-py-1-ch11-24


44. Consider the following function: 1. def mystery(n, m) : 2. if n == 0 : # special case 1 3. return 0 4. if n == 1 : # special case 2 5. return m 6. return m + mystery(n - 1), m) What will happen if lines #2 and #3 were swapped with lines #4 and #5? 1. The original function and the modified function will return the same result for all integer values of n and m. 2. The original function and the modified function will return different results for all integer value of n and m. 3. The original function and the modified function will return the same result when n is greater than m, and different results when m is greater than n. 4. The original function and the modified function will return the same result when n is less than m, and different results when m is less than n. Section 11.2 Problem Solving: Thinking Recursively Title Would switching the special case order affect the return value of function mystery? type mc from testbank-py-1-ch11-26 section 11.2 Problem Solving: Thinking Recursively id testbank-py-2-ch11-26 45. Consider the function powerOfTwo shown below: 1. def powerOfTwo(n) : 2. if n == 1 : 3. return True 4. elif n % 2 == 1 : 5. return False 6. else : 7. return powerOfTwo(n / 2) What is the best interpretation of lines 2 and 3? 1. One is a power of two. 2. One is not a power of two. 3. Any multiple of one is a power of two. 4. The integer 1 is an invalid choice for n. Section 11.2 Problem Solving: Thinking Recursively Title Analyze the powerOfTwo function type mc from testbank-py-1-ch11-28 section


45.

11.2 Problem Solving: Thinking Recursively id testbank-py-2-ch11-28

46. A palindrome is a word or phrase spelled which reads the same forward or backward. Consider the following code snippet: def palindrome(s) : return isPal(s, 0, len(s) - 1) def isPal(s, left, right) : if left >= right : return True elif s[left] == s[right] : return isPal(s, left + 1, right - 1) else : return False What does the function palindrome return? 1. True 2. False 3. a palindrome not found exception 4. the Boolean value returned from the isPalfunction Section 11.3 Recursive Helper Functions Title What does the function palindrome return? type mc section 11.3 Recursive Helper Functions id testbank-py-1-ch11-44 47. What is the purpose of a recursive helper function? 1. Shield the user of the recursive function from the recursive details 2. Speed up the execution 3. Eliminate the recursion 4. Add another base case Section 11.3 Recursive Helper Functions Title What is the purpose of a recursive helper function? type mc section 11.3 Recursive Helper Functions id testbank-py-1-ch11-45 48. Consider the following code segment: def sumList(data) : return sumListIndex(data, 0)


48. def sumListIndex(data, i) : if i == len(data) : return 0 else : return data[i] + sumListIndex(data, i + 1) This code segment contains an example of 1. a recursive helper function 2. backtracking 3. iteration 4. mutual recursion Section 11.3 Recursive Helper Functions Title What feature does this code segment contain? type mc section 11.3 Recursive Helper Functions id testbank-py-1-ch11-46 49. The printList function is supposed to print all of the elements in a list, one per line. What line of code should be placed in the blank to achieve this goal? def printList(data) : ____________________ def printHelper(data, i) : if i == len(data) : return print(data[i]) printHelper(data, i + 1) 1. print(data) 2. printHelper(data) 3. printHelper(data, 0) 4. printHelper(data, len(data)) Section 11.3 Recursive Helper Functions Title Complete the code segment involving a recursive helper function type mc section 11.3 Recursive Helper Functions id testbank-py-1-ch11-47 50. The following code segment is supposed to determine whether or not a string is a palindrome, meaning that it is the same forward and backward. def isPalindrome(s) : return palindromeHelper(s, l, h)


50. def palidromeHelper(s, l, h) : if h <= l : return True if s[l] != s[h] : return False ____________________ What line of code should be placed in the blank to achieve this goal? 1. isPalindrome(s, l, h) 2. isPalindrome(s, l + 1, h - 1) 3. palindromeHelper(s, l, h) 4. palindromeHelper(s, l + 1, h - 1) Section 11.3 Recursive Helper Functions Title Complete the function for determining if a string is a palindrome type mc section 11.3 Recursive Helper Functions id testbank-py-1-ch11-48 51. A palindrome is a word or phrase that reads the same forward and backward. Consider the functions palindrome and isPal shown below: def palindrome(s) : return isPal(s, 0, len(s) - 1) def isPal(s, left, right) : if left >= right : return True elif s[left] == s[right] : return isPal(s, left + 1, right - 1) else : return False The function isPal as shown here would be considered to be a ____ function. 1. iterative 2. method 3. helper 4. static Section 11.3 Recursive Helper Functions Title The function shown is considered to be a ____ function. type mc from testbank-py-1-ch11-43 section 11.3 Recursive Helper Functions id testbank-py-2-ch11-43


52. Why does the best recursive function usually run slightly slower than its iterative counterpart? 1. Testing the terminating condition takes longer. 2. Each recursive function call takes processor time. 3. Multiple recursive cases must be considered. 4. Checking multiple terminating conditions take more processor time. Section 11.4 The Efficiency of Recursion Title Why does the best recursive function usually run slightly slower than its iterative counterpart? type mc section 11.4 The Efficiency of Recursion id testbank-py-1-ch11-49 53. Which statement(s) about recursion are true? I. Recursion is faster than iteration II. Recursion is often easier to understand than iteration III. Recursive design has an economy of thought 1. I 2. II 3. II and III 4. I and III Section 11.4 The Efficiency of Recursion Title Identify the characteristics of recursion. type mc section 11.4 The Efficiency of Recursion id testbank-py-1-ch11-50 54. In recursion, the terminating condition is analogous to a loop _________. 1. call 2. iteration 3. termination condition 4. initialization condition Section 11.4 The Efficiency of Recursion Title In recursion, the terminating condition is analogous to a loop __________. type mc section 11.4 The Efficiency of Recursion id testbank-py-1-ch11-51 55. Consider the following code segment for computing Fibonacci numbers. How many times is fib(3) computed in order to compute fib(7)? def fib(n) : if n <= 2 :


55.

return 1 else : return fib(n - 1) + fib(n - 2) 1. 1 2. 3 3. 5 4. 7 Section 11.4 Efficiency of Recursion Title How many times is a smaller Fibonacci computed when computing a larger Fibonacci number? type mc section 11.4 The Efficiency of Recursion id testbank-py-1-ch11-52

56. How many squares are drawn by the following code segment? def tSquare(width, x, y, canvas) : canvas.drawRect(x, y, width, width) if width >= 4 : tSquare(width / 2, x, y, canvas) tSquare(width / 2, x + width / 2, canvas) tSquare(width / 2, x, y + width / 2, canvas) tSquare(width / 2, x + width / 2, y + width / 2, canvas) # Code to setup the canvas has been omitted tSquare(0, 0, 8, canvas) 1. 1 2. 4 3. 5 4. 8 Section 11.4 The Efficiency of Recursion Title Determine the number of squares drawn by a recursive function type mc section 11.4 The Efficiency of Recursion id testbank-py-1-ch11-53 57. How many squares are drawn by the following code segment? def tSquare(width, x, y, canvas) : canvas.drawRect(x, y, width, width) if width >= 4 : tSquare(width / 2, x, y, canvas) tSquare(width / 2, x + width / 2, canvas) tSquare(width / 2, x, y + width / 2, canvas)


57.

tSquare(width / 2, x + width / 2, y + width / 2, canvas) # Code to setup the canvas has been omitted tSquare(0, 0, 16, canvas) 1. 16 2. 21 3. 64 4. 85 Section 11.4 The Efficiency of Recursion Title Determine the number of squares drawn by a recursive function type mc section 11.4 The Efficiency of Recursion id testbank-py-1-ch11-54

58. Which of the following strings is a palindrome? 1. "Test" 2. "B" 3. "canal" 4. "salami" Section 11.5 Permutations Title Which of the following strings is a palindrome? type mc section 11.5 Permutations id testbank-py-1-ch11-55 59. The string "eat" has ____ permutations. 1. 2 2. 4 3. 6 4. 8 Section 11.5 Permutations Title The string "eat" has ____ permutations. type mc section 11.5 Permutations id testbank-py-1-ch11-56 60. A unique permutation is one that is different from any other generated permutation. How many unique permutations does the string "bee" have? 1. 2 2. 3 3. 4


60.

4. 5 Section 11.5 Permutations Title How many unique permutations does the string "bee" have? type mc section 11.5 Permutations id testbank-py-1-ch11-57

61. How many permutations are in a 5 letter word? 1. 5 2. 120 3. 12 4. 1 Section 11.5 Permutations Title How many permutations are in a 5 letter word? type mc section 11.5 Permutations id testbank-py-1-ch11-58 62. Which of the following statements about recursion is correct? 1. It is not necessary to have a special terminating case in all recursions. 2. It is not necessary to simplify the argument in the recursive call. 3. A recursive solution will always run faster than an equivalent iterative solution. 4. In many cases, a recursive solution will be easier to understand and to implement than an iterative solution. Section 11.5 Permutations Title Which of the following statements about recursion is correct? type mc section 11.5 Permutations id testbank-py-1-ch11-59 63. Which of the following statements about palindromes is correct? 1. The empty string is not a palindrome. 2. The string "I" is not a palindrome. 3. The string "rascal" is a palindrome. 4. All strings of length 0 or 1 are palindromes. Section 11.5 Permutations Title Which of these statements about palindromes is correct? type mc


63. section 11.5 Permutations id testbank-py-1-ch11-60 64. Recall the permutations function from Section 11.5 in the textbook. def permutations(word) : result = [] ____________________ result.append(word) return result else: for i in range(len(word)) : shorter = word[ : i] + word[i + 1 : ] shorterPermutations = permutations(shorter) for string in shorterPermutations : result.append(word[i] + string) return result In the textbook, the line now represented by the blank was if len(word) == 0 :. What line of code could be used instead to achieve the same list of permutations? 1. if len(word) == 1 : 2. if len(word) == [] 3. if word == [] : 4. if word == letter : Section 11.5 Permutations Title Complete the code segment for computing all permutations of a word type mc section 11.5 Permutations id testbank-py-1-ch11-61 65. Recall the permutations function from Section 11.5 in the textbook. def permutations(word) : result = [] if len(word) == 0 : result.append(word) return result else: ____________________ shorter = word[ : i] + word[i + 1 : ]


65.

shorterPermutations = permutations(shorter) for string in shorterPermutations : result.append(word[i] + string) return result In the textbook, the line now represented by the blank was for i in range(len(word)) :. What would happen if the blank was filled in with for i in range(len(word) - 1, -1, -1) : 1. The same permutations of the word would be generated in the same order 2. The same permutations of the word would be generated in the reverse order 3. The same permutations of the word would be generated in another order that is not the same as the original code segment, or the reverse of the original order 4. The modified code segment will not generate the same set of permutations Section 11.5 Permutations Title What is the impact of replacing a line of code in the permutations function? type mc section 11.5 Permutations id testbank-py-1-ch11-62

66. Recall the permutations function from Section 11.5 in the textbook. def permutations(word) : result = [] if len(word) == 0 : result.append(word) return result else: for i in range(len(word)) : shorter = word[ : i] + word[i + 1 : ] shorterPermutations = permutations(shorter) for string in shorterPermutations : result.append(word[i] + string) return result What is the base case for this function? 1. The empty list 2. Any list containing exactly one character 3. The empty string 4. Any string containing exactly one character Section 11.5 Permutations Title Identify the base case for the permutations function type mc section


66. 11.5 Permutations id testbank-py-1-ch11-63 67. Recall the permutations function from Section 11.5 in the textbook. def permutations(word) : result = [] if len(word) == 0 : result.append(word) return result else: for i in range(len(word)) : shorter = word[ : i] + word[i + 1 : ] shorterPermutations = permutations(shorter) for string in shorterPermutations : result.append(word[i] + string) return result How permutations will be generated by calling permutations("code")? 1. 1 2. 4 3. 10 4. 24 Section 11.5 Permutations Title How many permutations are generated when the permutations function is called? type mc section 11.5 Permutations id testbank-py-1-ch11-64 68. _______________ is a problem-solving technique that examines partial solutions, abandons unsuitable ones, and returns to consider other candidate solutions. 1. Debugging 2. Traceback 3. Backtracking 4. Recursion Section 11.6 Backtracking Title ____ is a problem-solving technique that examines partial solutions. type mc section 11.6 Backtracking id testbank-py-1-ch11-66


69. Recall the backtracking strategy outlined in the textbook. A similar strategy can be used to solve Sudoku puzzles. def solve(gameBoard) : status = examine(gameBoard) if status == CONTINUE : for nextBoard in extend(gameBoard) : solve(nextBoard) elif status == ACCEPT: ____________________ What code should be placed in the blank to complete the solution to this problem? 1. print(status) 2. print(gameBoard) 3. solve(gameBoard) 4. gameBoard = extend(gameBoard) Section 11.6 Backtracking Title Complete the backtracking algorithm type mc section 11.6 Backtracking id testbank-py-1-ch11-67 70. Which statement about backtracking is correct? 1. Backtracking starts from the end of the program and works backward to the beginning. 2. Backtracking builds up partial solutions that get increasingly closer to the goal. 3. Backtracking never abandons a partial solution. 4. Backtracking explores only one path toward a solution. Section 11.6 Backtracking Title How does backtracking work? type mc from testbank-py-1-ch11-65 section 11.6 Backtracking id testbank-py-2-ch11-65 71. Which problem is well suited to being solved with a backtracking algorithm? 1. Computing Fibonacci numbers 2. Determining the factorial of a number 3. Evaluating an expression 4. Finding a solution to the eight queens problem Section 11.6 Backtracking Title Which problem is well suited to being solved with a backtracking algorithm? type


71. mc section 11.6 Backtracking id testbank-py-2-ch11-83 72. Recursion will take place if any of the following happen: I. function A calls function B, which calls function C II. function A calls function B, which calls function A III. function A calls function A 1. I 2. I and II 3. II 4. II and III Section 11.7 Mutual Recursion Title Describe conditions necessary for recursion. type mc section 11.7 Mutual Recursion id testbank-py-1-ch11-68 73. Consider the following code snippet: def isEven(num) : if num % 2 == 0 : return True else : return isOdd(num) def isOdd(num) : if num % 2 == 1 : return True else : return isEven(num) For any given value of num, what is the maximum number of function calls that could occur? 1. 0 2. 1 3. 2 4. cannot be determined Section 11.7 Mutual Recursion Title For any given value of n, what is the maximum number of function calls that could occur? type mc section 11.7 Mutual Recursion id testbank-py-1-ch11-69


74. Complete the following code snippet, which is intended to determine if a value is even or odd using mutual recursion: def isEven(num) : if num == 0 : return True else : return isOdd(abs(num) - 1) def isOdd(num) : if num == 0 : ________________________ else : return isEven(abs(num) - 1) 1. return True 2. return False 3. return isOdd(abs(num) - 1) 4. return isOdd(abs(num)) Section 11.7 Mutual Recursion Title Complete this code for mutual recursion. type mc section 11.7 Mutual Recursion id testbank-py-1-ch11-70 75. Consider the following code segment: def f1(n) : if n < 0 : return 0 if n % 2 == 1 : return n return f2(n + 1) def f2(n) : if n < 0 : return 0 if n % 2 == 0 : return n return f1(n // 2) This code segment would be classified as: 1. backtracking 2. mutually recursive 3. non-recursive 4. object oriented Section 11.7 Mutual Recursion Title


75. Identify the nature of a code segment type mc section 11.7 Mutual Recursion id testbank-py-1-ch11-72 76. Consider the following code segment: def f1(n) : if n < 0 : return 0 if n % 2 == 1 : return n return f2(n + 1) def f2(n) : if n < 0 : return 0 if n % 2 == 0 : return n return f1(n // 2) print(f1(10)) When this code is run, it will display: 1. 0 2. 5 3. 10 4. 11 Section 11.7 Mutual Recursion Title Trace a pair of mutually recursive functions type mc section 11.7 Mutual Recursion id testbank-py-1-ch11-73 77. Consider the following code segment: def f1(n) : if n < 0 : return 0 if n % 2 == 1 : return n return f2(n + 1) def f2(n) : if n < 0 :


77.

return 0 if n % 2 == 0 : return n return f1(n // 2) print(f2(7)) When this code is run, it will display: 1. 0 2. 1 3. 3 4. 7 Section 11.7 Mutual Recursion Title Trace a pair of mutually recursive functions type mc section 11.7 Mutual Recursion id testbank-py-1-ch11-74

78. Consider the following code segment: def f(n) : if n == 1 : return n elif n == 2 : ____________________ else : return f(n // 2) def g(n) : if n % 2 == 0 : return n - 1 else : return f(n - 1) What statement should be placed in the blank to make these functions mutually recursive? 1. return f() 2. return f(n - 1) 3. return g() 4. return g(n - 1) Section 11.7 Mutual Recursion Title Which statement will make the functions mutually recursive? type mc section 11.7 Mutual Recursion id testbank-py-1-ch11-75


79. The following code segment is supposed to determine if an integer, n, is even or odd using mutual recursion. def isEven(n) : if n == 0 : return True else : return isOdd(abs(n) - 1) def isOdd(n) : ____________________ return False else : return isEven(abs(n) - 1) What code should be placed in the blank to achieve this goal? 1. if n == 0 : 2. if n == 1 : 3. if n % 2 == 1 : 4. if n // 2 == 0 : Section 11.7 Mutual Recursion Title What line of code will complete these mutually recursive functions? type mc from testbank-py-1-ch11-71 section 11.7 Mutual Recursion id testbank-py-2-ch11-71 80. What library is used to load a webpage into a data structure that makes it easy to extract the page's tags and the information between the tags? 1. Beautiful Soup 2. Carrot Cake 3. Pretty Pie 4. Roasted Potatoes Section 11.7 Mutual Recursion Title What library is used to load a webpage into a data structure that makes it easy to extract the page's tags and the information between the tags? type mc section 11.7 Mutual Recursion id testbank-py-2-ch11-76 81. Which statement finds all of the links in a webpage? 1. elements = doc.find_all("a") 2. elements = doc.find_all("li") 3. elements = doc.find_all(links) 4. elements = doc.find_links()


81. Section 11.7 Mutual Recursion Title Which statement finds all of the links in a webpage? type mc section 11.7 Mutual Recursion id testbank-py-2-ch11-77 82. Assume that the address variable currently holds the URL for webpage. Which statement(s) store a structured representation of that webpage in the doc variable? 1. response = urllib.request.urlopen(address) doc = bs4.BeautifulSoup(response) 2. doc = bs4.BeautifulSoup(address) 3. response = bs4.BeautifulSoup(address) doc = urllib.request.urlopen(response) 4. doc = import BeautifulSoup(address) Section 11.7 Mutual Recursion Title Which statement returns a structured representation of a webpage? type mc section 11.7 Mutual Recursion id testbank-py-2-ch11-78 83. Which problem is well suited to being solved with mutually recursive functions? 1. Computing the factorial of a number 2. Determining if a string is a palindrome 3. Computing Fibonacci numbers 4. Evaluating a numeric expression Section 11.7 Mutual Recursion Title Which problem is well suited to being solved with mutually recursive functions? type mc section 11.7 Mutual Recursion id testbank-py-2-ch11-80


1. What type of algorithm places elements in order? 1. sorting 2. searching 3. deletion 4. insertion Section 12.1 Selecton Sort Title What type of algorithm places elements in order? type mc section 12.1 Selection Sort id testbank-py-1-ch12-01 2. Which element does selection sort place in the correct location during each iteration? 1. The smallest in the list 2. The smallest element that has not been placed in the correct location during a prior iteration 3. The largest element in the list 4. A random element Section 12.1 Selecton Sort Title Which element does selection sort place in the correct location during each iteration? type mc from testbank-py-1-ch12-02 section 12.1 Selection Sort id testbank-py-2-ch12-02 3. What must hold true after 5 iterations of selection sort when it is working to sort a list of 10 elements? 1. Exactly 5 more iterations are always necessary to complete the sort 2. Exactly 4 more iterations are always necessary to complete the sort 3. Up to 5 more iterations may be needed to complete the sort 4. Up to 4 more iterations may be needed to complete the sort Section 12.1 Selecton Sort Title What must hold true after 5 iterations of selection sort when it is working to sort a list of 10 elements? type mc from testbank-py-1-ch12-03 section 12.1 Selection Sort id testbank-py-2-ch12-03 4. Consider a list of 10 elements that is being sorted into ascending order using the selection sort algorithm. What is guaranteed to be true after the algorithm's outter loop has finished executing for the first time? 1. The largest element will be in the correct place 2. One element will be in the correct place 3. Exactly two elements will be in the correct place


4.

4. At least two elements will be in the correct place Section 12.1 Selecton Sort Title After one iteration of selection sort working on a list of 10 elements, what must hold true? type mc from testbank-py-1-ch12-04 section 12.1 Selection Sort id testbank-py-2-ch12-04

5. Consider the swap function shown below from the SelectionSorter class. If we modified it as shown in the swap2 function shown below, what would be the effect on the sort function? def swap(values, i, j) : temp = values[i] values[i] = values[j] values[j] = temp def swap2(values, i, j) : values[i] = values[j] values[j] = values[i] 1. There would be no effect 2. Some list elements would be overwritten 3. It would sort the list in reverse order 4. It would still be correct, but run a little faster Section 12.1 Selecton Sort Title Consider the swap function shown below from the SelectionSorter class. If we modified it as shown in the swap2 function shown below, what would be the effect on the sort function? type mc section 12.1 Selection Sort id testbank-py-1-ch12-09 6. Suppose you wanted to test your sort on a list filled with different elements each time the code is run. What is an efficient technique for creating a list of 1,000 elements for each run? 1. Run the program many times, entering different values for the list elements. 2. Make a file with many sets of values and loop through them, sorting each one. 3. Use the Random class to generate list elements, sorting each set in a loop. 4. Create many different lists with different elements in the program code and sort each list. Section 12.1 Selecton Sort Title What is an efficient technique to create 1,000 elements for each sort test run? type mc section 12.1 Selection Sort


6. id testbank-py-1-ch12-10 7. Consider the selection sort function shown below: def selectionSort(values) : for i in range(len(values)) : minPos = minimumPosition(values, i) swap(values, minPos, i) The function works correctly in its current form. What would happen if the for loop was replaced with: for i in range(len(values) - 1) :? 1. The list would still be sorted, but it would take one less iteration 2. The list would still be sorted, using the same number of iterations 3. The list would still be sorted, but it would take one more iteration 4. A runtime error would occur Section 12.1 Selection Sort Title What happens when the implementation of selection sort is modified? type mc section 12.1 Selection Sort id testbank-py-1-ch12-11 8. Consider the selection sort function shown below: def selectionSort(values) : for i in range(len(values)) : minPos = minimumPosition(values, i) swap(values, minPos, i) The function works correctly in its current form. What would happen if the line calling swap was replaced with: swap(values, i, minPos)? 1. The list would still be sorted, but it would take one less iteration 2. The list would still be sorted, using the same number of iterations 3. The list would still be sorted, but it would take one more iteration 4. A runtime error would occur Section 12.1 Selection Sort Title What happens when the implementation of selection sort is modified? type mc section 12.1 Selection Sort id testbank-py-1-ch12-12 9. Consider the selection sort function shown below:


9. def selectionSort(values) : for i in range(len(values)) : minPos = minimumPosition(values, i) swap(values, minPos, i) The function works correctly in its current form. What would happen if the for loop was replaced with: for i in range(1, len(values)) :? 1. The list would still be sorted 2. All of the elements in the list, except the first one, would be sorted 3. All of the elements in the list, except the last one, would be sorted 4. A runtime error would occur Section 12.1 Selection Sort Title What happens when the implementation of selection sort is modified? type mc section 12.1 Selection Sort id testbank-py-1-ch12-13 10. Consider the selection sort function and function call shown below: def selectionSort(values) : for i in range(len(values)) : print(values) minPos = minimumPosition(values, i) swap(values, minPos, i) data = [9, 1, 7, 2] selectionSort(data) print(data) What is displayed when this code segment executes? 1. [1, 2, 7, 9] 2. [9, 1, 7, 2] [1, 9, 7, 2] [1, 2, 7, 9] 3. [9, 1, 7, 2] [1, 9, 7, 2] [1, 2, 7, 9] [1, 2, 7, 9] 4. [9, 1, 7, 2] [1, 9, 7, 2]


10.

4. [1, 2, 7, 9] [1, 2, 7, 9] [1, 2, 7, 9]

Section Title Trace Selection Sort for a list containing 4 elements type mc section 12.1 Selection Sort id testbank-py-1-ch12-15 11. Consider the selection sort function and function call shown below: def selectionSort(values) : for i in range(len(values)) : print(values) minPos = minimumPosition(values, i) swap(values, minPos, i) data = [1, 2, 3] selectionSort(data) print(data) What is displayed when this code segment executes? 1. [] 2. [1, 2, 3] 3. [3, 2, 1] 4. [1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3]

Section Title Trace Selection Sort for a list containing elements that are already sorted type mc section 12.1 Selection Sort id testbank-py-1-ch12-16


12. In a sorting algorithm, it may be necessary to find the position of the maximum element in a list, starting from some initial position, start. What code should be placed in the blank to complete the maximumPosition function? def maximumPosition(values, start) : maxPos = start for i in range(start + 1, len(values)) : ____________________ maxPos = i return maxPos 1. if values[maxPos] > values[i] : 2. if values[i] > values[maxPos] : 3. if values[i] < values[maxPos] : 4. if values[i] <= values[maxPos] : Section 12.1 Selection Sort Title Complete the code for finding the maximum value in a list type mc from testbank-py-1-ch12-14 section 12.1 Selection Sort id testbank-py-2-ch12-14 13. Which sorting algorithm sorts a list by repeatedly finding the smallest element of the unsorted tail region and moving it? 1. Insertion sort 2. Merge sort 3. Quick sort 4. Selection sort Section 12.1 Selection Sort Title Which sorting algorithm sorts a list by repeatedly finding the smallest element of the unsorted tail region and moving it? type mc section 12.1 Selection Sort id testbank-py-2-ch12-76 14. The following program is supposed to time the performance of the selectionSort function. Right now it is missing the code, startTime = time(), which records the starting time. Where should the missing code be inserted? # Line 1 values = [] # Line 2 for i in range(10000) : values.append(randint(1, 100))


# Line 3

14. selectionSort(values)

# Line 4 endTime = time() 1. Line 1 2. Line 2 3. Line 3 4. Line 4 Section 12.2 Profiling the Selection Sort Algorithm Title Where should the timing code be placed to profile selection sort? type mc section 12.2 Profiling the Selection Sort Algorithm id testbank-py-1-ch12-17 15. Consider the following variation of the selection sort algorithm: def sort(values) : for i in range(len(values)) : maxPos = i for j in range(i + 1, len(values)) : if values[j] > values[maxPos] : maxPos = j temp = values[maxPos] values[maxPos] = values[i] values[i] = values[maxPos] If this algorithm takes 5 seconds to sort 15,000 elements, how long would you expect it to take to sort 30,000 elements? 1. 5 seconds 2. 10 seconds 3. 25 seconds 4. 50 seconds Section 12.2 Profiling the Selection Sort Algorithm Title How long will selection sort take to execute when the number of elements is doubled? type mc section 12.2 Profiling the Selection Sort Algorithm id testbank-py-1-ch12-18 16. What is returned by the time() function that resides in Python's time module? 1. The number of seconds since the program began executing. 2. The number of milliseconds since the program began executing. 3. The number of seconds since January 1, 1970. 4. The number of milliseconds since January 1, 1970. Section 12.2 Profiling the Selection Sort Algorithm


16.

Title What is returned by the time() function? type mc section 12.2 Profiling the Selection Sort Algorithm id testbank-py-2-ch12-77

17. A particular sorting algorithm visits 0.5n2 + 2.5n - 3 elements in order to sort a list of n elements. Which bigOh expression best describes the growth rate of this sorting algorithm? 1. O(n) 2. O(n2) 3. O(2n) 4. O(0.5) Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title Which big-Oh expression best describes the growth behavior of a function? type mc from testbank-py-1-ch12-05 section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-2-ch12-05 18. A particular algorithm visits n2 + 2n + 30000 elements in order to perform its task on a list of n elements. Which big-Oh expression best describes the growth rate of this algorithm? 1. O(n) 2. O(n2) 3. O(2n) 4. O(30000) Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title Which big-Oh expression best describes the growth behavior of a function? type mc from testbank-py-1-ch12-06 section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-2-ch12-06 19. A particular algorithm visits n3 + nlog(n) + n! elements in order to perform its task on a list of n elements. Which big-Oh expression best describes the growth rate of this algorithm? 1. O(n) 2. O(n3) 3. O(n!)


19.

4. O(nlog(n)) Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title Which big-Oh expression best describes the growth behavior of a function? type mc from testbank-py-1-ch12-07 section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-2-ch12-07

20. Which expression indicates that the number of operations performed by an algorithm grows at least as fast as n2? 1. O(n2) 2. Θ(n2) 3. Ω(n2) 4. Φ(n2) Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title Which expression indicates that the number of operations performed by an algorithm grows at least as fast as n<sup>2</sup>? type mc from testbank-py-1-ch12-08 section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-2-ch12-08 21. After 9 iterations of selection sort working on an list of 10 elements, what must hold true? 1. The largest element is correctly placed by default. 2. One more iteration is needed to complete the sort. 3. The smallest element is incorrectly placed. 4. The largest element is incorrectly placed. Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title After 9 iterations of selection sort on an list of 10 elements, what must hold true? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-19 22. The performance of an algorithm is most closely related to what? 1. The total number of element visits 2. The total number of elements 3. The type of elements 4. The number of lines of code in the method Section


22. 12.3 Analyzing the Performance of the Selection Sort Algorithm Title The performance of an algorithm is related to what? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-20 23. Consider a list with n elements. If we visit each element n times, how many total visits will there be? 1. n 2. 2n 3. nn 4. n2 Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title If we visit each of n elements n times, how many total visits will there be? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-21 24. Suppose an list has n elements. We visit element #1 one time, element #2 two times, element #3 three times, and so forth. How many total visits will there be? 1. 2n 2. n(n + 1) / 2 3. n2 4. n3 Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title How many total element visits will there be in this scenario? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-22 25. Which of the following completes the selection sort function minimumPosition()?


25. def minimumPosition(values, from) : minPos = from for i in range(from + 1, len(values)) : _____________________________ return minPos 1. if values[i] > values[minPos] : minPos = i 2. if values[i] < values[minPos] : minPos = i 3. if values[i] < values[i] : minPos = i 4. if values[i] < values[minPos] : i = minPos Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title Which statement completes selection sort function minimumPosition()? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-24 26. How many comparisons does selection sort make when sorting a list of length n? 1. n 2. log(2n) 3. n(n + 1) / 2 4. n/2 Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title How many comparisons does selection sort make? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-25 27. In Big-Oh notation, selection sort is a(n) ____ algorithm. 1. O(n2) 2. O(1) 3. log n


27.

4. O(log n2) Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title In Big-Oh notation, selection sort is a(n) ____ algorithm. type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-26

28. Consider the following code snippet: def sort(values) : for i in range(1, len(values)) : next = values[i] j=i while j > 0 and values[j-1] > next : values[j] = values[j - 1] j=j-1 values[j] = next What sort algorithm is used in this code? 1. insertion sort 2. selection sort 3. merge sort 4. quicksort Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title What sort algorithm is used in this code? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-27 29. Which sort algorithm starts with an initial sequence of size 1, which is assumed to be sorted, and increases the size of the sorted sequence in the list in each iteration? 1. insertion sort 2. selection sort 3. merge sort 4. quicksort Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title What sort algorithm is used in this code? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-28


30. Consider the following function which increments every value in a list: def incrementList(data) : for i in len(data) : data[i] = data[i] + 1 What is the big-Oh complexity of this algorithm, where n is the number of elements in data? 1. O(1) 2. O(log(n)) 3. O(n) 4. O(n2) Section Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title What is the big-Oh complexity of this function for incrementing every element in a list? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-29 31. Consider the following function which determines whether or not a list contains any repeated values: def hasDuplicate(data) : for i in range(len(data)) : for j in range(i + 1, len(data)) : if data[i] == data[j] : return True return False What is the big-Oh complexity of this algorithm, where n is the number of elements in data? 1. O(1) 2. O(log(n)) 3. O(n) 4. O(n2) Section Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title What is the big-Oh complexity of this function for finding duplicate values in a list? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-30 32. Consider the following function which determines whether or not a sorted list contains any repeated values: def sortedHasDuplicate(data) : for i in range(0, len(data) - 1) : if data[i] == data[i + 1] : return True return False What is the big-Oh complexity of this algorithm, where n is the number of elements in data? 1. O(1)


32.

2. O(log(n)) 3. O(n) 4. O(n2) Section Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title What is the big-Oh complexity of this function for finding duplicate values in a list? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-31

33. When the size of an list increases by a factor of 100, the time required by selection sort increases by a factor of ____. 1. 2,000 2. 5,000 3. 10,000 4. 12,000 Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title When the size increases by a factor of 100, selection sort time increases by a factor of ____. type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-1-ch12-75 34. In big-Oh notation, when we consider the order of the number of visits an algorithm makes, what do we ignore? I. Power of two terms II. The coefficients of the terms III. All lower order terms 1. I only 2. II only 3. I and II only 4. II and III only Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title What do we ignore when we consider the order of the number of visits? type mc from testbank-py-1-ch12-23 section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-2-ch12-23 35. Consider the following big-Oh growth rates: O(n!) O(n3)


35. O(log(n)) O(n log(n)) Which big-Oh growth rate is most desireable? 1. O(n!) 2. O(n3) 3. O(log(n)) 4. O(n log(n)) Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title Which big-Oh growth rate is most desireable? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-2-ch12-78 36. Consider the following big-Oh growth rates: O(1) O(2n) O(n) O(n2) Which big-Oh growth rate is least desireable? 1. O(1) 2. O(2n) 3. O(n) 4. O(n2) Section 12.3 Analyzing the Performance of the Selection Sort Algorithm Title Which big-Oh growth rate is least desireable? type mc section 12.3 Analyzing the Performance of the Selection Sort Algorithm id testbank-py-2-ch12-79 37. How many times can an list with 4,096 elements be cut into two equal pieces? 1. 16 2. 12 3. 10 4. 8 Section 12.4 Merge Sort Title How many times can an list with 4,096 elements be cut into two equal pieces? type mc section 12.4 Merge Sort id testbank-py-1-ch12-33


38. How many times can an list with 729 elements be cut into three equal pieces? 1. 4 2. 5 3. 6 4. 7 Section 12.4 Merge Sort Title How many times can an list with 729 elements be cut into three equal pieces? type mc section 12.4 Merge Sort id testbank-py-1-ch12-34 39. Consider the code for mergeSort shown below, which works correctly: def mergeSort(values) : if len(values) <= 1 : return mid = len(values) // 2 first = values[ : mid] second = values[mid : ] mergeSort(first) mergeSort(second) mergeLists(first, second, values) What would happen if the line mid = len(values) // 2 was replaced with the line mid = len(values) // 4 1. Merge sort would continue to work at the same speed as the original version 2. Merge sort would continue to work, but it would be slower than the original version 3. Merge sort would continue to work, and it would be faster than the original 4. The modified version would not sort the list successfully Section 12.4 Merge Sort Title What is the impact of modifying the mergeSort function? type mc section 12.4 Merge Sort id testbank-py-1-ch12-35 40. What is printed when the following code segment executes? def mergeSort(values) : if len(values) <= 1 : return print(values) mid = len(values) // 2 first = values[ : mid] second = values[mid : ] mergeSort(first) mergeSort(second) mergeLists(first, second, values)


40. # The implementation of mergeLists has been omitted. # It can be found in the textbook. data = [3, 1, 2, 4] mergeSort(data) 1. [1, 2, 3, 4] 2. [3, 1, 2, 4] [1, 2] [3, 4] 3. [3, 1, 2, 4] [3 ,1] [2, 4] 4. [3, 1, 2, 4] [1, 2] [3, 4] [1, 2, 3, 4] Section 12.4 Merge Sort Title Trace this call to the mergeSort function type mc section 12.4 Merge Sort id testbank-py-1-ch12-36 41. Consider this modified version of the mergeLists function. While all of the lines of code are the same, the order of the lines has been changed so that the while loop involving second appears before the while loop involving first. def mergeLists(first, second, values) : iFrist = 0 iSecond = 0 j=0 while iFirst < len(first) and iSecond < len(second) : if first[iFirst] < second[iSecond] : values[j] = first[iFirst] iFirst = iFirst + 1 else : values[j] = second[iSecond] iSecond = iSecond + 1 j=j+1 while iSecond < len(second) : values[j] = second[iSecond]


41.

iSecond = iSecond + 1 j=j+1 while iFrist < len(first) : values[j] = first[iFirst] iFirst = iFirst + 1 j=j+1 What impact will this change have? 1. The mergeLists function will continue to run correctly, and at the same speed 2. The mergeLists function will continue to run correctly, but it will be slower 3. The mergeLists function will continue to run correctly, but it will be faster 4. The mergeLists function will no longer work correctly Section Section 12.4 Merge Sort Title What impact results from modifying the mergeLists function? type mc section 12.4 Merge Sort id testbank-py-1-ch12-37

42. Which sorting algorithm starts by cutting the list in half and then recursively sorts each half? 1. insertion sort 2. selection sort 3. merge sort 4. Shell sort Section 12.4 Merge Sort Title Which sorting algorithm starts by cutting the list in half and then recursively sorts each half? type mc from testbank-py-1-ch12-32 section 12.4 Merge Sort id testbank-py-2-ch12-32 43. In the textbook, we found that the number of element visits for merge sort totaled n + 5nlog2n. Lets consider sorting 1024 elements. How many visits are needed? 1. 1,024 2. 6,144 3. 51,200 4. 52,224 Section 12.5 Analyzing the Merge Sort Algorithm Title How many visits are needed for a merge sort of 1024 elements? type mc section 12.5 Analyzing the Merge Sort Algorithm


43. id testbank-py-1-ch12-40 44. In the textbook, we found that the number of element visits for merge sort totaled n + 5nlog2n. Which of the following is the appropriate big-Oh notation for merge sort? 1. 5nlog2n 2. n + log2 3. n + 5n 4. nlog2n Section 12.5 Analyzing the Merge Sort Algorithm Title Which of the following is the appropriate big-Oh notation for merge sort? type mc section 12.5 Analyzing the Merge Sort Algorithm id testbank-py-1-ch12-41 45. Selection sort has O(n2) complexity. If a computer can sort 1,000 elements in 4 seconds, approximately how many seconds will it take the computer to sort 1,000 times that many, or 1,000,000 elements? 1. 16 2. 1,000 3. 1,000,000 4. 4,000,000 Section 12.5 Analyzing the Merge Sort Algorithm Title How many seconds will it take selection sort to sort 1,000 times as many elements? type mc section 12.5 Analyzing the Merge Sort Algorithm id testbank-py-1-ch12-42 46. Merge sort is a(n) ____ algorithm. 1. O(n) 2. O(n log(n)) 3. O(n2) 4. O(log n) Section


46. 12.5 Analyzing the Merge Sort Algorithm Title Merge sort is a(n) ____ algorithm. type mc section 12.5 Analyzing the Merge Sort Algorithm id testbank-py-1-ch12-43 47. Consider the following function, which correctly merges two lists: def mergeLists(first, second, values) : iFrist = 0 iSecond = 0 j=0 while iFirst < len(first) and iSecond < len(second) : if first[iFirst] < second[iSecond] : values[j] = first[iFirst] iFirst = iFirst + 1 else : values[j] = second[iSecond] iSecond = iSecond + 1 j=j+1 while iFrist < len(first) : values[j] = first[iFirst] iFirst = iFirst + 1 j=j+1 while iSecond < len(second) : values[j] = second[iSecond] iSecond = iSecond + 1 j=j+1 What is the big-Oh complexity of this algorithm, where n is the total number of elements in first and second? 1. O(1) 2. O(log(n)) 3. O(n) 4. O(n2) Section Section 12.5 Analyzing the Merge Sort Algorithm Title What is the big-Oh complexity of this function for merging two lists? type mc section 12.5 Analyzing the Merge Sort Algorithm id testbank-py-1-ch12-45


48. Consider the following mergeSort function: def mergeSort(values) : if len(values) <= 1 : return mid = len(values) // 2 first = values[ : mid] second = values[mid : ] mergeSort(first) mergeSort(second) mergeLists(first, second, values) # The implementation of mergeLists has been omitted. # It can be found in the textbook. If the function takes 1.0 seconds to sort a list of 10,000 elements, how long would you expect it to take to sort a list of 20,000 elements? 1. 1.1 seconds 2. 2.2 seconds 3. 4.4 seconds 4. 8.8 seconds Section 12.5 Analyzing the Merge Sort Algorithm Title How long would you expect this merge sort to take? type mc section 12.5 Analyzing the Merge Sort Algorithm id testbank-py-1-ch12-46 49. Recall the merge sort algorithm presented in the textbook. That algorithm requires T(n) = T(n / 2) + T(n / 2) + 5n visits to sort a list of n elements. The function to merge two sorted lists requires a total of 5n visits. What does T(n / 2) describe? 1. The total number of visits needed to merge sort a list of n elements 2. Half the number of visits needed to merge sort a list of n elements 3. The total number of visits needed to merge sort a list of n / 2 elements 4. Half the number of visits needed to merge sort a list of n / 2 elements Section 12.5 Analyzing the Merge Sort Algorithm Title What does T(n / 2) describe when analyzing the merge sort algorithm? type mc from testbank-py-1-ch12-38 section 12.5 Analyzing the Merge Sort Algorithm id testbank-py-2-ch12-38 50. Assume we are using quicksort to sort a list into ascending order. Where does quicksort place the pivot element after partitioning the list? 1. The pivot element is placed at the lowest index in the list that is still available. 2. The pivot element is placed at the highest index in the list that is still available. 3. The pivot element is placed in a position that is closer to its final correct location.


50.

4. The pivot element is placed in its final correct location. Section 12.5 Analyzing the Merge Sort Algorithm Title Where does quicksort place the pivot element after partitioning? type mc from testbank-py-1-ch12-44 section 12.5 Analyzing the Merge Sort Algorithm id testbank-py-2-ch12-44

51. Which sorting algorithm has better than O(n2) behavior, even in the worst case? 1. Insertion sort 2. Merge sort 3. Quicksort 4. Selection sort Section 12.5 Analyzing the Merge Sort Algorithm Title Which sorting algorithm has better than O(n<sup>2</sup>) behavior, even in the worst case? type mc section 12.5 Analyzing the Merge Sort Algorithm id testbank-py-2-ch12-80 52. In the worst case, a linear search locates a value in an list of length n in ____ steps. 1. O(n2) 2. O(log n) 3. O(n) 4. O(log n2) Section 12.6 Searching Title In the worst case, a linear search locates a value in an list of length n in ____ steps. type mc section 12.6 Searching id testbank-py-1-ch12-47 53. The following code is an example of a ___ search. def search(values, v) : for i in range(len(values)) :


53.

if values[i] == v : return i return -1 1. sorted 2. binary 3. linear 4. random Section 12.6 Searching Title This code is an example of a _____ search. type mc section 12.6 Searching id testbank-py-1-ch12-48

54. Suppose you have a phone number and need to find the address that it corresponds to. If there are 2,000,000 entries, how many do you expect to search in a printed phone directory before finding the address you are looking for? 1. Approximately 50,000 records 2. Approximately 75,000 records 3. Approximately 1,000,000 records 4. Approximately 1,200,000 records Section 12.6 Searching Title How many phone book entries would you expect to search? type mc section 12.6 Searching id testbank-py-1-ch12-49 55. If an element is present in a list of length n, how many element visits, in the worst case, are necessary to find it using a linear search? 1. n/2 2. n 3. 2n 4. n2 Section 12.6 Searching Title How many phone book entries would you expect to search? type mc section 12.6 Searching


55. id testbank-py-1-ch12-50 56. If an element is present in a list of length n, how many element visits, on average, are necessary to find it using a linear search? 1. n/2 2. n 3. 2n 4. n2 Section 12.6 Searching Title How many phone book entries would you expect to search? type mc section 12.6 Searching id testbank-py-1-ch12-51 57. Another name for linear search is ____ search. 1. sorted 2. sequential 3. random 4. binary Section 12.6 Searching Title Another name for linear search is ____ search. type mc section 12.6 Searching id testbank-py-1-ch12-52 58. Binary search is an ____ algorithm. 1. O(n) 2. O(n2) 3. O(log n) 4. O(n log n) Section 12.6 Searching Title


58. Binary search is an ____ algorithm. type mc section 12.6 Searching id testbank-py-1-ch12-53 59. Given an ordered list with 15 elements, how many elements must be visited in the worst case of binary search? 1. 8 2. 4 3. 3 4. 2 Section 12.6 Searching Title For an ordered list with 15 elements, how many elements must be visited in the worst case of binary search? type mc section 12.6 Searching id testbank-py-1-ch12-54 60. A search technique where, in each step, you split the size of the search in half is called a____ search. 1. random 2. binary 3. linear 4. merging Section 12.6 Searching Title A search technique where, in each step, you split the size of the search in half is called a____ search. type mc section 12.6 Searching id testbank-py-1-ch12-56 61. Consider the following function for performing a linear search: def linearSearch(values, target) : for i in range(len(values)) : if values[i] == target : return i return -1 How many elements will be visited when values is [1, 5, 7, 6, 2, 4, 9, 3, 8, 0] and target is 2? 1. 0 2. 2 3. 5 4. 10 Section


61. 12.6 Searching Title How many elements are visited during a linear search? type mc section 12.6 Searching id testbank-py-1-ch12-58 62. Consider the following function for performing a linear search: def linearSearch(values, target) : for i in range(len(values)) : if values[i] == target : return i return -1 How many elements will be visited when values is [1, 5, 7, 6, 2, 4, 9, 3, 8, 0] and target is 10? 1. 0 2. 2 3. 5 4. 10 Section 12.6 Searching Title How many elements are visited during a linear search? type mc section 12.6 Searching id testbank-py-1-ch12-59 63. Consider the following function for performing a binary search: def binarySearch(values, low, high, target) : if low <= high : mid = (low + high) // 2 if values[mid] == target : return mid elif values[mid] < target : return binarySearch(values, mid + 1, high, target) else : return binarySearch(values, low, mid - 1, target) else : return -1 How many elements will be visited when values is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], low is 0, high is 9, and target is 2? 1. 1 2. 3


63.

3. 5 4. 10 Section 12.6 Searching Title How many elements are visited during a binary search? type mc section 12.6 Searching id testbank-py-1-ch12-60

64. Consider the following function for performing a binary search: def binarySearch(values, low, high, target) : if low <= high : mid = (low + high) // 2 if values[mid] == target : return mid elif values[mid] < target : return binarySearch(values, mid + 1, high, target) else : return binarySearch(values, low, mid - 1, target) else : return -1 How many elements will be visited when values is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], low is 0, high is 9, and target is 10? 1. 0 2. 2 3. 4 4. 10 Section 12.6 Searching Title How many elements are visited during a binary search? type mc section 12.6 Searching id testbank-py-1-ch12-61 65. Can binary search be applied to the following list? data = [1, 4, -6, 7, 2, 10, 21] 1. Yes, binary search will return the correct result for this list 2. No, binary search can only be applied to a list that is in sorted order 3. No, binary search can only be applied to a list whose length is a power of 2 4. No, binary search cannot be applied to lists containing negative values Section


65. 12.6 Searching Title Can binary search be used to search this list? type mc section 12.6 Searching id testbank-py-1-ch12-62 66. A binary search ____ a linear search. 1. can't be compared to 2. generally has a similar running time to 3. is generally faster than 4. is generally slower than Section 12.6 Searching Title What is the relationship between a binary search and a linear search? type mc from testbank-py-1-ch12-55 section 12.6 Searching id testbank-py-2-ch12-55 67. Can you search the following list using binary search? values = [6, 5, 2, 4, 0, 1, -17, -1] 1. Yes. Binary search can be applied to any list. 2. No. Binary search can only be applied to a sorted list. 3. Yes, but the algorithm runs more slowly because the list is not in sorted order. 4. No, binary search cannot be used on a list that contains negative numbers. Section 12.6 Searching Title Can you search this list using binary search? type mc from testbank-py-1-ch12-57 section 12.6 Searching id testbank-py-2-ch12-57 68. What requirement must be satisified before an element can be located in a list using a binary search? 1. The list must only contain integers 2. The list must be sorted 3. The length of the list must be a power of 2 4. The list must not contain any repeated values Section 12.6 Searching


68. Title What requirement must be satisified before an element can be located in a list using a binary search? type mc section 12.6 Searching id testbank-py-2-ch12-82 69. Which of the following statements about running times of algorithms is correct? 1. An algorithm that is O(1) means that only one comparison takes place. 2. When determining the running time, constants are not taken into consideration. 3. When determining the running time, lower-order terms must be taken into consideration. 4. An algorithm that is O(n) means that the number of comparisons does not grow as the size of the list increases. Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title Which of the following statements about running times of algorithms is correct? type mc section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-1-ch12-63 70. A portion of your program includes the loop shown in the code snippet below to examine the elements of a list lst: count = 0 targetVal = 70 for i in range(len(lst)) : if lst[i] >= targetVal : count = count + 1 What can you conclude about the running time of this section of code? 1. Its running time will be O(n). 2. Its running time will be O(n2). 3. Its running time will be O(log n). 4. Its running time will be O(n log n). Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title What can you conclude about the running time of this section of code? type mc section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-1-ch12-64 71. The function findLargest examines the elements of an list lst which contains non-negative values curLargest = -1


71. for i in range(len(lst)) : if lst[i] >= curLargest : curLargest = lst[i] What can you conclude about the running time of this section of code? 1. Its running time will be O(n). 2. Its running time will be O(n2). 3. Its running time will be O(log n). 4. Its running time will be O(n log n). Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title What can you conclude about the running time of this section of code? type mc section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-1-ch12-65 72. An algorithm that tests whether the first list element is equal to any of the other list elements would be an ____ algorithm. 1. O(1) 2. O(n) 3. O(log n) 4. O(n log n) Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title Testing whether the first element is equal to any other element would be an ____ algorithm. type mc section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-1-ch12-67 73. An algorithm that cuts the work in half in each step is an ____ algorithm. 1. O(n) 2. O(n2) 3. O(log n) 4. O(n log n) Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title


73. An algorithm that cuts the work in half in each step is an ____ algorithm. type mc section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-1-ch12-70 74. Which method must a user-defined class implement in order for list's sort method to work correctly? 1. __int__ 2. __lt__ 3. __repr__ 4. __sort__ Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title Which method must be implemented in order for list's sort method to work correctly? type mc section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-1-ch12-71 75. Which sorting algorithm does the following code segment employ? def mysterySort(values, start, to) : if start >= to : return p = partition(values, start, to) mysterySort(values, start, p) mysterySort(values, p + 1, to) 1. Merge Sort 2. Quicksort 3. Selection Sort 4. Shell Sort Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title Which sorting algorithm does the following code segment employ? type mc section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-1-ch12-72 76. Which sorting algorithm does the following code segment employ? def mysterySort(values) : if len(values) <= 1 : return first = values[ : mid]


76.

second = values[mid : ] mysterySort(first) mysterySort(second) mergeLists(first, second, values) 1. Merge Sort 2. Quicksort 3. Selection Sort 4. Shell Sort Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title Which sorting algorithm does the following code segment employ? type mc section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-1-ch12-73

77. Which sorting algorithm does the following code segment employ? def mysterySort(values) : for i in range(len(values)) : minPos = minimumPosition(values, i) temp = values[minPos] values[minPos] = values[i] values[i] = temp 1. Merge Sort 2. Quicksort 3. Selection Sort 4. Shell Sort Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title Which sorting algorithm does the following code segment employ? type mc section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-1-ch12-74 78. The checklist function is shown below: def checklist(lst) : if(lst[0] >= lst[len(lst)-1] : return True return False What can you conclude about the running time of this function? 1. Its running time will be O(n). 2. Its running time will be O(n2). 3. Its running time will be O(log n). 4. Its running time will be O(1).


78.

Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title What can you conclude about the running time of a function? type mc from testbank-py-1-ch12-66 section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-2-ch12-66

79. Consider the following code segment that examines the elements of two lists: matches = 0 for i in range(len(lst1)) : for j in range(len(lst2)) : if lst1[i] == lst2[j] : matches = matches + 1 What can you conclude about the running time of this code segment if both lists contain n elements? 1. Its running time will be O(n). 2. Its running time will be O(n2). 3. Its running time will be O(log n). 4. Its running time will be O(n log n). Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title What can you conclude about the running time of this code segment? type mc from testbank-py-1-ch12-68 section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-2-ch12-68 80. Consider the following function: def findElement(lst, newVal) : pos = binarySearch(lst, newVal) return pos What can you conclude about the running time of this function if lst contains n elements? 1. Its running time will be O(n). 2. Its running time will be O(n2). 3. Its running time will be O(log n). 4. Its running time will be O(n log n). Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title What can you conclude about the running time of this code segment?


80. type mc from testbank-py-1-ch12-69 section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-2-ch12-69 81. Which sorting algorithm was enhanced to create Shell sort? 1. Insertion sort 2. Merge sort 3. Quicksort 4. Selection sort Section 12.7 Problem Solving: Estimating the Running Time of an Algorithm Title Which sorting algorithm was enhanced to create Shell sort? type mc section 12.7 Problem Solving: Estimating the Running Time of an Algorithm id testbank-py-2-ch12-83

download the full zip files containing all source files and other materials here: https://drive.google.com/file/d/1FGBLY05ZhzzmEcEihS5FflBeq6IsXo6E/view ?usp=sharing


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.