PCAP Study Guide Questions

Ace your homework & exams now with Quizwiz!

What would you use instead of XXX if you want to check whether a certain 'key' exists in a dictionary called diet? (Select two answers) if XXX: print("Key exists")

'key' in dict 'key' in dict.keys()

Which of the following expression evaluate to True? (Select two answers)

't'.upper() in 'Thames' 'in' in 'in'

Assuming that the code below has been executed successfully, which of the expressions evaluate to True? (choose two) class Class: var = 1 def __init__(self, value): self.prop = value Object = Class(2)

'var' in Class.__dict__ len(Object.__dict__) == 1

What is the expected out of the following code of the file named zero_length_existing_file is a zero length file located inside the working directory? try: f = open('zero_length_existing_file', 'rt') d = f.readline() print(len(d)) f.close() except IOError: print(-1)

-1

What is the expected output of the following code? def foo(x, y, z): return x(y) - x(z) print(foo(lambda x: x % 2, 2, 1))

-1

Which of the following literals reflect the value given as 34.23? (select two answers)

.3423e2 3423e-2

What is the expected output of the following code? myli = range(-2,2) m = list(filter(lambda x: True if abs(x) < 1 else False, myli)) print(len(m))

1

What will be the value of the i variable when the while e loop finishes its execution? i = 0 while i != 0: i = i - 1 else: i = i + 1

1

What is the expected output of the following code if existing_file is the name of a file located inside the working directory? try: f = open('existing_file','w') print(1, end=' ') except IOError as error: print(error.errono, end=' ') print(2, end=' ') else: f.close() print(3, end=' ')

1 3

Which of the following expressions evaluate to True? (Select two answers)

121 + 1 != '!' + 2 * '2' '3.14' != str(3.1415)

What is the expected output of the following snippet? 1st = [1,2,3,4] 1st = 1st[-3:-2] 1st = 1st[-1] print(1st)

2

What is the expected output of the following code if there is no file named non existing_file inside the working directory? try: f = open('non_existing_file', 'r') print(1, end=' ') except IOError as error: print(error.errno, end=' ') print(2, end=' ') else: f.close() print(3, end=' ')

2 2

What is the expected output of the following code? def f(n): if n == 1: return '1' return str(n) + f(n-1) print(f(2))

21

What is the expected output of the following code? def foo(x,y): return y(x) + (x+1) print(foo(1, lambda x: x*x))

3

What is the expected output of the following snippet? a = 2 if a > 0: a += 1 else: a -= 1 print(a)

3

What will the value of the i variable be when the following loop finishes its execution? for i in range(10): pass

9

An operator able to perform bitwise shifts is coded as (select two answers)

<< >>

Assuming that the V variable holds an integer value to 2, which of the following operators should be used instead of OPER to make the expression equal to 1? V OPER 1 -

>>

The following class hierarchy is given. What is the expected output of the code? class A: def a(self): print("A", end=' ') def b(self): self.a() class B(A): def a(self): print("B", end=' ') def do(self): self.b() class C(A): def a(self): print("C", end=' ') def do(self): self.b() B().do() C().do()

BC

Assuming that the code below has been placed inside a file named code.py and executed successfully, which of the following expressions evaluate to True? class ClassA: var = 1 def __init__(self, prop): prop1 = prop2 = prop def __str__(self): return class ClassB(ClassA): def __init__(self, prop): prop3 = prop ** 2 super().__init__(prop) Object = ClassB(2)

ClassA.__module__ == '__main__' str('Object') == 'Object'

What is the expected output of the following snippet? class X: pass class Y(X): pass class Z(Y): pass X = Z() Z = Z() print(isinstance(X, Z), isinstance(Z, X))

False True

What is the expected output of the following snippet? class Upper: def method(self): return 'upper' class Lower(Upper): def method(self): return 'lower' Object = Upper() print(isinstance(Object, Lower), end=' ') print(Object.method())

False upper

Which of the following statements are true? (Select two answers)

II in ASCII stands for Information Interchange a code point is a number assigned to a given character

Which of the following statements are true? (Select two answers)

Python strings can be concatenated Python strings can be sliced like lists

