INSY final part 1 w/ exam 1-3 review questions

¡Supera tus tareas y exámenes ahora con Quizwiz!

What is the output? def foo(): try: print(1) finally: print(2) foo()

1 2

def loopTest(): n=0 while n < 10: n +=1 if n ==5: break print(n) loopTest()

1 2 3 4

def loopTest(): n=0 while n < 10: n +=1 if n ==5: continue print(n) loopTest()

1 2 3 4 6 7 8 9 10

1) lst = [1, 2, 3] lst[3] 2) t[5] 3) 4+'3' 4) int(ten) 5) int('34.6')

1) IndexError: list index out of range 2)NameError: name 't' is not defined 3)TypeError: unsupported operand type(s) for +: 'int' and 'str' 4)NameError: name 'ten' is not defined 5)ValueError: invalid literal for int() with base 10: '34.6'

What is the output if the input entered in each case is -6? 1) import math num=int(input("Enter a number of whose factorial you want to find")) print(math.factorial(num)) 2) num=int(input("Enter a number of whose factorial you want to find")) print(math.factorial(num))

1) ValueError: factorial() not defined for negative values 2) NameError: name 'math' is not defined

range can be used to produce a variety of sequences, please list the output of the following range() functions 1. range(1, 10, 2) → 2. range(10, 0, -2) → 3. range(-5, 5) → 4. range(1, -1, -1) → 5. range(0) →

1. 1 3 5 7 9 2. 10 8 6 4 2 3. -5 -4 -3 -2 -1 0 1 2 3 4 4. 1 0 5. empty

Using your own examples, please write Python expressions to create following data types: 1. x (int) 2. lst (List) 3. items (Tuple) 4. flag (bool) 5. message (str)

1. >>> x=3300 2. >>> lst = [1,2,3,4,5] 3. >>> items = ('textbook', 'pen', 'notebook' 'laptop') 4. >>> flag = True >>> flag True 5. >>> message = 'have a nice a day'

Given the following code, what are the dimensions, in pixels, of the shape created? import tkinter class myShape: def __init__(self): self.main_window = tkinter.Tk() self.canvas = tkinter.Canvas(self.main_window, width=200, height=200) self.canvas.create_rectangle(30,30, 175, 175) self.canvas.pack() tkinter.mainloop() shape = myShape() a. 200 X 200 b. 30 X 175 c. 145 X 145 d. None of these

145 X 145

What is the output of the following code in Python Shell (3+)? >>> book = open ('file1.txt', 'w') >>> book.write('hello')

5

Base classes are also called a. superclasses b. derived classes c. subclasses d. class instances

A

In the following line of code, what is the name of the subclass? class Rose(Flower): a. Rose b. Flower c. Rose(Flower) d. None of these

A

Mutator methods are also known as a. setters b. getters c. instances d. attributes

A

Of the two classes, Cherry and Flavor, which would most likely be the subclass? a. Cherry b. Flavor c. either one d. neither; these are inappropriate class or subclass names

A

What is the binary value of the following decimal number? 118 a. 01110110 b. 11001000 c. 00111001 d. 01110101

A

What is the decimal value of the following binary number? 10011101 a. 157 b. 8 c. 156 d. 28

A

What is the process used to convert an object to a stream of bytes that can be saved in a file? a. pickling b. streaming c. writing d. dumping

A

What will be assigned to the string variable pattern after the following code executes? i = 3 pattern = 'z' * (5 * i) a. 'zzzzzzzzzzzzzzz' b. 'zzzzz' c. 'z * 15' d. Nothing; this code is invalid

A

What will be assigned to the variable s_string after the following code executes? special = '1357 Country Ln.' s_string = special[4:] a. ' Country Ln.' b. '1357' c. 'Coun' d. '57 C'

A

What will be displayed after the following code is executed? counter = 1 while counter <= 20: print(counter, end=" ") counter *= 3 print("\nThe loop has ended.") a. 1 3 9 The loop has ended. b. 1 3 9 The loop has ended. c. 1 3 9 12 15 18 The loop has ended. d. 1 3 9 The loop has ended.

