PluralSight - Python Core Language

Ace your homework & exams now with Quizwiz!

You must create an Iterator to iterate from values one to five and then stop. How can you do it using a generator expression? - [i for i in range(1,6)] - (i for i in range(5)) - {i for i in range(1,6)} - (i for i in range(1,6)) - I don't know yet.

(i for i in range(1,6))

What is the maximum number of arguments that can be passed inside fractions.Fraction()? - 1 - 3 - 2 - 0 - I don't know yet.

2

What is the output of the following code? class test():a = 8def __init__(self, a=5):self.a = aprint(self.a)foo = test(2) - 2 - 5 - None - 8 - I don't know yet.

2

How would you identify the location of the installed packages? - >>> import site >>> site.getuserbase() - >>> import site >>> site.getsitepackages() - >>> import site >>> site.FILE - >>> import site >>> site.USER_BASE - I don't know yet.

>>> import site >>> site.getsitepackages()

For the following code, how can you find the order to search for an attribute starting with class C? class A:def a():return 'a' class B():def b():return 'b' class C(A, B):def c():return 'c' - C.__mro - C.mro(A, B) - C.mro([A, B]) - C.__mro__ - I don't know yet.

C.__mro__

What is a benefit of using dictionary views? - Works with unicode - Compresses the information - Conserves memory - Assists data conversion - I don't know yet.

Conserves memory

AssertionError and BufferError are derived from which built-in Python class? - SuperException - OSException - RunTimeException - Exception - I don't know yet.

Exception

How do you initialize an instance for the following class to output a tuple (5, 'print', ['1', '2'])? class Class:def __init__(self, a, b, c):self.a = 5self.b = 'print'self.c = cdef r(self):return (self.a, self.b, self.c) - obj = Class(1, 'hello', ['1', '2']) obj.r() - obj = Class(1, ['1', '2']) obj.r() - obj = Class(['1', '2']) obj.r() - obj = Class([1, 'hello', ['1', '2']]) obj.r() - I don't know yet.

obj = Class(1, 'hello', ['1', '2']) obj.r()

How could you determine if variable my_string is a Unicode or byte string? - >>> repr(my_string) - >>> type(my_string) - >>> my_string.type() - >>> my_string..isidentifier() - I don't know yet.

>>> type(my_string)

What makes a module of a package importable? - An __init__.py in the folder of the module - A main.py in the folder of the module - A __call__.py in the folder of the module - A new.py in the folder of the module - I don't know yet.

An __init__.py in the folder of the module

You have a class named Class as shown: class Class:def init(self, a, b):self.a = aself.b = b You enter two values for Class to later display them on screen, but it resulted in the error TypeError: Class() takes no arguments. How can you display the output without an error? - By using __init__(...) and the following code: class Class:...def ret(self):return (self.a, self.b)obj = Class(1, 2)print(obj.ret()) - By using __init__(...) and the following code: class Class:...def return(self):return (self.a, self.b)obj = Class('1', 2)print(obj.return()) - By using __input__(...) and the following code: class Class:...def ret(self):return (a, b)obj = Class(1, 2)print(obj.ret()) - By using __input__(...) and the following code: class Class:...def ret():return (self.a, self.b)obj = Class(1, 2)print(obj.ret()) - I don't know yet.

By using __init__(...) and the following code: class Class:...def ret(self):return (self.a, self.b)obj = Class(1, 2)print(obj.ret())

You have subdirectories with packages you'd like to ensure are imported when you import the main directory. Where can you add import lines for the subdirectories to do this? - In the __init.py__ file of the main directory - At the top of the script - In each subdirectory - In the usr directory - I don't know yet.

In the __init.py__ file of the main directory

What example shows how a built-in Python function can execute reverse iteration on a range of numbers using a for loop? - N = 6 for num in range(N + 1) : print (num, end = " ") - N = 6 for num in range(N + 1) : print (num, reverse(num)) - N = 6 for num in reversed(range(N + 1)) : print (num, end = " ") - N = 6 for num in range(N + 1) : reverse(num, end = " ") - I don't know yet.

N = 6 for num in reversed(range(N + 1)) : print (num, end = " ")

What takes place when a generator function calls yield? - The generator function iterates through a nested for loop and saves each iterator into a new temporary variable. - The generator function exits and the variables are all initialized to 0. - The generator function will save all variable values and pause. The code to be executed next is saved and will execute when the next() function is called. - The generator function continues execution as normal until the yield function no longer can return positive integers. - I don't know yet.