What is the expected out put of the following snippet? s = 'abc' for i in len(s): s[i] = s[i].upper() print(s)

The code will cause a runtime exception

What is the expected output of the following code? str = 'abcdef' def fun(s): del s[2] return s print(fun(str))

The program will cause a runtime exception error

What is the expected output of the following code? import sys import math b1 = type(dir(math)) is list b2 = type(sys.path) is list print(b1 and b2)

True

Which of the following statements are true? (Select two answers)

UTF-8 is one of the ways of representing UNICODE code points. ASCII is the name of a character coding standard

A property that stores information about a given class's super-classes is named:

__bases__

Assuming that the following code has been executed successfully, selected the expression which evaluate to True (Select two answers) def f(x, y): nom, denom = x, y def g(): return nom / denom return g a = f(1,2) b = f(3,4)

a is not None a != b

What can you deduce from the following statement? (Select two answers) str = open('file.txt', "rt")

a newline character translation will be performed during the reads the opened file cannot be written with the use of the str variable

Python's built-in function named open() tries to open a file and returns:

a stream object

A variable stored separately in every object is called:

an instance variable

What is the output of the following piece of code? a = 'ant' b = "bat" c = 'camel' print(a, b, c, sep='"')

ant"bat"camel

Assuming that the following code has been executed successfully, select the expressions which evaluate to True (Select two answers) var = 1 def f(): global var var += 1 def g(): return var return g a = f() b = f()

b() > 2 a() > 2

A class constructor (Select two answers)

cannot be invoked directly from inside the class can be invoked directly from any of the subclasses