A

When there are several classes that have many common data attributes, it is better to write a(n) __________ to hold all the general data. a. superclass b. subclass c. object d. method

A

When using the __________ logical operator, one or both of the subexpressions must be true for the compound expression to be true. a. or b. and c. not d. Maybe

A

Where does a computer store a program and the data that the program is working with while the program is running? a. in main memory b. in the CPU c. in secondary storage d. in the microprocessor

A

Which attributes belong to a specific instance of a class? a. instance b. self c. object d. data

A

Which computer language uses short words known as mnemonics for writing programs? a. Assembly b. Java c. Pascal d. Visual Basic

A

Which logical operators perform short-circuit evaluation? a. or, and b. or, not c. not, and d. and, or, not

A

Which method would you use to determine whether a certain substring is the suffix of a string? a. endswith(substring) b. find(substring) c. replace(string, substring) d. startswith(substring)

A

Which of the following is the correct if clause to determine whether choice is anything other than 10? a. if choice != 10: b. if choice != 10 c. if choice <> 10: d. if not(choice < 10 and choice > 10):

A

Which of the following is the correct if clause to determine whether y is in the range 10 through 50, inclusive? a. if y >= 10 and y <= 50: b. if 10 < y or y > 50: c. if 10 > y and y < 50: d. if y >= 10 or y <= 50:

A

Which type of error prevents the program from running? a. syntax b. human c. grammatical d. logical

A

sum(2,4,6) sum([1,2,3]) a. Error, 6 b. 12, Error c. 12, 6 d. Error, Erro

A

What is the result of the following Boolean expression, given that x = 5, y = 3, and z= 8? not (x < y or z > x) and y < z a. False b. True c. 8 d. 5

A. False

What is the result of the following Boolean expression, given that x = 5, y = 3, and z = 8? x < y or z > x a. True b. False c. 8 d. 5

A. True

A(n) __________ structure is a logical design that controls the order in which a set of statements execute. a. function b. control c. sequence d. Iteration

B

Accessor methods are also known as a. setters b. getters c. instances d. attributes

B

For the following code, what will the result be if the user enters 5 at the prompt? sum = 0 end_value = int(input("Enter a number: ")) for i in range(1, end_value): sum = sum + i print(sum, end=", ") a. 10, b. 1, 3, 6, 10, c. 1, 3, 6, 10, 16, d. 1, 2, 3, 4, 5,

B

In order to avoid KeyError exceptions, you can check whether a key is in the dictionary using the __________ operator. a. included b. in c. isnotin d. isin

B

Programs are commonly referred to as a. system software b. software c. application software d. utility programs

B

To open a file c:\scores.txt for reading, we use a. infile = open("c:\scores.txt", "r") b. infile = open("c:\\scores.txt", "r") c. infile = open(file = "c:\scores.txt", "r") d. infile = open(file = "c:\\scores.txt", "r")

B

To read the entire remaining contents of the file as a string from a file object infile, we use a) infile.read(2) b) infile.read() c) infile.readline() d) infile.readlines()

B

What is the correct structure to create a dictionary of months where each month will be accessed by its month number (for example, January is month 1, April is month 4)? a. { 1 ; 'January', 2 ; 'February', ... 12 ; 'December'} b. { 1 : 'January', 2 : 'February', ... 12 : 'December' } c. [ '1' : 'January', '2' : 'February', ... '12' : 'December' ] d. { 1, 2,... 12 : 'January', 'February',... 'December' }

B

What is the first negative index in a string? a. 0 b. -1 c. -0 d. the size of the string minus one

B

What is the return value of the string method lstrip()? a. the string with all whitespaces removed b. the string with all leading whitespaces removed c. the string with all leading tabs removed d. the string with all leading spaces removed

B

What will be the value of the variable string after the following code executes? string = 'abcd' string.upper() a. 'abcd' b. 'ABCD' c. 'Abcd' d. Nothing; this code is invalid

B