The generator function will save all variable values and pause. The code to be executed next is saved and will execute when the next() function is called.

The update function in the following code is supposed to add a new user to your dictionary: Users = {}def add_users(new_user):Users.update(new_user)add_users('User1') What is wrong with this code? - The new_user is an instance of a str data structure. Also, inserting a new user with matching keys will overwrite the already existing one. - 'User1' must be enclosed in curly brackets. - You must specify how many elements you want to store in the dictionary, otherwise it will not work. - The def function does not return the dictionary Users so that just exists locally. - I don't know yet.

The new_user is an instance of a str data structure. Also, inserting a new user with matching keys will overwrite the already existing one.

The unpacking gives an error with the following tuple definition: pythonmy_numbers = tuple( _ for _ in range(10) if _ % 3 == 0)first, second, third = my_numbersTraceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: too many values to unpack (expected 3) What is the problem? - When you print my_number it shows it's a generator object and it cannot be unpacked. - The tuple cannot be unpacked into more than three variables. - This is not Python 3 compatible code, it's from Python 2 and the syntax is invalid. - The tuple holds four values and the unpacking expression specified only has three variables. - I don't know yet.

The tuple holds four values and the unpacking expression specified only has three variables.

You are using the command line to iterate through a list using the next() command. What does it mean when you receive this error on your last execution of the next() command? Traceback (most recent call last):File "<pyshell#10>", line 1, in <module>next(list)StopIteration - The list items are outside the bounds of what the list was initialized at. - The list contains integers that cannot be iterated. - There are no more items left in the list to iterate through. - The list is empty. - I don't know yet.

There are no more items left in the list to iterate through.

What is the difference in the following two Python statements? (1,), 1,? - There is no difference because both expressions evaluate to the same single element tuple. - The expression with parenthesis is a zero element tuple while the expression without parenthesis is a single element tuple. - There is no difference because both expression evaluate to the same zero element tuple. - The expression with parenthesis is a single element tuple while the expression without parenthesis is a zero element tuple. - I don't know yet.

There is no difference because both expressions evaluate to the same single element tuple.

Why would you use keyword arguments in Python functions? - To change variables depending on the function - To create variable length arguments - To make the code more explicit by setting default values - To pass different object types in keyword arguments - I don't know yet.

To make the code more explicit by setting default values

A deque object has reached its maximum length of eight that was specified by the object initialization. If two new items are added after the deque bound length is met, how is the deque affected? - Two items are removed from the end of the deque. - Two items are added to the end of the deque. - Two items are discarded from the opposite end. - Two items are added to the beginning of the deque. - I don't know yet.

Two items are discarded from the opposite end.

Your code is slow while iterating over a dictionary with more than 100,000 records. Your code attempts to access the underlying data in the dictionary by making a copy into a list. What would you use to access the underlying data in a dictionary without making a copy and therefore conserving memory and reducing runtime? - Keyword assignments - Lists - Views - Functions - I don't know yet.

Views

When are the default arguments of a function evaluated? - After the pass is called - When the function is defined - When the global variables are defined - Each time the function is called - I don't know yet.

When the function is defined

How can you create a global variable in Python? - You can only do it in modules. - You use the global keyword before its first assignment. - You place it on the top of your scripts. - You cannot have global variables in Python. - I don't know yet.

You use the global keyword before its first assignment.

What function must be defined to a callable object? - __new__ - __call__ - __init__ - __super__ - I don't know yet.

__call__

Which module is most beneficial if you are working on a Python 2 application and planning on having Python 3 support for your code? - sys module - __future__ module - _testmultiphase module - pip module - I don't know yet.

__future__ module

Which special function would override the following operator?variable_one ^ variable_two - __xor__ - __pow__ - __invert__ - __mod__ - I don't know yet.

__xor__

Which snippet of code correctly defines a static method? - class Class:@staticdef r():pass - class Class:@staticmethoddef r():pass - class Class:@staticmethoddef r(self):pass - class Class:@staticdef r(self):pass - I don't know yet.

class Class:@staticmethoddef r():pass

You use a custom context manager for opening a file and for returning it for use in a with statement. Inside which function should you add the statement that assigns the open file to a variable? class customContext: def __init__(myfile, name): def __enter__(myfile): def __exit__(myfile): - def __exit__(myfile): - def __in__(myfile): - def __enter__(myfile): - def __init__(myfile, name): - I don't know yet.

