Python Final Study
If x = 0.428, what is the result of print(format(x,' .2%'))
42.80% # converts decimal into percentage and prints two decimal places
What is the output for y? y = 0 for i in range(0, 10): y += i print(y)
45 # 0 + 1 + 2 +3 +4 +5+6+7+8+9
Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1.index(5)?
2 # 5 is index 2
Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is max(list1)?
25
Which of the following is the most accurate statement?
It is best to create a customized exception class that is a sub class of an existing exception class.
Choose the correct statements:
It is best to use for loops for counter controlled loops. It is best to use while loops for sentinel controlled loops. Sometimes, an infinite loop is needed
The following loop displays _______________. for i in range(1, 11): print(i, end = " ")
Nothing due to Indentation Error
Python syntax is case-sensitive.
True
What is the value of the following expression? True or True and False
true
Given two sets s1 and s2, s1 < s2 is _________.
true if s1 is a proper subset of s2
What statement can be used to handle some of the run-time errors in a program?
try/except statement
To set the pen size to 5 pixels, use _________.
turtle.pensize(5)
What is max("Programming is fun")?
u # returns highest ascii
Assume v1 = IntVar(), how do you set a new value 5 to v1.
v1.set(5)
Suppose s is "Welcome", what is s.lower()?
welcome
Assume x = 4 and y = 5, Which of the following is true?
x < 5 or y < 5
What is the output of the following code? x = 0 if x < 4: x = x + 1 print("x is", x)
x is 1
__________ creates a list.
list1 = list() list1 = [ ] list1 = list([12, 4, 4]) list1 = [12, 4, 4] # all of above
Suppose t = (1, 2, 4, 3), t[1 : 3] is _________.
(2, 4)
Assume m = [[1, 2], [3, 4], [5, 6]], what is len(m[0])
2
Suppose d = {"john":40, "peter":45}, the keys are __________
"john" and "peter"
A Python line comment begins with ________.
#
Suppose x is 1. What is x after x -= 1? A. 0 B. 1 C. 2 D. -1 E. -2
0
random.randint(0, 1) returns ____________.
0 or 1
Assume m = [[1, 2], [3, 4], [5, 6]], what is len(m)
3
What will be displayed by the following code? x = 1 x = 2 * x + 1 print(x)
3
What will be displayed when the following code is executed? number = 6 while number > 0: number -= 3 print(number, end = ' ')
3 0
Analyze the following code: Code 1: if number % 2 == 0: even = True else: even = False Code 2: even = number % 2 == 0
Both Code 1 and Code 2 are correct
Which statement is true?
Every object of a subclass is also an object is also an object of of that class's superclass
What will be displayed by the following code? ch = 'F' if ch >= 'A' and ch <= 'Z': print(ch)
F
Which of the following statements is true on overriding methods?
Overriding means re-defining a method with same name as a method in the super class.
________ is interpreted.
Python
Which of the following is not a superclass/subclass relationship?
Savings Account/Checking Account
What statements are true regarding super class and sub class?
Super class is sometimes called parent class A super class may have more than one sub class.
To bind a canvas with a left mouse click event p, use __________
canvas.bind("<Button-1>", p)
Suppose s = {1, 2, 4, 3}, what happens when invoking s.add(4)?
This method is executed fine and 4 is not added to the set since 4 is already in the set.
Suppose s is "Welcome", what is s.upper()?
WELCOME
What will be displayed by the following code? ? (note ? represents a blank space) print(format("Welcome", "10s"), end = '#') print(format(111, "4d"), end = '#') print(format(924.656, "3.2f"))
Welcome???#?111#924.66
Which of the following should be defined as a function that returns a value?
Write a function that converts gallons to liters Write a function that checks if a number is odd or even Write a function that picks a random character from 'A' to 'Z'
Which of the following should be defined as a None function?
Write a function that prints integers from 1 to 20
What is list("abcd")?
['a', 'b', 'c', 'd']
Suppose list1 = [2 * x for x in range(0, 4)], list1 is ________
[0, 2, 4, 6]
In the following code, def A: def __init__(self): __a = 1 self.__b = 1 self.c = 1 __d__ = 1 # Other methods omitted Which of the following is a private data field?
__b
Which special method returns a string representation of the object?
__str__ method
How do you draw a red line from 100, 100 to 400, 500?
canvas.create_line(100, 100, 400, 500, fill = "red")
How do you draw a rectangle centered at 100, 100 with width 100 and height 100 on canvas?
canvas.create_rectangle(100 - 50, 100 - 50, 100 + 50, 100 + 50)
Assume name = StringVar(), how do you create a text field (entry) under parent frame2 with variable bound to name?
entryName = Entry(frame2, textvariable = name)
What function do you use to read a number?
eval(input("Enter a number"))
To open a file c:\scores.txt for reading, use __________.
infile = open("c:\\scores.txt", "r")
Choose all the valid identifiers.(how you can name variables)
mile1 MILE Y_5
The ______ function can be used to check if a file f exists.
os.path.isfile(f)
To shuffle list1, use _______.
random.shuffle(list1
Consider the following incomplete code: def f(number): # Missing function body print(f(5)) The missing function body should be ________.
return number
Suppose s1 = {1, 2, 4, 3} and s2 = {1, 5, 4, 13}, what is s1 & s2?
{1, 4}
What is displayed when the following program is run?def main(): try: f() print("After the function call") except ZeroDivisionError: print("Divided by zero!") except: print("Exception") def f(): print(1 / 0) main()
"Divided by zero!"
What is displayed when the following program is run? try: list = 10 * [0] x = list[10] print("Done") except IndexError: print("Index out of bound") else: print("Nothing is wrong") finally: print("Finally we are here")
"Index out of bound" followed by "Finally we are here"
Suppose t = (1, 2), 2 * t is _________.
(1, 2, 1, 2)
Which statement is true regarding Object class
- Object class is the root of class hierarchy - Every class inherits directly or indirectly from Object class
What is y after the following statement is executed? x = 0 y = 5 if x > 0 else -5
-5
In Python exception handling structure, when executing code in the try block, which statements are true?
-If no exception occurs, the except clause is skipped. -If an exception occurs during execution of the try clause, the rest of the try clause is skipped. -If an exception occurs and it does not match the exception name in the except clause, the exception is passed on to the caller of this function
What will be displayed by the following code? class Parent: def __init__(self, x=0): self.__x = x def __str__(self): return str(self.__x) class Child(Parent): def __init__(self, y=1): super().__init__() self.__y = y def __str__(self): return super().__str__() +","+ str(self.__y) p = Parent() c = Child() print(p, c)
0 0,1
The function range(5) return a sequence ______________.
0, 1, 2, 3, 4
What will be displayed by the following code? myList = [1, 5, 5, 5, 5, 1] max = myList[0] indexOfMax = 0 for i in range(1, len(myList)): if myList[i] > max: max = myList[i] indexOfMax = i print(indexOfMax)
1
What will be displayed by the following code? myList = [1, 2, 3, 4, 5, 6] for i in range(0, 5): myList[i + 1] = myList[i] for i in range(0, 6): print(myList[i], end = " ")
1 1 1 1 1 1
What will be displayed by the following code? m = [[1, 2], [3, 4], [5, 6]] print(m[0][1])
2
What will be displayed by the following code? class Parent: def __init__(self, x=0): self.__x = x def __str__(self): return str(self.__x) class Child(Parent): def __init__(self, y=1): super().__init__() self.__y = y def __str__(self): return super().__str__() +","+ str(self.__y) p = Parent(5) c = Child(2) print(p, c)
5 0,2
Given a string s = "Programming is fun", what is s.find('m')?
6 # because is in index 6
What is chr(ord('A')))?
A # ord('A') returns 65 but than chr() returns it back to A
Which of the following code is correct? A. print("Programming is fun") print("Python is fun") B. print("Programming is fun") print("Python is fun") C. print("Programming is fun) print("Python is fun") D. print("Programming is fun) print("Python is fun")
B
Which of the following loops prints "Welcome to Python" 10 times? A: for count in range(1, 10): print("Welcome to Python") B: for count in range(0, 10): print("Welcome to Python") C: for count in range(1, 11): print("Welcome to Python") D: for count in range(1, 12): print("Welcome to Python")
B C
How do you create a canvas under parent frame1 with background color white?
Canvas(frame1, bg = "white")
Assume v1 = IntVar(), how do you create a check button under parent frame1 with variable bound to v1?
Checkbutton(frame1, text = "Bold", variable = v1, command = processCheckbutton)
What is "Good".replace("o", "e")?
Geed
The expression "Test " + 1 + 2 + 3 evaluates to ________.
Illegal expression because test is a string
What will be displayed by the following code? isCorrect = False print("Correct" if isCorrect else "Incorrect")
Incorrect
What gives a program the ability to call the correct method depending on the type of object that is used to call it?
Polymorphism
Analyze the following code and choose the more accurate statement. class A: def __init__(self, s): self.s = s def print(self): print(s) a = A("Welcome") a.print()
The program would run if you change print(s) to print(self.s).
"Welcome to Python".split() is ________
["Welcome", "to", "Python"]
Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.sort()?
[1, 3, 3, 4, 5, 5, 20, 25] # sorts number least to greatest
You can place the line continuation symbol __ at the end of a line to tell the interpreter that the statement is continued on the next line.
\
When creating an object, the system allocates memory and invokes the ______ method.
__init__ method
An object is an instance of a __________.
a class
________ is used to create an object.
a constructor
You can display an image in ______________.
a label, button, a check button, a radio button
The readlines() method returns a ____________.
a list of lines
Each time a function is invoked, the system stores parameters and local variables in an area of memory, known as _______, which stores elements in last-in first-out fashion.
a stack
Given the following function def nPrint(message, n): while n > 0: print(message, end="") n -= 1 What will be displayed by the call nPrint('a', 4)?
aaaa
Which classes are exception classes in Python?
arithmetic error syntax error runtime error
Why do computers use zeros and ones?
because digital devices have two stable states and it is natural to use one state for 0 and the other for 1.
Which option do you use to put the components in a container using the pack manager in the same row?
component.pack(side = LEFT)
Analyze the following code and choose all the correct statements. count = 0 while count < 100: # Point A print("Welcome to Python!") count += 1 # Point B # Point C
count < 100 is always True at Point A count < 100 is always False at Point C
Which of the following statements create a dictionary?
d = {} d = {"john":40, "peter":45} d = {40:"john", 45:"peter"}
Suppose d = {"john":40, "peter":45}, to delete the entry for "john":40, use ________.
del d["john"]
list1 = [11, 2, 23] and list2 = [2, 11, 23], list1 == list2 is ________
false
Class design should include ________
fields constructor accessor and mutators methods other useful methods
What does a subclass inherit from a superclass? (Choose all that apply)
fields methods
Given the following function header: def fn(p1, p2, p3) Which of the following is correct to invoke it?
fn(1, 2, 3) fn(p1 = 1, p2 = 2, p3 = 3)
To format a number x to 3 digits after the decimal point, use _______.
format(x, "5.3f")
How do you create a frame inside the container window?
frame = Frame(window)
To place a button in a specified row and column in its parent container, use ________.
grid manager
Suppose isValid is a boolean variable, which of the following is the correct and best statement for testing if isValid is true.
if isValid :
To read the entire remaining contents of the file as a string from a file object infile, use _________.
infile.read( )
To read two characters from a file object infile, use _________.
infile.read(2)
How many times will the following code print "Welcome to Python"? count = 0 while count < 10: print("Welcome to Python")
infinite because there is no update statement so 0 < 10 will loop as always true
In Python, a syntax error is detected by the ________ at _________.
interpreter/at runtime
Inheritance is also known as the __________.
is a relationship
To check whether an object o is an instance of class A, use _________.
isinstance(o, A)
To create a label under parent window, use _______.
label = Label(window, text = "Welcome to Python")
Suppose d = {"john":40, "peter":45}, to obtain the number of entries in dictionary, use ________.
len(d)
Whenever possible, you should avoid using __________.
local variables has the same name as a global variable
To open a file c:\scores.txt for writing, use __________.
outfile = open("c:\\scores.txt", "w")
Check all the correct statement using print function.
print("Hello") print(135) print("135")
Suppose list1 is [1, 3, 2, 4, 5, 2, 1, 0], Which of the following is correct?
print(list1[0]) print(list1[:2]) print(list1[:-2]) #all of above
Suppose s = {1, 2, 4, 3}, which of the following is(are) incorrect?
print(s[3]) s[3] = 45
Typically, in the function that handles a button click event in GUI applications, these logic component should be included:
retrieve data user entered from the widgets validate data entered process data display results/confirmation # all of above
To check whether string s1 contains s2, use _________.
s2 in s1
You can use ___________ to create an empty set.
set( )
Which of the following statements produces {'a', 'b', 'c'}?
set("abac")
Suppose A is a subclass of B, to invoke the __init__ method in B from A, you write _________.
super().__init__( )
Suppose t = (1, 2, 4, 3), which of the following is incorrect?
t[3]=45
The time.time() returns ________________ .
the current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time).
How do you create a window?
window = Tk()
How do you create an event loop?
window.mainloop()
Suppose s1 = {1, 2, 4, 3} and s2 = {1, 5, 4, 13}, what is s1 ^ s2?
{2, 3, 5, 13}
What is x after the following statements? x = 2 y = 1 x *= y + 1
4
Which of the following is the correct expression of CHARACTER 4?
"4" and '4'
What is the output of the following? balance = 10 while True: if balance < 9: break balance = balance - 9 print(balance)
1
One gigabyte is approximately ________ bytes.
1 billion
Choose all possible ways to run a Python program test.py:
1) Use the command: python test.py 2)Use "Run Module" from IDLE editor that has test.py loaded
To following code reads two number. Which of the following is the correct input for the code? x, y = eval(input("Enter two numbers: "))
1, 2 # enter both with numbers wanted separated by a comma
What is the result of 45 // 4?
11 # the double division means it will give you answer but as an integer no decimals
2 * 3 ** 2 evaluates to __________.
18
What will be displayed by the following code? x, y = 1, 2 x, y = y, x print(x, y)
2 1
What will be displayed by print(ord('z') - ord('a'))?
25
What will be displayed by the following code? def f1(x = 1, y = 2): x = x + y y += 1 print(x, y) f1(2, 1)
3 2
What will be displayed by the following code? def f1(x = 1, y = 2): x = x + y y += 1 print(x, y) f1()
3 3
What is the output for y? y = 0 for i in range(10, 1, -2): y += i print(y)
30
Which of the following expressions return True.
6 >=6 5<6 True
What is ord(B)?
66 # ord() function returns an integer representing the Unicode code point of the character
What is max(3, 5, 1, 7, 4)?
7
What is the value of i printed? j = i = 1 i += j + j * 5 print("What is i?", i)
7
How many times is the print statement executed? for i in range(10): for j in range(8): print(i * j)
80
The equal comparison operator is __________.
==
What will be displayed by the following code? print("A", end = ' ') print("B", end = ' ') print("C", end = ' ') print("D", end = ' ')
A B C D # end = ' ' continues next print statement on the same line
___________ translates high-level language program into machine language program.
A compiler
Choose all the correct statements.
A function may return multiple values A function may have 0 or more parameters
Which of the following statement is most accurate?
An object is a reference type variable An object may contain the references of other objects.
Which of the following loops correctly computes 1/2 + 2/3 + 3/4 + ... + 99/100? A: sum = 0 for i in range(1, 99): sum += i / (i + 1) print("Sum is", sum) B: sum = 0 for i in range(1, 100): sum += i / (i + 1) print("Sum is", sum) C: sum = 0 for i in range(1.0, 99.0): sum += i / (i + 1) print("Sum is", sum) D: sum = 0 for i in range(100): sum += i / (i + 1) print("Sum is", sum)
B
Choose all of the following expressions that result in 8.
all possibilities: 2**3 2*2*2 math.pow(2,3)
__________ represents an entity in the real world that can be distinctly identified.
an object
When you invoke a function with a parameter, the value of the argument is passed to the parameter. This is referred to as _________.
pass by value
Given the following function def nPrint(message, n): while n > 0: print(message) n -= 1 What will be displayed by the call nPrint(4, 'a')?
invalid call
What is the output of the following code? x = 0 while x < 4: x = x + 1 print("x is", x)
its a while loop so returns: x is 4
The following code displays ___________. temperature = 50 if temperature >= 100: print("too hot") elif temperature <= 40: print("too cold") else: print("just right")
just right
What is the number of iterations in the following loop: for i in range(1, n): # iteration code
n-1
Choose the correct ways to invoke the following function and get the return values. def f1(x = 1, y = 2): return x**2, y**2
n1, n2 = f1(5,10) n1, n2 =f1() n2,n1 = f1(1,2)
Does the function call in the following function cause syntax errors? import math def main(): math.sin(math.pi) main()
no
If a function does not return a value, by default, it returns ___________.
none
Which of the following is equivalent to x != y?
not (x == y) x > y or x < y
Suppose x = 1, y = -1, and z = 1. What will be displayed by the following statement? if x > 0: if y > 0: print("x > 0 and y > 0") elif z > 0: print("x < 0 and z > 0")
nothing displayed
Which statement(s) are true regarding private class variables?
private variables can be accessible inside the class. private variables can be changed outside the class through set methods.
To generate a random integer between 1 and 10, use ________________.
random.randint(1, 10) random.randrange(1, 11)
Which of the following function(s) is(are) incorrect?
range(0, 3.5) range(2.5, 4.5) # cant use decimals have to be integers
What is "Programming is fun"[1:3]?
rog # because P index is 0
Which of the following functions return 4.
round(3.9)
The format function returns _______.
str()
To add number to sum, you write
sum = sum + number sum += number
To draw a circle of diameter 20 with red color use _________.
turtle.dot(20,"red")
To move the turtle to a point at (4, 5), use ___________.
turtle.goto(4, 5)
To show the current location and direction of the turtle object, use ___________.
turtle.showturtle()
Does 37% 6 results in a value 1?
yes, because % means divide but return back only the remainder