What will the output of the following code be if the user enters 3 at the prompt? your_num = int(input("Enter a number:")) while (your_num > 0): product = your_num * 5 print(your_num, " * 5 = ", product) your_num -= 1 a. 3*5 = 15 b. 3*5 = 15 2*5 = 10 1*5 = 5 c. 3 * 5 = 15 3 * 5 = 15 3 * 5 = 15 d. 3 * 5 = 15 2 * 5 = 10 1 * 5 = 5 0 * 5 = 0

B

Which method would you use to get all the elements in a dictionary returned as a list of tuples? a. list b. items c. pop d. keys

B

Which section in the UML holds the list of the class's data attributes? a. first section b. second section c. third section d. fourth section

B

Combining data and code in a single object is known as a. modularity b. instantiation c. encapsulation d. objectification

C

Given the following beginning of a class definition for a superclass named clock, how many accessor and mutator methods will be needed to complete the class definition? class clock: def __init__(self, shape, color, price): self.shape = shape self.color = color self.price = price a. 1 mutator, 1 accessor b. 3 mutator, 4 accessor c. 3 mutator, 3 accessor d. 4 mutator, 5 accessor

C

In object-oriented programming, one of first tasks of the programmer is to a. list the nouns in the problem b. list the methods that are needed c. identify the classes needed d. identify the objects needed

C

The following is an example of an instruction written in which computer language? 10110000 a. Assembly language b. Java c. machine language d. C#

C

The process known as the __________ cycle is used by the CPU to execute instructions in a program. a. decode-fetch-execute b. decode-execute-fetch c. fetch-decode-execute d. fetch-execute-decode

C

What is the special name given to the method that returns a string containing an object's state? a. __state__ b. __obj__ c. __str__ d. __init__

C

Which would you use to get the number of elements in a dictionary? a. size b. length c. len d. sizeof

C

__________ has the ability to define a method in a subclass and then define a method with the same name in a superclass. a. Inheritance b. Encapsulation c. Polymorphism d. the 'is a' relationship

C

How many except statements can a try-except block have? a) zero b) one c) more than one d) more than zero

D

How many times will "Hi again!" be displayed after the following code executes? for i in range(0, 12, 2): print("Hi, again!") a. 2 b. 12 c. 5 d. 6

D

In a dictionary, you use a(n) __________ to locate a specific value. a. datum b. element c. item d. key

D

What will be displayed after the following code executes? (Note: the order of the display of entries in a dictionary are not in a specific order.) cities = {'GA' : 'Atlanta', 'NY' : 'Albany', 'CA' : 'San Diego'} if 'CA' in cities: del cities['CA'] cities['CA'] = 'Sacramento' print(cities) a. {'CA': 'Sacramento'} b. ['CA': 'Sacramento'] c. {'NY': 'Albany', 'GA': 'Atlanta'} d. {'CA': 'Sacramento', 'NY': 'Albany', 'GA': 'Atlanta'}

D

Which of the following functions is a built-in function in python? a) seed() b) sqrt() c) factorial() d) print()

D

A recursion in which a function directly calls itself is known as ___________ recursion.

Direct

Some problems are more __________ solved with recursion than with a loop.

Easily

A subclass may not override any method other than the __init__ method.

F

All instances of a class share the same values of the data attributes in the class.

F

An "is a" relationship exists between a grasshopper and a bumblebee.

F

Checkbutton widgets are displayed in groups and used to make mutually exclusive selections.

F

Radio buttons can be used to allow the user to make multiple selections at one time.

F

Recursive algorithms are always more concise and efficient than iterative algorithms.

F

The Entry widget's get method retrieves either numeric or string data.

F

The Python language uses a compiler which is a program that both translates and executes the instructions in a high-level language.

F

The following statement will check to see if the turtle's pen color is 'green': if turtle.pencolor() = 'green'

F

The point (0,0) represents the same place in a window with the Canvas widget as with turtle graphics.

F

To use an Entry widget to get data entered by a user, you must use the Entry widget's set method.

F

A function is called from the main function and then it calls itself five times. The depth of recursion is __________.

Five

A(n) ___________ is a container that can hold other widgets and organize the widgets in a window.

Frame

What will the following statement displays? print('George', 'John' , 'Paul', 'Ringo' , sep='@')