def __enter__(myfile):

You must create a Python script for a health care company's accounting department. The script must filter list input using the filter() function. What function definition could you pass to the first parameter of the filter function to filter the list to include elements that only start with the character H? - def startsWithH(list):for item in element:if item = 'H'return element[0] == 'H'return False - def startsWithH(List):if len(element) == H:return element[i]return False - def startsWithH(element):if element[i] == 'H'return element return False - def startsWithH(element):if len(element) > 0:return element[0] == 'H'return False - I don't know yet.

def startsWithH(element): if len(element) > 0: return element[0] == 'H' return False

You want to combine two lists into a dictionary. You produced the following code but it does not work as intended. What function should you combine with dict() to create the desired output? list_1 = [ 'a', 'b', 'c', 'd'] list_2 = [ 1, 2, 3, 4 ] dict_1 = dict(list_1, list_2) ## Desired output is { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4 } - convertTodict(list_1, list_2) - combine(list_1, list_2) - list(zip(list_1, list_2)) - dict(zip(list_1, list_2)) - I don't know yet.

dict(zip(list_1, list_2))

You have written a function that prints even numbers starting from zero by keeping in mind that only a limited amount of memory is consumed at a time. def even_series():num = 0while True:yield numnum += 2 Based on this function, how can you print the values 0, 2, and 4? - print(next(even_series())) print(next(even_series())) print(next(even_series())) - even = even_series() print(next(even)) print(next(even)) print(next(even)) - even = next(even_series()) print(next(even)) print(next(even)) - print(next(even_series(), 3)) - I don't know yet.

even = even_series() print(next(even)) print(next(even)) print(next(even))

Which code is equivalent to the following code? import ostry:os.remove('load_file.tmp')except FileNotFoundError:pass - from contextlib import ContextDecorator class demo(): def __exit__(self): ContextDecorator(os.remove('load_file.tmp')) - from contextlib import suppress with suppress(FileNotFoundError): os.remove('load_file.tmp') - from contextlib import ExitStack class demo(): def __remove__(self): ExitStack(os.remove('load_file.tmp')) - from contextlib import closing with closing(FileNotFoundError): os.remove('load_file.tmp') - I don't know yet.

from contextlib import suppress with suppress(FileNotFoundError): os.remove('load_file.tmp')

You have your custom_module with hundreds of classes. How would you import just the class named MyClass and refer to it as Production? - import MyClass from custom_module as Production - import MyClass from custom_module alias Production - from custom_module import MyClass as Production - import custom_module.MyClass - I don't know yet.

from custom_module import MyClass as Production

The list lst contains five elements at the beginning: lst = ['This is an example statement!', 'Cloud', 'Compute', 'Memory', 'Resources'] After running the code lst.insert(0, lst[:]), the list received a lengthy element at its first index. How can you replace the first lengthy element using ellipsis? ## Expected Output[[...],'This is an example statement!','Cloud','Compute','Memory','Resources'] - import pprint pp = pprint.PrettyPrinter(length=1) pp.pprint(lst) - import pprint pp = pprint.PrettyPrinter(depth=1) pp.pprint(lst) - import pprint pp = pprint.PrettyPrinter(depth=5) pp.pprint(lst) - import pprint pp = pprint.PrettyPrinter(length=5) pp.pprint(lst) - I don't know yet.

import pprint pp = pprint.PrettyPrinter(depth=1) pp.pprint(lst)

Which function can check if a class Exception is part of a class BaseException? - issubclass(Exception, BaseException) - isinstance(Exception, BaseException) - isbaseclass(Exception, BaseException) - ischildclass(Exception, BaseException) - I don't know yet.

issubclass(Exception, BaseException)

You would like to write a function that takes any number of arguments, but is allowed to perform a single expression. Which one would you choose? - lambda - named - def - class - I don't know yet.

lambda

You have two lists each holding three elements as follows: X = [1, 0, 1]Y = [1, 1, 0] Which line of code will result in an integer data type list [0, 1, 1] representing an exclusive or (XOR) operation between list X and list Y? - list(map(lambda x, y: x ^ y, X, Y)) - filter( lambda x, y: x ^ y, (X, Y) ) - list(map(lambda x, y: x != y, X, Y)) - filter(lambda x, y: x != y, X, Y) - I don't know yet.