What is the expected behavior of the following snippet? def a (1, I) return 1[I] print(a(0, [1])

cause a runtime exception

You are going to read just one character from a stream called s. Which statement would you use?

ch = s.read(1)

A compiler is a program designed to (select two answers)

check the source code in order to see if its correct translate the source code into machine code

Assuming that the following inheritance set is in force, which of the following classes are declared properly? (Select two answers) class A: pass class B(A): pass class C(A): pass class D(B): pass

class Class_4(D,A): pass class Class_1(C,D): pass

The simplest possible class definition in Python can be expressed as:

class X: pass

You need data which can act as a simple telephone directory. You can obtain it with the following clauses (choose two relevant variants; assume that no other items have been created before)

dir={'Mom':5551234567, 'Dad':5557654321> dir={'Mom':'5551234567', 'Dad':'5557654321'}

The following expression 1 + -2 is:

equal to -1

If you need to serve two different exceptions called Ex1 and Ex2 in one except branch, you can write:

except (Ex1, Ex2):

If you want to access an exception object's components and store them in an object called e, you have to use the following form of exception statement

except Exception as e:

Select the valid fun() invocations: (select two answers) def fun (a, b=0): return a*b

fun(a=0) fun(1)

Assuming that the following piece of code has been executed successfully, which of the expressions evaluate to True? (Select two answers) class A: VarA = 1 def __init__(self): self.prop_a = 1 class B(A): VarA = 2 def __init__(self): self.prop_a = 2 self.prop_aa = 2 class C(B): VarA = 3 def __init__(self): super().__init__() obj_a = A() obj_b = B() obj_c = C()

hasattr(obj_b, 'prop_aa') isinstance(obj_c, A)

The first parameter of each method:

holds a reference to the currently processed object

Which of the following statement are true? (Select two answers)

if open()'s second argument is 'r' the file must exist or open will fail if open()'s second argument is 'w' and the invocation succeeds, the previous file's content is lost

A Python module named pymod, py contains a function named pyfun ( ). Which of the following snippets will let you invoke the function? (Select two answers)

import pymod pymod.pyfun() from pymod import pyfun pyfun()

A Python module named pymod.py contains a variable named pyvar. Which of the following snippets will let you access the variable?

import pymod pymod.pyvar = 1 from pymod import pyvar pyvar()

With regards to the directory structure below, select the proper forms of the directives in order to import module_a. (select two answers) pypack (dir) | |--upper (dir) | | | |--lower (dir) | | | | | |--module_c.py (file) | | | |--module_b.py (file) | |--module_a.py (file)

import pypack.module_a from pypack import module_a

What is the expected behavior of the following code? class Class: Variable = 0 def __init__(self): self.value = 0 object_1 = Class() object_1.Variable += 1 object_2 = Class() object_2.value += 1 print(object_2.Variable + object_1.value)

it outputs 0

What is the expected behavior of the following code? x = 3 % 1 y = 1 if x > 0 else 0 print (y)

it outputs 0

What is the expected behavior of the following code? m = 0 def foo(n): global m assert m != 0 try: return 1/n except ArithmeticError: raise ValueError try: foo(0) except ArithmeticError: m += 2 except: m += 1 print(m)

it outputs 1

What is the expected behavior of the following code? x = 8 ** (1 / 3) y = 2. if x < 2.3 else 3. print(y

it outputs 2.0

What is the expected behavior of the following code? string = str(1/3) dummy = '' for character in string: dummy = dummy + character print(dummy[-1])

it outputs 3

What is the expected behavior of the following code? class Class: _Var = 1 __Var = 2 def __init__(self): self.prop = 3 self.__prop = 4 o = Class() print(o._Class__Var + o._Class__prop)

it outputs 6

What is the expected behavior of the following code? the_list = "alpha;beta;gamma".split(":") the_string = ''.join(the_list) print(the_string.isalpha())

it outputs False

What is the expected behavior of the following code? my_list = [i for i in range(5, 0, -1)] m = [my_list[i] for i in range(5) if my_list[i] % 2 == 0] print(m)

it outputs [4, 2]

What is the expected behavior of the following code? my_list = [1, 2, 3] try: my_list[3] = my_list[2] except BaseException as error: print(error)

it outputs list assignment index out of range

What is the expected behavior of the following code? class Super: def make(self): pass def doit(self): return self.make() class Sub_A(Super): def make(self): return 1 class Sub B(Super): pass a = Sub_A() b = Sub_B() print(a.doit() + b.doit())

it raises an exception

Which of the following lambda definitions are correct? (Select two answers)

lambda x,y: x // y - x % y lambda x,y: (x, y)

Which of the following lambda function definitions are correct? (Select two answers)

lambda x: None lambda : 3.1415

Which of the following expression evaluate to True? (Select two answers)

len('\'') == 1 chr(ord('A') + 1) == 'B'

Assuming that the following snippet has been successfully executed, which of the equations are True? (Select two answers) a = [0] b = a[:] a[0] = 1

len(a) == len(b) a[0] - 1 == b[0]

Assuming that the following snippet has been successfully executed, which of the equations are True? (Select two answers) a = [1] b = a a[0] = 0

len(a) == len(b) b[0] - 1 != a[0]

Assuming that the math module has been successfully imported, which of the following expressions evaluate to True?

math.hypot (3,4) == math.sqrt (25)

Which of the following statements are true? (Select two answers)

open() is a function which returns an object that represents a physical file if invoking open() fails, an exception is raised

If you need a function that does nothing, what would you use instead of XXX? (Select two answers) def idler(): XXX

pass None

Which one of the platform module functions should be used to determine the underlying platform name?

platform.platform ()

What is the expected behavior of the following snippet? def x(): # line 01 return 2 # line 02 x = 1 + x() # line 03 print(x) # line 04

print 3

What is the expected behavior of the following code? def f (n): for i in range(1, n+1) yield I print(f(2))

print <generator object f at (some hex digits)>

Assuming that the code below has been executed successfully, which of the following expressions will always evaluate to True? import random v1 = random.random() v2 = random.random()

random.choice([1,2,3]) >= 1

There is a stream named s open for writing. What option will you select to write a line to the stream''

s.write("Hello\n")

Which of the following lines of code will work flawlessly when put independently inside the add_new() method in order to make the snippet's output equal to [0, 1, 1] ? (Select two answers) class MyClass: def __init__(self, initial): self.store = initial def put(self, new): self.store.append(new) def get(self): return self.store def dup(self): # insert line of code here Object = MyClass([0]) Object.put(1) Object.dup() print(Object.get())

self.put(self.get()[-1]) self.put(self.store[-1])

Which of the following lines of code will work flawlessly when put independently inside the add_new () method in order to make the snippet's output equal to [0, 1, 21] ? (Select two answers) class MyClass: def __init__(self, size): self.queue = [i for i in range(size)] def get(self): return self.queue def get_last(self): return self.queue[-1] def add_new(self): # insert the line of code here Object = MyClass(2) Object.add_new() print(Object.get())

self.queue.append(get_last() + 1) self.queue.append(self.queue[-1] + 1)

How many elements will the list2 list contain after execution of the following snippet? list1 = [False for i in range (1, 10)] list2 = list1 [-1:1:-1]

seven

Which of the following expressions evaluate to True? (Select two answers)

str(1-1) in '0123456789'[:2] 'True' not in 'False'

Assuming that the snippet below has been executed successfully, which of the following expressions will evaluate to True? string = 'python' [::2] string = string[-1] + string[-2]

string[0] == 'o'

Assuming that the snippet below has been executed successfully, which of the following expressions will evaluate to True? (Select two answers) string = 'SKY'[::-1] string = string[-1]

string[0] == string[-1] len(string) == 1

What is the expected output of the following snippet? i = 5 while i > 0: i = i // 2 if i % 2 = 0: break else: i += 1 print(i)

the code is erroneous

What is the expected behavior of the following code? s = '2A' try: n = int(s) except: n = 3 except ValueError: n = 2 except ArithmeticError: n = 1 print(n)

the code is erroneous and it will not execute

What is true about Python class constructors? (Select two answers)

the constructor is a method named __init__ the constructor must have at least one parameter

What is a true about python class constructors? (Select two answers)

the constructor must have at least one parameter the constructor is a method named __init__

A file name like this one below says what: (select three answers) services.cpython-36.pyc

the interpreter used to generate the file is version 3.6 it has been produced by CPython the file comes from the services .py source file

What is true about Object-Oriented Programming in Python? (Select two answers)

the same class can be used many times to build a number of objects a subclass is usually more specialized than its superclass

What is true about the following snippet? (Select two answers) class E(Exception): def __init__(self, message): self.message = message def __str__(self): return "it's nice to see you" try: print("I feel fine") raise Exception("what a pity") except E as e: print(e) else: print("the show must go on")

the string "I feel fine" will be seen the string "what a pity" will be seen

What is true about Python packages? (Select two answers)

the sys.path variable is a list of strings a code designed to initialize a package's state should be placed inside a file named __init__.py

What is true about Python packages? (Select two answers)

the__name__variable content determines the way in which the module was run a package can be stored as a tree of sub-directories/sub-folders

How many lines does the following snippet output? for i in range(1, 3): print("*", end="") else: print("*")

three

Assuming that String is six or more letters long, the following slice String[1:-2] is shorter than the original string by:

three chars

Which of the following words can be used as a variable name? (Select two valid names)

true For

Which of the following snippets will execute without raising any unhandled exceptions? (Select two answers)

try: print(0/0) except: print(0/1) else: print(0/2) import math try: print(math.sqrt(-1)) except: print(math.sqrt(0)) else: print(math.sqrt(1))

Which of the listed actions can be applied to the following tuple? (Select two answers)

tup[:] del tup

Which of the following sentences are true? (Select two answers)

tuples may be stored inside lists lists may be stored inside lists

How many elements will the list1 list contain after execution of the following snippet? list1 = "don't think twice, do it!".split(',')

two

Can a module run like regular code?

yes, and it can differentiate its behavior between the regular launch and import

Is it possible to safely check if a class object has a certain attribute?

yes, by using the hasattr() function

What can you do if you don't like a long package path tike this one? import alpha.beta.gamma.delta.epsion.zeta

you can make an alias for the name using the as keyword


Related study sets

COMP 560 Midterm: A.I. Artificial Intelligence

View Set

Microbio Final exam (old material)

View Set

Soynia RES study guide for State Exam

View Set

Sustainable development on the environment

View Set

Module 22. Studying And Encoding Memories

View Set

Osteoporosis/GERD/Pancreatitis/Urinary Calculi Exam 2 NCLEX

View Set

5. Fundamentals of TCP/ IP Transport and Applications

View Set

CH 9: Sustainable Development Goals

View Set