Python

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

What is the expected output of the following code def quote(quo): def embed(str): return quo + str + quo return embed dblq = quote(' " ') print(dblq('Jane Doe"))

"Jane Doe"

Which of the following are valid Python string literals? (select two)

"King's Cross Station" // """The Knights who say 'Ni!'"""

Which of the following expressions evaluate to true and raise no exception? (select two)

' ' in 'alphabet' // 'bc' in 'abc'

which of the following expressions evaluate to True and raise no exception?

'Analog' < 'analog' // ' ' * 0 < 1 * ' '

Assuming that the following code has been executed successfully, indicate the expressions which evaluate to True and don't raise any exceptions(Select two) class Class: class_var = 1 def __init__(self): self.instance_var = 1 def method(self): pass object = Class()

'__dict__' in Class.__dict__ // Class._dict__['method'] != None

Assuming that the following code has been exectued successfully, indicat3e the expressions which evaluate to true and don' raise any exceptions. (select two) class Collection: stamps = 2 def __init__(self, stuff): self.stuff = stuff def dispose(slef): def self.stuff binder = collection(1) binder.dispose()

'stamps' in collection.__dict__ // len(binder.__dict__) != len(collection.__dict__)

What is the expected output of the following code? consts = [3.141592, 2.718282] try: print(consts.index(314e-2)) except Exception as exception: print(exception.args) else: print("success")

('3.14 is not in list',)

What is the expected output of the following code? consts = (3.141592, 2.718282) try: print(consts[2]) except Exception as exception: print (exception.args) else: print("('success')")

('tuple index out of range',)

What is the exoected output of the following code? def fun(x): return 1/x def mid_level(x): try: fun(x) except: raise AssertionError else: return 0 try: x = mid_level(0) except Exception: x = -1 except: x = -2 print(x)

-1

What is the expected output of the following code> s = lambda x: 0 if x == 0 else 1 if x > 0 else -1 print(s(-273.15))

-1

What is the expected output of the following code? x, y = 3.0, 0.0 try: z = x/y except ArithmeticError: z = -1 else: z = -2 print(z)

-1

What is the expeceted output of the following code? x, y = 0.0, 3.0 try: z = x / y except ArithmeticError: z = -1 else: z = -2 print(z)

-2

What is the expected output of the following code? def fun(x): assert x >= 0 return x ** 0.5 def mid_level(x): try: fun(x) except Error: raise try: x = mid_level(-1) except RuntimeError: x = -1 except: x = -2 print(x)

-2

What is hte expected output of the followign code? 1 = [x for x in range(1,10,3) if x % 2 ==0] print(len(1))

1

What is the expected output of the following code if there is no file named non_existing_file in the working directory/folder, and the open() function invocation is successful? try: f = open("non_existing_file", "w") print(1, end = " ") s = f.readline() print(2, end = " ") except IOError as error: print(3, end = " ") else f.close() print(4, end+" ")

1 3

Which of the following expressions evaluates to False and raises no exception?

10 == '1' + '0'

what is the expected output of the following code? foo = [x for x in range(4)] spam = [x for x in foo[1:-1]] print(spam[1])

2

What is teh expected output of the following code? def f(1) : return 1(-3,3) print(f(lambda x,y: x if x>y else y))

3

What is the expected output of the following code? class Top: def __str__(self): return '1' class Left(Top): def __str__(self): return '2' class Right(Top): def __str__(self): return '3' class Bottom(Right, Left): pass object = Bottom() print(object)

3

What is the expected output of the following code? import math x = -1.5 print(abs(math.floor(x) + math.ceil(x)))

3

What is the expected output of the following code? plane = "cessna" counter = 0 for c in plane * 2: if c in ["e", "a"]: counter +=1 print(counter)

4

What is true about object-oriented programming(OOP)? (select two)

A class may exist without its objects, while objects cannot exist without their class// a class is like a bluepint used to construct objects.

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

A source file named __init__.py is used to mark a directory/folder as containing a python package, and to initialize the package. // The variable named __name__ is a string containing the module name.

What is the expected output of the following code? vect = ["alpha", "bravo", "charlie"] new_vect = map(lambda s: s[0].upper(), vect) print(list(new_vect)[1])

B

Given the code below, indicate the code lines which correctly increment the __element variable by one(select two) class BluePrint: __element = 1 def __init__(self): self.component = 1 def __action(self): pass product = BluePrint()

BluePrint._BluePrint__element += 1 // product._BluePrint__element += 1

which of the following snippets output True to the screen? (select two)

Class A: def __init__(self, value = True): print(value) a = A() // class A: def __init__(self): print(True) class B(A): pass b = B()

What is true about object-oriented programming(OOP) (select two)

Encapsulation is a phenomenon which allows you to hide certain class traits from the outer world. // A part of a class designed to build new objects is called a construstor

What is the expected output of the following code? class Economy: def __init__(self): self.econ_attr = True class Business (Economy): def __init__(self): super().__init__() self.busn_attr = False econ_a = Economy() econ_b = Economy() busn_a = Business() busn_b = busn_a print(isinstance(busn_a, Economy) and isinstance(econ_a, Business), end=" ") print(busn_b is busn_a or econ_a is econ_b)

False True

Given the code below, which of the following expressions will evalute to True?(select two) class Alpha: def say(self): return "alpha" class Beta(Alpha): def say(self): return "beta" class Gamma(Alpha): def say(self): return "gamma" class Delta (Beta,Gamma): pass d = Delta() b = Beta()

Gamma in Delta.__bases__// isinstance(d, Alpha)

Which of the following operations may raise an exception? (select two)

Indexing a list. // invoking the int() function

Which of the following are the names of built-in python exceptions (select two answers)

KeyError // AssertionError

which of the following can be used to find a given substring withing a string? (select two)

The .index() method // the .rfind() method

The following code snippet is used to import and invoke the c() function. What is always true about the function and its environment? (select two) import a.b a.b.c()

The c() function is contained in the b module // the b component is a module, and it is contained insde the a package, or is a submodule of a

What is the expected output of the following code? plane = "Blackbird" counter = 0 for c in plane + 2: if c in ["1", "2"] : counter += 1 print(counter)

The code is erroneous and cannot be run

What is true about how python looks for modules/packages

The directory from which the code has been run is always searched through

What is the expected output of the following code if the file name existing_text_file is a non-zero length text file located in the working directory, and the open() function invocation is successful? try: f = open("existing_text_file", "rt") span = f.readlines() print(len(spam)) f.close() except IOError: print(-1)

The number of the lines contained inside the file

Which of the following statements are true?

The second arguement of the open() function is a string// The open() function raises an exception when its operation fails

What is the expected output of the following code? class ceil: Token = 1 def get_token(self): return 1 class Floor(Ceil): def get_token(self): return 2 def set_token(self): pass holder = Floor() print(hasattr(holder, "Token"), hasattr(Ceil, "set_token"))

True False

Which of the following are character encoding standard names? (select two)

Unicode // ASCII

what is the expected output of the following code? v = [1, 2, 3] def g(a,b,m): return m(a,b) print(g(1, 1, lambda x,y: v[ x:y+1 ]))

[2]

if you want to check if a python file is either used as a module or run as a standalone program, you should check a built-in variable named:

__name__

If you want an object to be able to present its contents as a string, you should equip its class with a method named:

__str__()

The built-in class property called __bases__ is:

a tuple, which contains information about the direct superclasses of the class.

Given the code below, which of the expressions will evaluate to true? (select two) class Top: value = 3 def say(self): return self.value class Midlle(Top): value = 2 class Bottom(Midlle): def say(self): return -self.value short = Bottom() tall = top() average = Midlle()

average.value == 2// short.value == 2

Which of the following classes have valid constructors? (select two)

class Bet: def__init__(self): raise ArithmeticError // class Aleph: def __init__(self): self.attribute = True

which method is used to break the connection between the file handle and a physical file?

close()

Given the class below, indicate a method which will correctly provide the value of the rack field? class Storage: def __init__(self): self.rack = 1 # Insert a method here. stuff = Storage() print(stuff.get())

def get(self): return self.rack

What is the expected output of the following code? class Aircraft: def start(self): return "default" def take_off(self): start() class Fixed_Wing(Aircraft): pass class Fixed_Wing(Aircraft): def start(self): return "spin" fleet = [Fixed_WIng(), Rotor_Craft()] for airship in fleet: print(airship.start(), end=" ")

default spin

The system that allows you to diagnose input/output errors in Python is called:

errno

what is the expected output of the following code? string = '\' '.join(("mary", "had", "21", "sheep")) print(string[0:1].islower())

false

a function named f() is included in a module named m, and the module is a part of a package named p, which of the following code snippets allows you to properly invoke the function? (Select two answers)

from p.m import f f() // import p.m p.m.f()

Which of the following functions come from the math module? (select two)

hypot() // sqrt()

Given the code below, which of the following expressions will evaluate to true? (select two) class Alpha: value = "Alpha" def say(self): return self.value.lower() class Beta(Alpha): value = "Beta" class Gamma(Alpha): def say(self): return self.value.upper() class Delta(Gamma, Beta): pass

isinstance (d, Beta) // d.say() == "BETA"

Which of the following statements are true about the __pycache__ directory/folder? (select two)

it contains semi-compiled module code. // it is created automatically.

What is true about sys.path?

it is a list of strings which indicates all directories/folders scanned by python in order to find the specific modules.

What is the expected behavior of the following snippet? class Team: def show_ID(self): print(self.get_ID()) def get_ID(self): return "anonymous" class A(Team): def ge_ID(self): return "Alpha" a = A() a.show_ID()

it outputs Alpha

What is the expected behavior of the following code? class Package: spam = ' ' def __init__(self, content): Package.spam += content + ";" envelope_1 = Package("Capacitors") envelope_2 = Package("Transistors") print(envelope_2.spam)

it outputs Capacitors;Transistors;

What is the expected behavior of the following code? class tin: label = "Soup" def __init__(self, prefix): self.name = prefix + " " + Tin.label can_1 = Tin("Tomato") can_2 = Tin("Chicken") print(can_1.label == can_2.label)

it outputs True

Which of the following lines contain contain valid Python code? (select two)

lambda x,y: '0123456789' [x:y] // lambda x,y: x + y

which of the following lines contain valid python code?

lambda x: x+1 // lambda x : None

Which of the following messages will appear on the screen when the code is run? class Failure(IndexError): def __init(self, message): self.message = message def __str__(self): return "problem" try: print("launch") raise Failure("ignition") except RuntimeError as error: print(error) except IndexError as error: print("ignore") else: print("landing")

launch // ignore

What is the expected output of the following code? vect = ["alpha", "bravo", "charlie"] new_vect = fliter(lambda s: s[-1].upper() in ["A", "O"], vect) for x in new_vect: print(x[1], end = ''')

lr

Which of the folllowing expressions evaluate to True? (select two)

ord('x') - ord('X') == ord(' ') // chr(ord('k') +2) == 'm'

A programmer needs to use the following functions: machine(), choice(), and system(). Which modules have to be imported to make this possible? (Select two answers)

platform// random

Which of the following snippets output ABC to the screen? (select two)

print('ABCDEF' [:3])// print('AXBYCZ' [::2])

Given the class below complete the print() method body in a way that will ensure that the get() method is properly invoked. (select two) class Storage: def __init__(self): self.rack = 1 def get(self): return self.rack def print(self): # insert a line of code here stuff = Storage() print(stuff.print())

print(self.get()) // print (Storage.get(self))

Which of the following messages will appear on the screen when the code is run? (select two) class Accident(Exception): def __init__(self, message): self.message = message def __str__(self): return "problem" try: print("action") raise Accident("accident") except Accident as accident: print(accident) else: print("success")

problem // action

Given the code below, indicate the code line which correctly invokes the __action() method class BluePrint: __element = 1 def __init__(self): self.component = 1 def __action(self): pass product = BluePrint()

product._BluePrint_action()

which of the following assignments can be performed without raising any exceptions? (select two)

s = 'rhyme' s = s[::2] // s = 'rhyme' s = s[-2]

which of the following statements are true?

stdin,stdout, and stderr are the names of pre-opened streams. // The print() function writes its output to the stdout stream.

Which of the following are true about string encodings used by python?(select two)

the python escape sequence always begins with the / character // codepoint is a number which corresponds to a character

Which of the following snippets can be used to build a new string consisting of sorted characters contained in the 'zyx' string assigned to the letters variable?(select two) letters = 'zyx'

tmp = list(letters) tmp.sort() new_string = ''.join(tmp) // new_string = ' '.join(sorted(letters))

what is the expected output of the following code? foo = "Mary had 21 little sheep" print(foo.split()[2].isdigit())

true


Kaugnay na mga set ng pag-aaral

ENZYMES LOWER the ACTIVATION ENERGY for reactions

View Set

Ch 3: The Accounting Cycle: End of the Period

View Set

Exam FX Life and Health Insurance Practice Exam: Learning Mode

View Set

Functions in Python: Working with Advanced Features of Python Functions

View Set

Chapter 57 The Child With Alterations in Skin Integrity

View Set

Econ 202 Homework for Chapter 14

View Set