George@John@Paul@Ringo

Recursive function calls are __________ efficient than loops.

Less

A solution using a(n) __________ is usually more evident than a recursive solution.

Loop

The majority of repetitive programming tasks are best done with ___________.

Loops

def add(x, y): z = x + y num1 = 4 num2 = 8 answer = add(num1, num2) print(answer)

None

Each time a function is called, the system incurs __________ that is not necessary with a loop.

Overhead

__________ allows subclasses to have methods with the same names as methods in their superclasses.

Polymorphism

The base case does not require __________, so it stops the chain of recursive calls.

Recursion

All the cases of a recursive solution other than the base case are called the __________ case.

Recursive

Usually a problem solved by recursion is reduced by making the value of one or more parameters __________ with each recursive call.

Smaller

Identify the type of error in the codes shown below. Print("Good Morning") print("Good night)

Syntax Syntax

A class can be thought of as a blueprint that can be used to create an object.

T

A root widget's destroy method can be used as a callback function for a Quit button.

T

An "is a" relationship exists between a wrench and a tool.

T

Each subclass has a method named __init__ that overrides the superclass's __init__ method.

T

Each time a function is called in a recursive solution, the system incurs overhead that is not incurred with a loop.

T

IDLE is an alternative method to using a text editor to write, execute, and test a Python program.

T

Object-oriented programming allows us to hide the object's data attributes from code that is outside the object.

T

Python does not have GUI programming features built into the language itself.

T

The following code snippet will change the turtle's pen size to 4 if it is presently less than 4: if turtle.pensize() < 4: turtle.pensize(4)

T

The pack method determines where a widget should be positioned.

T

The self parameter is required in every method of a class.

T

The self parameter need not be named self but it is strongly recommended to do so, to conform with standard practice.

T

To use the showinfo function, the tkinter.messagebox module must be imported.

T

When, in a recursive solution, function A calls function B which, in turn, calls function A, this is known as indirect recursion.

T

What is the output of the following code in Python Shell? >>> en_to_es = { 'cat':'gato' , 'dog':'perro' } >>> en_to_es['perro']

Traceback (most recent call last): File "<input>", line 1, in <module> KeyError: 'perro'

What is the output of this code? tuple_one = (2, 3, 4, 5, 6) for index in range(len(tuple_one)): tuple_one[index] = index print(tuple_one[index], end=' ')

TypeError: 'tuple' object does not support item assignment

___________ provides a set of standard diagrams for graphically depicting object-oriented systems.

UML

Can a function return more than one values?

Yes

def f(aList): print(aList) aList.append(3) Suppose that function f() has been defined and that you are executing the below sequence of commands in the IDLE shell: lst = [1] f(lst) f(lst) f(lst) b) Show the contents of lst after all the above code has run:

[1, 3, 3, 3]

def f(aList): print(aList) aList.append(3) Suppose that function f() has been defined and that you are executing the below sequence of commands in the IDLE shell: lst = [1] f(lst) f(lst) f(lst) a) What is printed when the code is executed?

[1] [1, 3] [1, 3, 3]

What is the output of this code? list_one = [2, 3, 4, 5, 6] for index in range(len(list_one)): list_one[index] *=2 print(list_one)

[4, 6, 8, 10, 12]

What is the output of this code? numbers = [5, 7, 11, 13, 17, 19, 29, 31] numbers[1] = 3 del numbers[3] numbers[3] = 37 numbers[4] = numbers[5] print(numbers)

[5, 3, 11, 37, 29, 29, 31]

Rewrite the code shown below so it uses a while loop instead of a for loop. Your code should behave identically. (6 points) for a in range(-100, 100, 10): print('*', end='') print()

a = -100 while a < 100: print('*', end='') a=a+10 print()

A method that returns a value from a class's attribute but does not change it is known as a(n) __________ method.

accessor

A superclass is also called a(n) __________ class.

base

Rewrite the following script to write to a file called output.txt instead of printing to the console. (Hint: use file object name as outfile) print('hello world') print(3300) print('\n')