list(map(lambda x, y: x ^ y, X, Y))

You have four different data type variables: v1 = 45 v2 = 62.88 v3 = 'Hi' v4 = 8+9j Which type of conversion will execute successfully? - print(complex(v2)) - print(int(v4)) - print(complex(v3)) - print(str(float(v4))) - I don't know yet.

print(complex(v2))

For the statement 5 / '5' in the try block, how can you obtain the error class along with its message? - Use args: try:5 / '5'except TypeError as E:print(E.args) - Use msg: try:5 / '5'except TypeError as E:print(E.msg) - Use eval: try:5 / '5'except TypeError as E:print(eval(E)) - Use repr: try:5 / '5'except TypeError as E:print(repr(E)) - I don't know yet.

repr: try:5 / '5'except TypeError as E:print(repr(E))

Running the following code, returns the output as False. What should you change for it to show True? from decimal import * getcontext().prec=1 Decimal(0.1 + 0.2) == Decimal (0.3) - Decimal(0.1) + 0.2 == 0.3 - from decimal import float - round(Decimal(0.1 + 0.2), 1) == round(Decimal(0.3), 1) - getcontext().prec=2 - I don't know yet.

round(Decimal(0.1 + 0.2), 1) == round(Decimal(0.3), 1)

Which keyword is required as a mandatory argument for instance methods? - __self__ - self - self__ - __self - I don't know yet.

self

Which Python data structure allows you to have only a unique member without verification of what you add to it? - list - tuple - set - dict - I don't know yet.

set

An object named p from a class named person contains attributes for first name and last name. What code option would change the attribute last_name of the class person to "User1"? - setattr('p.last_name', 'User1') - setattr(p, 'last_name', 'User1') - setattr(p[last_name] == 'User1') - setattr(p.last_name = 'User1') - I don't know yet.

setattr(p, 'last_name', 'User1')

Consider the code a = input(). What is the data type of the variable a if the input value is 78? - int - float - complex - str - I don't know yet.

str

What list in Python contains arguments passed to a script? - list.argv - arguments.list() - sys.argv - stdout() - I don't know yet.

sys.argv

When writing to a stream, what must you adjust for the following code to work? str_val = "Hello"open" ('myfile.txt', 'w'): w.write(str_val) - with open('myfile.txt', 'wb'): wb.write(str_val.encode('utf-8')) - with open('myfile.txt', 'wb') as w: w.write(str_val) - open('myfile.txt', 'wb+') as w: w.write(str_val) - with open('myfile.txt', 'wb') as w: w.write(str_val.encode('utf-8')) - I don't know yet.

with open('myfile.txt', 'wb') as w: w.write(str_val.encode('utf-8'))

How do you define an empty set? - x = set() - x = {} - x = {()} - x = set([]) - I don't know yet.

x = set()

In Python, which syntax is associated with generators? - yield from - create from - get from - construct from - I don't know yet.

yield from

What is the output of the given code? class test():class_var = 1def __init__(self, var):self.var = varfoo = test(2)bar = test(3)print(foo.__dict__)print(bar.__dict__) - ['var', 2] ['var', 3] - {'var': 2} {'var': 3} - 23 - None None - I don't know yet.

{'var': 2} {'var': 3}

Given the following code: def double(n): return n*n kval = {'foo': {'a': 4, 'b': 3}, 'bar': {'c': 5, 'd': 8}, 'baz': {'e': 8, 'f': 7}} Which dictionary comprehension code can lead you to the following result? # Square of each value {'foo': {'a': 16, 'b': 9}, 'bar': {'c': 25, 'd': 64}, 'baz': {'e': 64, 'f': 49}} - {k1: {k2: double(v1) for k1, v1 in v1.items()} for k2, v2 in kval.items()} - {k1: {k2: double(v2) for k2, v2 in v1.items()} for k1, v1 in kval.items()} - {k1: k2: double(v1) for k1, v1 in v1.items() for k2, v2 in kval.items()} - {k1: k2: double(v2) for k2, v2 in v1.items() for k1, v1 in kval.items()} - I don't know yet.

{k1: {k2: double(v2) for k2, v2 in v1.items()} for k1, v1 in kval.items()}


Related study sets

MOD 3 WEEK 4 Compliance in Healthcare Environments

View Set

ZOO4480: Topic 6: Modes of Feeding

View Set