book = open ('output.txt', 'w') book.write("hello world \n") book.write('3300') book.write('\n') book.close()

Which of the following is not a standard exception in Python? a) NameError b) IOError c) AssignmentError d) ValueError

c) AssignmentError

A(n) __________ function is a function or method that executes when the user clicks a button.

call back or event handler

The __________ widget provides methods that allow the programmer to draw some simple shapes.

canvas

A(n) __________ is code that specifies the data attributes and methods for a particular type of object.

class

To create a line with the create_line method of the Canvas widget, you must include four arguments that represent beginning and ending __________.

coordinates

A class __________ is a set of statements that defines a class's methods and data attributes.

definition

A subclass is also called a(n) __________ class.

derived

Code to create an English to French dictionary

en_to_fr = {'cat': 'chat', 'dog': 'chein', 'mouse': 'souris', 'snake':'serpent'}

Code to add a new set of word in your dictionary

en_to_fr['mango'] = 'mangue'

There are two ways to step through the values in a list. One is directly; this is the method we have met already. The second is to step through the indices and to look up the corresponding value in the list. lst = [2, 3, 4, 5, 6, 7, 11, 13, 17, 19]

for item in lst: print(item) for index in range(len(lst)): print(lst[index]) These are equivalent and the first method we have already seen is shorter to write. So why bother with the second? Good for swapping, sorting, searching mechanisms

Write Python code that prompts the user to enter his or her height and assigns the user's input to a variable named height.

height = int(input('Enter your height: '))

What is the output? i = 0 while i < 25: i = i + 5 print('hello')

hello hello hello hello hello

What is the output? sum = 0 for i in range(0, 25, 5): i += 2 print('hello')

hello hello hello hello hello

In a UML diagram, a line with an open arrowhead from a subclass to a superclass indicates ___________.

inheritance

A(n) __________ method in a class initializes an object's data attributes.

initializer __init__(self)

Each object that is created from a class is called a(n) __________ of the class.

instance

The __________ function determines whether or not an object is an instance of a specific class or an instance of a subclass of that class.

is instance

Write a for loop that iterates over a list of numbers lst and prints the even numbers in the list. For example, if lst is [ 2, 3, 4, 5, 6, 7, 8, 9]. Then the numbers 2,4,6, and 8 should be printed.

lst = [ 2, 3, 4, 5, 6, 7, 8, 9] for i in lst: if i%2==0: print(i, end=' ')

In ___________ programming, the programming is centered on objects that are created from abstract data types that encapsulate data and functions together.

object oriented

When a subclass method has the same name as a superclass method, the subclass method __________ the superclass method.

overrides

The Label widget's __________ method determines where a widget should be positioned and makes the widget visible when the main window is displayed.

pack

The term ___________ refers to an object's ability to take different forms.

polymorphism

Code to list all the keys

print(en_to_fr.keys()) .keys

Code to list all the values

print(en_to_fr.values()) .values

Assume the variable sales references a float value. Write a statement that displays the value rounded to two decimal points.

print(format(sales, '.2f'))

___________ programming is a method of writing software that centers on the actions that take place in a program.

procedural

The instance attributes are created by the __________ parameter and they belong to a specific instance of the class.

self

An object's __________ contains the values of the object's attributes at a given moment.

state

In an inheritance relationship, a minivan can be thought of as a(n) ___________ of the vehicles class.

subclass

In an inheritance relationship, the extended class is called the __________.

subclass

The following small Python program certainly will cause a run-time error if the user enters the word "five" instead of typing the digit 5. x = int(input("Please enter a small positive integer: ")) print("x =", x) Write a try/except construct to handle the ValueError exception:

try: x = int(input("Please enter a small positive integer: ")) print("x =", x) except ValueError as err: print(err)


Conjuntos de estudio relacionados

[Lección 4] Estructura 4.2 - ¿Qué hacen?

View Set

Money and Banking Chapter 3 Review

View Set

EAQ- Lewis Med Surg CH.24, Nursing Management: Integumentary Problems

View Set

Nutrition Chapter 2: Standards and Guidelines

View Set

Anatomy: Practice with Directional Terms

View Set