PCAP Test

Ace your homework & exams now with Quizwiz!

Which of the following evaluates to True? (Select 2 Answers) 'abc' < 'abcd' 'abc' > 'abcd' 'Abc' > 'abc' 'abc'=='Abc' 'abc'>'Abc'

'abc' < 'abcd' and 'abc'>'Abc' Strings in python are compared character by character from left to right and whenever a lower codepoint is encountered, the string with the higher code point value is declared greater. 'abc'<'abcd' is correct because although all code points are equal from left to right but since the string on the right is longer hence it is greater. 'Abc'>'abc' is incorrect because when comparing from left to right, character by character, the first character of left string is 'A' while first character of right string is 'a' and the lower case characters have higher code point values hence right string should be greater. Same reason why 'abc'=='Abc' is incorrect as well.

What is the output of the following snippet of code? class A: pass class B(A): pass class C(B): pass print(C.__bases__)

(<class'_main_.B'>,) You have to remember that the '__bases__' property holds the information about the immediate super class of the class. It is not aware of any other hierarchy. Also, it contains the super classes in a tuple and NOT a list.

What is the output of the following snippet of code: a = "television" print(a.find('tele.'))

-1

What is the output of the following snippet of code? import math as m print(m.floor(-3.3) - m.trunc(-3.9)) ​

-1 For positive numbers, both 'trunc' and 'floor' functions work in the same way, i.e. they both remove the decimal point and whatever is to the right of it but their difference is visible for negative numbers. The math.floor() method rounds a number DOWN to the nearest integer. So for -3.3, rounding DOWN means -4 and NOT -3 because -4 is smaller as compared to -3.3, while -3 is bigger. Again I will emphasize that if you are not comfortable using 'ceil' and 'floor' functions, you should draw a number line to practice them. The math.trunc() method returns the truncated integer part of a number. Note: This method will NOT round the number up/down to the nearest integer, but simply remove the decimals. So final answer is given by: -4 - (-3) = -1

import math as m print(m.sqrt(16) - m.hypot(4,3))

-1.0 The 'sqrt' function finds the POSITIVE square root of the number and the 'hypot' function finds the length of the hypotenuse from the given 2 arguments (Formula: c = √(a² + b²)).

Select the correct output of the below code snippet: print(-6 // 4) print(6. // -4)

-2 -2.0 Explanation // is the floor division. It divides it, and then makes it the integer below. To provide this behavior, integer division rounds towards negative infinity, rather than towards zero. Just to explain further: x // y == math.floor(x/y) x // y is the largest integer less than or equal to x / y so in the case of -6//4, 6/4 will give you 1.5 while is negative so you are getting -1.5 but in the case of 6//4 it will try to give you an integer towards -2, not -1 as per the definition. similarly, in case of -5//2 you will get -3

What is the output of the following code: a = "qwecvxqwe" print(a.index('qwe') - a.rfind('qwe'))

-6 The index method would return '0' while the rfind method will return 6. Hence the output will be -6

What is the difference between / and // for division

/ you get a float back and the exact division number // rounds the result closest to negative infinity

What is the expected output of the following code? data = () print(data.__len__())

0

What is the expected output: print(len([i for i in range(0, -2)]))

0

What would be the output of the following code snippet? x=1 y=0 x=x^y y=x^y x=x^ y print(x)

0

What is the output of 2//3*4

0 As mentioned in the question it has to be evaluated as left-side binding. We will start evaluating 2//3 first. 2//3 will give zero as per floor operator rule with a nearest integer value. Then next we will do 0*4 hence answer will be 0.

What is the output of the following snippet of code a = 'edge' print(a.find('e'))

0 The 'find' function returns the index of the first match within the string, since the first 'e' is encountered at index 0, the output is 0.

Select the correct output of the below code snippet: print(1 // 2) print(6. // -4)

0 -2.0

What is the output: a=1 b=1 print(a^b)

0 This is bitwise XOR. Each bit position in the result is the logical XOR of the bits in the corresponding position of the operands. (1 if the bits in the operands are different, 0 if they are the same.)

What is the expected output of the following code? import calendar c = calendar.Calendar() for weekday in c.iterweekdays(): print(weekday, end=" ")

0 1 2 3 4 5 6

What is the expected output x = 1//5 + 1/5

0.2 0 + 0.2

What is the output of the following code in python Print(1%2)

1

What is the output of the below code def fun(x): x=2 x=1 fun(x) print(x)

1 If you notice carefully, x=1 is outside the function and even if you call f(x), it will not change the value of x=1 inside the function. So when you call print(x) it will print the value 1.

Select the correct output of the below code: print(10 % 7 % 2)

1 The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. So the print(10 % 7 % 2) statement will calculate 10%7 first and return 3 and then 3%2 will be calculated and it will return 1

What is the output of the following snippet of code: a = "refrigerator" print(a.find('e'))

1 The 'find' function returns the index of the first match within the string, since the first 'e' is encountered at index 1, the output is 1.

What is the expected output of the following code? numbers = (1, 2, 5, 9, 15) def filter_numbers(num): nums = (1, 5, 17) if num in nums: return True else: return False filtered_numbers = filter(filter_numbers, numbers) for n in filtered_numbers: print(n)

1 5

What is the expected output of the following code? data = [(0, 1), (1, 2), (2, 3)] res = sum(i for j, i in data) print(res)

1 +2 +3 = 6

What is the expected output of the following code? x = 0 y = 1 x = x ^ y y = x ^ y y = x ^ y print(x, y)

1 1 The bitwise xor operator returns 1 when one operand is 1 and the other is 0 When both operands are 0 or both operands are 1 it returns 0

Which of the following evaluates to False (select 2 answers) 1. 'abc' > 'abcd' 2. 'Abc' > 'abc' 3. 'cA' > 'Caaaaaaaaaaaa' 4. 'abc' < 'abcd' 5. 'abc' > 'Abc'

1. 'abc' > 'abcd' 2. 'Abc' > 'abc' Strings in python are compared character by character from left to right and whenever a lower codepoint is encountered, the string with the higher code point value is declared greater.

What is false about string comparison in Python 1. Comparison is based on sum of the code points of all the characters in the string 2. Capital letters have higher code point values as compared to lowercase letters 3. Numbers have lower code point values as compared to Capital letters 4. Strings are compared character by character from left to right 5. Comparison ends when a character with higher code point is found as compared to the code point value of character at same index in second string

1. Comparison is based on sum of the code points of all the characters in the string 2. Capital letters have higher code point values as compared to lowercase letters

Which of the following is a FALSE statement (Select 2 Answers) 1. In UTF-8 the 8 represents 8 languages 2. ASCII is a subset of UTF-8 3. ASCII stands for American standard code for information interchange 4. ASCII and UTF-8 are mutually exclusive 5. ASCII is a 7-bit character set containing 128 characters

1. In UTF-8 the 8 represents 8 languages 4. ASCII and UTF-8 are mutually exclusive The correct answer choices are false statements about ASCII and UTF-8 while the incorrect choices are facts and should be memorized

Which of the following is an INCORRECT way to open a file in read mode? 1. file = open(file, 'read') 2. file = open(file, 'w') 3. file = open(file, 'r') 4. file = open(file) 5. file = open(file, 'r+')

1. file = open(file, 'read') 2. file = open(file, 'w')

Given the following snippet of code: class A: var = 1 def __init__(self): self.x = 1 class B(A): def __init__(self): super().__init__() b = B() 1. hasattr(B, 'super') 2. hasattr(b, 'x') 3. hasattr(B, 'A') 4. hasattr(B, '_init_') 5. hasattr(b, '_init_)

1. hasattr(B, 'super') 3. hasattr(B, 'A') '__init__' is the attribute of both classes and objects.Note: Even though __init__ is the attribute of objects, it is NOT present in the __dict__ property of objects but IS present in the __dict__ property of class. hasattr(B, 'A') option is correct because A is not an attribute of B but is the super class of B. hasattr(B, 'super') option is correct because the super() function is used to give access to methods and properties of a parent class and is not an attribute of child class.

What is the output of the following snippet of code? a = lambda x,y: x+y b = lambda x: x*2 def func(a,b,c): return a(b(c[0]),b(c[1])) print(func(a,b,[2,3])) ​

10 Although the code looks very cluttered, you need to break it down and take it step by step. We are printing the output of the function 'func' which takes in 3 arguments. Now look at what is happening inside the function 'func'. We are calling the function 'a' on 2 arguments. We have not yet looked at the implementation of a, we just know that it takes in 2 arguments. Next we look at the arguments that are being passed to function 'a'. The first argument is the OUTPUT of the function 'b' which is being passed a single argument which corresponds to the 0th index of item 'c'. Second argument is also the same except that the argument being passed to function 'b' is the item corresponding to 1st index of 'c'. Now we move from inside to out. 'c' is a list containing '2' on 0th index and '3' on 1st index. Function 'b' is a lambda function that takes in one argument and MULTIPLIES it by 2. So b[c[0]] becomes 2*2 = 4 and b[c[1]] becomes 3*2 = 6. Next we look at implementation of function 'a', which is a lambda function that takes in 2 arguments and returns the sum. Therefore, when we pass it, 4 and 6 as arguments, the output is 4+6 = 10. Hence 10 gets printed on the screen.

What is the decimal base

10 Decimal number system which has the base 10, represent any number using 10 digits 0-9

What is the output of the following snippet of code? class A: __var = 100 def __init__(self): self.__var = 10 def get_var(self): return self._A__var a = A() print(a.get_var())

10 '_A__var' is another way for accessing the private instance variable '__var'. If you wanted to access the class variable '__var' then you need to write A.__var return A._A__var to get the class variable or return A.__var

What is the output of the following snippet of code? class A: def __init__(self, var): self.var = var a = A(10) b = A(100) print(a.var)

10 since var has been defined with the 'self' keyword, it is an instance variable and will be unique for each object. Therefore when var variable of object a is printed, its value is 10.

What is the output of the following code: class A: __Var = 100 def __init__(self): A._A__Var += 1 a = A() b = A() print(A()._A__Var)

103 Each object initialization increases the value of '__Var ' variable by one. When object 'a' is created, the value becomes 101, when 'b' is created the value becomes 102 and finally in the print statement we are creating another object although we are not assigning it to a variable, the value becomes 103. Private class variables can be accessed inside and outside the class by using the way shown in question to access them.

What is the expected output of the following code? from random import randint for i in range(2): print(randint(1, 2), end='')

11, 12, 21, 22

fruits1 = ['Apple', 'Pear', 'Banana'] fruits2 = fruits1 fruits3 = fruits1[:] fruits2[0] = 'Cherry' fruits3[1] = 'Orange' res = 0 for i in (fruits1, fruits2, fruits3): if i[0] == 'Cherry': res += 1 if i[1] == 'Orange': res += 10 print(res)

12 A list is a mutable data type. Assigning it will create a reference. Slicing it from start to end [:] will create a copy. Therefore Cherry goes in fruits2 and thereby also in fruits1 Orange only goes in fruits3

What base does a Hexadecimal have and what are the they

16 Decimal uses ten digits, binary uses two digits, and hexadecimal uses sixteen digits. Since we only have the ten digits from the decimal system to use, we substitute letters for everything above the number nine. Therefore, the digits in hexadecimal are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. They represent zero through nine, then A is worth ten, B is worth eleven, C is worth twelve, D is worth thirteen, E is fourteen, and F wraps up with a value of fifteen. So, there are sixteen digits in hexadecimal.

from datetime import datetime datetime = datetime(2019, 11, 27, 11, 27, 22) print(datetime.strftime('%y/%B/%d %H:%M:%S'))

19/November/27 11:27:22

What is the expected output of the following code? class A: def __init__(self): self.i = 1 def func(self): self.i = 10 class B(A): def func(self): self.i += 1 return self.i b = B() print(b.func())

2

What is the index of: 'fer' in 'referee' when using the index method

2

What is the binary number base?

2 Binary number system, in mathematics, positional numeral system employing 2 as the base and so requiring only two different symbols for its digits, 0 and 1

Select the correct output of the below code: print(17%3) print(14%3.5)

2 0.0 % Modulus : divides left hand operand by right hand operand and returns remainder. print(17%3) will return the remainder 2. print(14%3.5) will return 0.0 as it's float division.

Select the correct output of the following code snippet: print(8 / 4) print(8 / 4.) print(8. / 4) print(8. / 4.)

2 2.0 2.0 2.0 / : Divides the number on its left by the number on its right and returns a floating point value. So even the integer division 8/4 will return the float value 2.0

What is the expected output of the following code? data = 'abbabadaadbbaccabc' print(data.count('ab', 1))

2 the 1 means it starts at index 1

How many # will be printed in the following output: var = 2 while var < 8: print('#') var = var<<1

2 Bitwise left shift: Shifts the bits of the number to the left and fills 0 on voids right as a result. Similar effect as of multiplying the number with some power of two. Hence in this case the loop will run only twice and after that value of var will go higher than 8.

Select the correct statement below about the print() function with comma separated arguments. 1. print() function invoked with more than one argument outputs them in seperate lines 2. print() function invoked with more than one arguments outputs them all in one line. 3. print() function puts a space between the output arguments by default 4. print() function with more than one argument will give error.

2. print() function invoked with more than one arguments outputs them all in one line. 3. print() function puts a space between the output arguments by default

What is the expected output x = 4.5 y =2 print (x//y)

2.0 If one operand is a float, the floor division operator returns a float. Only if both operands are an integer, the floor division operator returns an integer.

What is the output of the following code: num1= input() num2= int(input()) print (num1 * num2)

222

What is the expected output of the following code? class Test: def __init__(self, id): self.id = id id = 100 x = Test(23) print(x.id)

23

Select the correct output of the below code snippet: print(2 ** 2 ** 3)

256 The associativity is the order in which Python evaluates an expression containing multiple operators of the same precedence. Almost all operators except the exponent (**) support the left-to-right associativity. So print(2 ** 2 ** 3) will be evaluated right to left. hence it will be treated like 2**8 it will return 256.

What is the expected output of the following code? x = True y = False z = False if not x or y: print(1) elif not x or not y and z: print(2) elif not x or y or not y and x: print(3) else: print(4)

3

What is the length of this list myList = [0 for i in range(1,4)]

3

num=4 while num>=0: print('#') num -=2

3

What is the output of the following snippet of code? a = ['a','A','B','C','q','w','p'] b = list(filter(lambda x: x.isupper(), a)) print(len(b))

3 The 'filter' function is taking in 2 arguments, the first is the predicate, which is a fancy way of calling a function that returns a Boolean and the second argument is the object to apply the predicate. In this case we are passing in the lambda function that checks whether a character is upper case or not. The function is then applied to each member of the list a. And the final result contains the characters which returned true i.e. which are upper case. Finally the output is the length of the filtered list.

The file abc.txt contains the following 3 lines of text: abc def ghi What is the output of the following snippet of code in the abc.py file? file = open('abc.txt') print(len(file.readlines()))

3 The 'readlines()' method returns a list containing each LINE in the file as a list item. Since there are 3 lines in the file, the length of the list output from 'readlines()' will be 3.

What will be the output of the following code? myList=[[2-i for i in range(2)] for j in range(2)] var=0 for i in range(2): var+=myList[i][i] print(var)

3 myList=[[2-i for i in range(2)] for j in range(2)] will form a list [[2, 1], [2, 1]] for loop will run twice due to the range function. inside the for loop during the first run the value of var will become 2. Because the value of myList[0][0] is 2 in the second run it will become 2+1 because the value of myList[1][1] is 1.

What is the expected output of the following code? num = 1 def func(): num = 3 print(num, end=' ') func() print(num)

3 1 The num variable inside the function scope will be a different variable. It will shadow the name of the num variable from the outer scope, but it will be a different entity.

What is the expected output of the following code? def func(p1, p2): p1 = 1 p2[0] = 42 x = 3 y = [1, 2, 3] func(x, y) print(x, y[0])

3, 42

What will be the result of running the following snipped of code? print (dir(pandas)) 1. It will print dictionary containing the names of all entities inside the pandas module 2. It will print the description of the pandas module 3. It will print a list of names of all entities inside the pandas module 4. It will print all the functions inside the pandas module 5. It will print "pandas" to the console

3. It will print a list of names of all entities inside the pandas module The 'dir' function will return all the properties and methods, even built-in properties for any entity passed to it. In this case it is the 'pandas' module

Which of the following statements are incorrect about the sys.path variable 1. The sys.path variable is a lit 2. The sys.path variable contains string 3. The sys.path variable is a dictionary of paths which python uses to look for modules 4. The sys.path variable cannot be modified 5. The sys.path variable is mutable

3. The sys.path variable is a dictionary of paths which python uses to look for modules 4. The sys.path variable cannot be modified The correct answer choices are false statements about the sys.path variable as it is a mutable list of strings.

Which of the following are the incorrect ways to create tuple 1. Tuple = (2,7,3,9) 2. Tuple = 2,7,3,9 3. Tuple = [2,7,3,9] 4. Tuple = {2,7,3,9}

3. Tuple = [2,7,3,9] 4. Tuple = {2,7,3,9}

What is the output x = 2/2 + 2 **2-2

3.0

The value thirty point eleven times ten raised to the power of nine should be written as:

30.11E9

What would be the output of the following code: myList = [5, 7, 4,9,2] print(myList[myList-1]])

4

How many #'s will be printed? for i in range(-2,2): print('#')

4 Range function will run the values from -2, -1, 0, 1

What will be the output of the following code snippet? d = {} d[1] = 1 d['1'] = 2 d[1] += 1 sum = 0 for k in d: sum += d[k] print(sum)

4 Therefore d[1] is a different index than d['1']

What is the expected output of the following code? data = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] for i in range(0, 4): print(data[i].pop(), end=' ')

4 8 12 16

What is INCORRECT about __pycache__? 1. It contains files with extensions ending in .pyc 2. It contains files with extensions ending in .pyo 3. It contains files with complied Python bytecode 4. It is cache for storing variables 5. It is created manually by the user

4. It is cache for storing variables 5. It is created manually by the user The correct answer choices are false statements about __pycache__ while the incorrect choices are facts and should be memorized.

Select the incorrect statement about break instructions 1. It gives instructions to exit the loop immediately 2. It unconditionally ends the loop's operation. 3. The program begins to execute the nearest instruction after the loop's body 4. The program doesn't execute any instruction even if there is any nearest instruction after the loop's body

4. The program doesn't execute any instruction even if there is any nearest instruction after the loop's body

What is INCORRECT about _init_.py file 1. _init_.py is mutable 2. Files names _init_.py are used to mark directories on disk as Python package directories 3. _init_.py allows you to define any variables at the package level 4. _init_.py is automatically created by Python 5. _init_.py contains bytecode that is not human readable

4. _init_.py is automatically created by Python 5. _init_.py contains bytecode that is not human readable The correct answer choices are false statements about __init__.py while the incorrect choices are facts and should be memorized.

How many stars will the following snippet print to the monitor? x = 16 while x > 0: print('*') x //= 2

5

What will be the length of the following list myList = [2 for i in range(3,9)]

6

What is the output of the following snippet of code? a = "refrigerator" print(a.rfind('r', 0, 9))

7 'rfind' is similar to 'find' except that it starts searching for the substring from the right of the target string. BUT even though it is searching from the right, the index it returns is still positive. Just like 'find' it also returns the index of the FIRST match and NOT all matches. The first argument of rfind is the substring to find, the second argument and third argument define the substring from the main string in which we have to find the string provided in first argument. So in this case a.rfind('r', 0, 9) We are looking for the character 'r' from the right in the substring 'refrigera' because 0-9 indexes define it as such.

Which of the following will generate max value? 1. 7//2*4 2. 7%2*4 3. 7/2%4 4. 7/2*4

7/2*4

What base does Octal have and what are they

8 Octal stands for eight. We prefix octal numbers with a zero followed by a lowercase o, like '0o'. The eight digits of octal are 0, 1, 2, 3, 4, 5, 6, 7.

Select the correct output of the following code snippet: print(3 ** 2) print(3 ** 2.) print(3. ** 2) print(3. ** 2.)

9 9.0 9.0 9.0

What is the expected output of the following code? data = [ lambda x: x ** 2, lambda x: x ** 3, lambda x: x ** 4 ] for func in data: print(func(3), end=' ')

9 27 81

The file abc.txt contains the following 3 lines of text: abc def ghi What is the output of the following snippet of code in abc.py file? file = open('abc.txt') print(file)

<_io.TextIOWrapper name='abc.txt' mode = 'r' encoding='cp1252'> The file object will be a generator that reads in file items line by line. Since we are not iterating the generator and simply printing it, the output would be <_io.TextIOWrapper name='abc.txt' mode='r' encoding='cp1252'>

What is the expected output of the following code? print(type(1J)) print(type(2a)) print(type(2J))

<type 'complex'> You can use J or j for complex numbers. 1j is a complex number where the real part is 0 and the imaginary part is 1

What is the output of the following snippet of code? class A: def func(self): return "A" class B: def func(self): return "B" class C(A, B): pass c = C().func() print(c)

A You need to remember this rule that whenever there are more than 2 classes from which a class is inheriting from and both classes contain a function/variable with same name then the class name on the left is given priority and its functions/variables are called so in this case 'A' is first so its function is called.

What happens if you run the following code, assuming that the d directory already exists? import os os.mkdir("a/b/c/d")

A FileExistsError excpetion will be raised

What is the output of the following code: a = 'abcdef' del a print(a)

A NameError will occur because variable 'a' has been deleted and Python can't print it

What is the output of the following snippet of code? a = "television" print(a.index('Vision'))

A Value Error occurs The 'index' function, like the 'find' function starts looking for the substring from the left and returns the index of the first match. BUT unlike the 'find' function, if 'index' function does not find the sub string in the target string, it throws an exception ('find' function returns -1 if sub string not found). Therefore the above code will throw a ValueError because 'Vision' does not exist in 'television'.

Which of the following function definition does not return any value: a. A function that prints integers from 1 to 100 b. A function that returns a random integer from 1 to 100 c. A function that converts an uppercase letter to lowercase

A function that prints integers from 1 to 100

If there is a superclass named A and a subclass named B which one of the presented invocations should you put instead of the comment? class A: def __init__(self): self.a = 1 class B(A): def __init__(self): # Put selected line here. self.b = 2 __init__() A.__init__() (Incorrect) A.__init__(self) (Correct) A.__init__(1)

A._init_(self)

The file abc.txt contains the following 3 lines of text: abc def ghi What is the output of the following snippet of code in abc.py file? file = open('abc.txt', 'w+') file.close() file = open('abc.txt') print(file.read())

An empty string is the output When a file is opened in write mode ('w+'), all previous contents are lost.

What do you call a program which directly executes instructions written in a programming language?

An interpreter In computer science, an interpreter is a computer program that directly executes instructions written in a programming or scripting language, without requiring them previously to have been compiled into a machine language program

What will be the output of the following code tup = (7,14,21) tup.append(28) print(tup)

Attribute Error since you can't append to a tuple

PyPI is often referred to as

Cheese Shop

What is the expected output of the following code? data = 'abcdefg' def func(text): del text[2] return text print(func(data))

Code causes an error can't del

What is the expected output of the following code? data = [[0, 1, 2, 3] for i in range(2)] print(data[2][0])

Code causes an error if the data doesn't exist causes an error

Complete set of commands is known as a

Command List

Name a tool which helps to launch your code step by step and allow you to inspect it at each moment of execution: a. Editor b. Compiler c. Debugger D. Console

Debugger

The concept of public and private variables is depicted by which phenomena of OOP?

Encapsulation In Python, Polymorphism lets us define methods in the child class that have the same name as the methods in the parent class. In inheritance, the child class inherits the methods from the parent class. In this question, there is no child class so both these options are out. Abstraction is the process of hiding the real implementation of a function from the user and emphasizing only on how to use the function. This is also not happening in this question. When a variable name is defined starting with __ (2 underscores), it is a private variable. So it cannot be accessed outside the class. This concept of public and private variables is related to encapsulation. Encapsulation is restricting access to methods and variables based on their requirement. Data hiding is just a term I made up to confuse although it is the essence of encapsulation but it is not the correct option.

The following statement: from x.y import a causes the import of:

Entity a from module y and package x The package name comes first followed by the module name, finally we import the entity required.

What is the expected output of the following code? print('Peter' 'Wellert')

Error

myList = [] yourList=myList[:] yourList.append(7) are these two list lengths the same

False

What is the output of the following snippet of code? class A: pass class B(A): pass class C(B): pass c = C() print(isinstance(C, A))

False The 'isinstance()' function checks if the object (first argument) is an instance or subclass of the class (second argument). Although object c is derived from class C but class C inherits from B which in turn inherits from A, hence c will be considered an instance of A. Consider it like your family tree. You will be considered related to your Great Grand Parents even though you are not directly their child. BUT since isinstance(C, A) question is asking whether class C is an instance of class A, the output would be False

Which of the following is the output of the below Python code? class A: def __init__(self, x=0): self.x = x obj1 = A(2) obj2 = A(2) print(id(obj1) == id(obj2)) str1 = 'Hello' str2 = 'Hello' print(id(str1) == id(str2))

False True An object is mutable and if you create two new objects with the same values they still will be different objects and have different ids. A string is immutable and if you create two strings with the same value they will both point to the same object and therefore have the same ids.

What is the output print (not 'python') print( not None)

False, True

Who created Python?

Guido van Rossum

What is the output of the following snippet of code? class MyException(Exception): def __init__(self, message): super().__init__(message) print("Hello", end=" ") def __str__(self): return "A" try: raise MyException("B") except Exception as e: print(e)

Hello A Explanation When the custom exception, 'MyException' is raised. Its instance is initialized and the '__init__' function is run, printing 'Hello ' on the screen. This exception is then caught in the 'catch' branch because 'MyException' inherits from the 'Exception' class. Then the exception gets printed. Since '__str__' is defined, whatever string this function returns will be printed when the exception is printed. So final output is 'Hello A'.

Name a tool which helps to launch your code step by step and allow you to inspect it at each moment of execution:

Hexadecimal It's a hexadecimal number. The numbers starting with 0x are hexadecimal (base 16). We use the hex() function to convert values to hexadecimal format for display purposes.

What is the output when the file, abc.py, containing the following code is run? if(__name__=='abc'): print("Hello!") elif(__name__=='__main__'): print("Hi!") elif(__name__=='main'): print("Aloha!") else: print("Bye!")

Hi Explanation It is important to remember that when file is run on its own, the '__name__' variable is set to '__main__' but if the file is referenced inside another file and the function is then called inside the second file, only then the '__name__' variable will contain the file name.

What type of programming language is Python

High level Programming Language

What is the output of: print("I am loving\\nPython.") print("I am loving\\Python.")

I am loving\nPython. I am loving\Python. To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert. So in this case \n and \ will be considered in the output.

What is the outcome of the below code print("I", "am", "an", sep="_", end="*") print("Interpreter"m "!.", sep="*", end="*\n")

I_am_an*Interpreter*!.* sep="_" will add _ after each comma-separated value(I_am_an). end="*" will add * towards end (I_am_an*) and will continue in the same line because of end parameter functionality. Next print statement will add * between Interpreter and !.(I_am_an*Interpreter*!.) end="*\n" will add * towards end and move to next line. (I_am_an*Interpreter*!.*)

Why the following snippet of code results in an error? class A: def func(): print("Hello!") a = A() a.func()

If a function inside a class does not have 'self' as one of the arguments, it can only be called by reference of the class

Select the valid variable name from below: 1. import 2. Import 3. float 4. Exchange Rate 5. True

Import

Which of the following is an example of a Python built in concrete exception a. BaseException b.IndexError c. ImportError d. ArithmeticError

IndexError BaseException is the base class for all built-in exceptions what makes it the opposite of a built-in concrete exception.

The fact that B is able to access the function in A in the following snippet of code, depicts what phenomena? class A: def my_func(self): pass class B(A): pass b = B() b.my_func()

Inheritance You might be tempted to choose Object Oriented Programming as the answer but it is not a phenomena but a programming model that comprises of various phenomenon. One of them is inheritance which is clearly depicted in this as class B object inherits the function from class A.

The code and respective output are shown Code: import random as r r.seed(0) for i in range(3): print(r.random()) Output: 0.8444218515250481 0.7579544029403025 0.420571580830845 What is the output when the following code is run on a different machine? import random as r r.seed(0) print(r.random())

Insufficient information provided The seed value ensures that whatever random sequence we get on one machine remains the same when the seed value is same on the SAME machine. In this case we are testing our code on a different machine so output can't be predicted. Also the random function outputs numbers between 0 and 1.

What is the acronym for IDLE

Integrated Development and Learning Environment

What is true about __pycache__?

It contains files with extensions ending in .pyc It contains files with complied Python bytecode The correct answer choices are facts about '__pycache__' . It is good to memorize them. Also pay close attention to the wrong choices as they can be used to confuse you on the real test.

What is true about '__Test' in the following snippet of code? class A: def __init__(self): pass def __Test(self): pass a. It is public and can be used outside the class b. It is a method c. It is a function d. It has an erroneous name e. It is private and cannot be accessed outside the class

It is a method, It is private and cannot be accessed outside the class A method, like a function, is a set of instructions that perform a task. The difference is that a method is associated with an object, while a function is not. '__Test' is a method because its first argument is self, which holds the reference of object which called the method. It should not be called a Function. Since '__Test' method name starts with double underscores, it is a private method and cannot be called outside the class.

What is True about the following snippet of code? class A: def __init__(self, a=1): self.__var = a a = A(5) print(a._A__var) It's output is None It results in an error because there is no such variable in the class It results in error because _var variable is a private variable Its output is 1 Its output is 5

Its output is 5 Although '__var' is a private variable because its name is starting with double underscores and its value CAN'T be accessed by simply calling 'a.__var' BUT it CAN be accessed through this way 'a._A__var'. Here A is the class name. This is true for all private properties of class objects.

What is alternative name for a data structure called a stack

LIFO (Last In First Out)

What cannot be the output of the following snippet of code? (Select 2 Answers) from platform import python_implementation print(python_implementation()) Linux IronPython CPython PyPy 3.8.4

Linux, 3.8.4 The 'python_implementation()' function returns a string identifying the Python implementation. An "implementation" of Python should be taken to mean a program or environment which provides support for the execution of programs written in the Python language.

Where does Python name come from

Monty Python's Flying Circus

What is the output of the following snippet of code? class A: def __init__(self): self.a = 1 def __str__(self): return f"My secret number is {self.a}" class B(A): def __init__(self): self.a = 10 class C(B): def __init__(self): self.a = 100 super().__init__() c = C() print(c)

My secret number is 10 First we create an instance of the class C. This runs the '__init__' method in class C. An instance variable 'a' gets initialized to the value 100. But then the 'super()' function is used to call the super class's constructor (The super() function is used to give access to methods and properties of a parent class). The parent class for C is class B. So its '__init__' method gets called. This changes the value of 'a' of the 'c' object to 10. Next we print the object 'c'. Printing an object causes the '__str__' method to be called. This method is defined in class A. Since value of variable 'a' for object 'c' is 10, therefore, "My secret number is 10" gets printed on the screen.

An integer number preceded by an 0o (Zero-o) will be treated as:

Octal Number having 0o or 0O as prefix represents octal number which can have 0 to 7 as one of the digits in it.

Which of the following statements are true? Select 2 answers a. Opening the file in 'b' mode is valid b. By default, when opening a file, if mode string is not provided (second argument of 'open' function), then file is opened in text mode. c. Opening the file in 'rb' mode, opens it in binary read only mode d. Opening a file with 'a' mode will set the current file position (the virtual reading/writing head) before the first byte of the file. e. Opening a file with 'w' mode will set the current file position (the virtual reading/writing head) after the last byte of file

Opening a file with 'a' mode will set the current file position (the virtual reading/writing head) before the first byte of the file is incorrect because when opening a file in 'a' mode, the current file position (the virtual reading/writing head) is set after the last byte of file. Opening a file with 'w' mode will set the current file position (the virtual reading/writing head) after the last byte of file is incorrect because when opening a file in 'w' mode, the current file position (the virtual reading/writing head) is set to the start of the file and all previous content removed. Opening the file in 'b' mode is valid is incorrect because just specifying that file should be opened in binary mode ('b') is not sufficient, we need to tell whether it is read, write or append etc.

What is true about the output of the following snippet of code? class A: def __init__(self): self.var = 10 pass print(A.__dict__)

Output is a non empty dictionary and does not contain the key var The output is contains metadata about the class like the module info etc. in the form of a dictionary and doesn't contain the key 'var' because 'var' is not a class variable.

Why does this cause an error? try: raise Exception except: print("c") except BaseException: print("a") except Exception: print("b")

Syntax Error because default except has to be last

What is the expected output of the following code? x = True y = False z = False if x or y and z: print('TRUE') else: print('FALSE')

TRUE

What is the output of the following snippet of code? class MyException(Exception): pass try: raise MyException("A") except MyException as e: print(e.args)

The 'args' property is a tuple containing the values passed when the exception is raised.

What is the output of the following snippet of code? class MyException(Exception): pass try: raise Exception("A", "B") except MyException: print("Hello", end=" ") finally: print("Bye")

The code breaks due to unhandled Exception You have to remember that if class hierarchy is like this: A->B (A is SUPER class of B i.e. B is inheriting from A). Then any objects of class B will be considered instances of class A BUT any objects of class A will NOT be considered instances of class B. Using this example we now consider the question. Since we are raising an Exception of type 'Exception' which is the super class of all exceptions, it does NOT get caught by the except branch because except branch will only catch exceptions of type 'MyException' and any exceptions that derive from it. Due to this the exception is unhandled and breaks the code.

What is the expected output of the following code? data = {'a': 1, 'b': 2, 'c': 3} print(data['a', 'b'])

The code causes an error

What is the expected output of the following code? try: if '1' != 1: raise FirstError else: print('FirstError has not occured.') except FirstError: print('FirstError has occured.') else: print('None of the above.')

The code causes an error because FirstError is not a known Python exception if you use your own Python exception you need to inherit from an existing Python exception class

What is the expected output of the following code? num = 1 def func(): num = num + 3 print(num) func() print(num)

The code is erroneous

What is the expected output of the following code? colors = ['red\n', 'yellow\n', 'blue\n'] file = open('wellert.txt', 'w+') file.writelines(colors) file.close() file.seek(0) for line in file: print(line)

The code is erroneous The file gets closed too early. All operations on the file need the be finished before you can close it file.seek(0) is where the Value Error happens

What's the difference between when applied: def func(item): item += [1] def func(item): item.append([1]) data = [1, 2, 3, 4] func(data)

The first one is [1, 2, 3, 4, 1] second one is [1, 2, 3,4, [1]]

What does the method items() return in Python dictionary

The method items() returns the tuples The items() method returns a list of tuples containing the key:value pairs of the dictionary. The first item in each tuple is the key, and the second item is its associated value.

What is true about the following snippet of code? (Select 2 Answers) import random as r print(r.sample([2,3], 2))

The output ca be [3,2] The output is a list The 'sample()' function takes in 2 arguments, the first is the sequence from which we want to draw the random sample and the second argument which specifies how many items we need to draw. The second argument cannot be greater than the length of the sequence otherwise a ValueError occurs, in this case it is not true. This function always returns a list containing the sample even if the second argument is 1. Finally since the output is random we cannot say for sure whether the output will be [2,3] or [3,2].

import random as r print(r.choice([1,2,3])) What can be the output?

The output is an integer and can be 2 The choice() method returns a randomly selected element from the specified sequence. So output cannot be a list. Since the output is random we cannot say for sure whether it will be 3. But we can say that output CAN be 2 or 3 or 1.

What is the expected output of the following code? data = (1,) * 3 data[0] = 2 print(data)

The tuple is immutable. Therefore can't change it so this code has an error

for i in range(1,-1): try: print(1/i, end=' ') except: print("ERROR", end=' ') else: print("SAFE", end=' ') finally: print("DONE", end=' ') What is the output?

There is no output because the loop doesn't run First is that you should be familiar with how 'for' loops work in python and what each value passed to the for loop means. 'for(1,-1)' means that initial value is 1, final value will be -1 and the steps will be of magnitude 1 and in positive direction. Since 1 is already greater than -1, loop statements will not be executed.

The result of the input() function is a string: True or False

True

What is the expected output of the following code? class A: pass class B(A): pass class C(B): pass print(issubclass(C, A))

True

What is the output: myList = [7,12,5,4,27] print(27 in myList)

True

What value will be assigned to the x variable? z = 2 y = 1 x = y < z or z > y and y > z or z < y

True

What value will be assigned to the x variable? z = 3 y = 7 x = y < z and z > y or y > z and z < y

True

What will be the outcome of the following code? x=5 z=10 y=3 x=z>x or z==y print(x)

True Lets evaluate the value of x: x=z>x or z==y z>x will give True as 10>5 z==y will give False as z is 10 and y is 3 Hence x=z>x or z==y will be evaluated as x= True or False hence it will print True.

What is the output of the following snippet of code? class A: pass class B: pass class C(B): pass c = C() print(isinstance(c, (B,A)))

True The 'isinstance' function checks whether the object specified in first argument is an instance of the class or tuple of classes specified in the second argument. For the case when a tuple of classes is provided, the check is an 'OR' relation NOT an 'AND' relation. So in the above scenario, the 'isinstance' function call can be translated like this: isinstance(c, B) or instance(c, A) So even though object 'c' is not an instance of class A, the output will be True because the left side of the OR statement is TRUE.

What is the output of the following snippet of code? class A: pass class B: pass class C(B): pass c = C() print(isinstance(c, (B,A)))

True The 'isinstance' function checks whether the object specified in first argument is an instance of the class or tuple of classes specified in the second argument. For the case when a tuple of classes is provided, the check is an 'OR' relation NOT an 'AND' relation. So in the above scenario, the 'isinstance' function call can be translated like this: isinstance(c, B) or instance(c, A) So even though object 'c' is not an instance of class A, the output will be True because the left side of the OR statement is TRUE.

What is the expected output of the following code? class A: def __init__(self, x=2, y=3): self.x = x self.y = y def __str__(self): return 'A' def __eq__(self, other): return self.x * self.y == other.x * other.y a = A(1, 2) b = A(2, 1) print(a == b)

True This question is about operator overloading. __eq__() overloads the equal to operator if used with objects of the class A If you use the equal to operator with two object of the class A the __eq__() method is called and the two objects are passed to it. The return value is going to be the result of the comparison. And because 1 * 2 == 2 * 1 the result is True

What is the output of the following code snipped print(True > False) print(True < False)

True False True =1 False = 0

The output of the following code will be an empty list: True or False

True If some slicing expressions are made that do not make sense or are incomputable then empty lists are generated. If you move from left to right from index -1 then you will not find anything hence it will return empty list.

Is a tuple an immutable sequence type in Python? True or False

True Meaning can't add or delete its elements

Which of the following is a correct statement True + 1 evaluates to 2 True and False evaluates to False True or False evaluates to False 7 + False evaluates to False

True + 1 evaluates to 2 True and False evaluates to False Value of True is 1

What is the expected output of the following code? class A: A = 7 def __init__(self): self.a = 0 print(hasattr(A, 'A'))

True because A is the class varibale

What is the output print (not 0) print( not 7) print (not '')

True, False, True

Which of the following is not a tuple type Tup=(4) Tup=(4,) Tup = () Tup = 1,

Tup = (4) This becomes an int

Select the incorrect statement about variable naming in Python: 1. Uppercase and lowercase letters are treated as different 2. Upper and lowercase letters are treated as the same 3. Variable names may contain letters, digits (0-9), or the underscore character _ 4. The name of the variable must not be any of the Python's reserved words

Upper and lowercase letters are treated as the same

What is the output of the following snippet of code? print(int("abc"))

ValueError occurs

If a list passed into function's argument and modified inside the function 1. Will affect the argument 2. Will not affect the argument 3. Will give an error 4. Will become global by default

Will affect the argument In Python, data types can be either mutable (changeable) or immutable (unchangeable). And while most of the data types we've worked with in introductory Python are immutable (including integers, floats, strings, Booleans, and tuples), lists and dictionaries are mutable. That means a global list or dictionary can be changed even when it's used inside of a function

Which snippet of code will produce the following output: * ** *** **** *****

ZeroDivisionError

What is the expected output of the following code? with open('data.txt', 'w') as f: f.write("I'm gonna make him an offer he can't refuse.") with open('data.txt', 'r') as f: data = f.readlines() for line in data: words = line.split() print(words)

["I'm", 'gonna', 'make', 'him', 'an', 'offer', 'he', "can't", 'refuse.']

What is the output of the following snippet of code? a = "ab cd,ef" print(a.split(','))

['ab cd', 'ef']

print(list('hello'))

['h', 'e', 'l', 'l', 'o']

What is the expected output of the following code? import os os.mkdir('thumbnails') os.chdir('thumbnails') sizes = ['small', 'medium', 'large'] for size in sizes: os.mkdir(size) print(os.listdir())

['large', 'medium', 'small']

What is the output of the following snippet of code? a = [1,2,3,4,5,6,7,8,9] b = [i if i%3==0 else 0 for i in a] print(b)

[0,0,3,0,0,6,0,0,9] Explanation For list comprehension questions always tackle the problem from right to left. On the right we can see that we are iterating through the list 'a'. On the left, we check whether the value is divisible by 3 (If remainder is 0 when dividing by 3 then the number is divisible by 3). If the number is divisible by 3, we keep the number otherwise we get 0. Therefore the list 'b' contains numbers from list 'a' which are divisible by 3, the rest of the numbers are replaced by 0.

What is the output of the following snippet of code? a = [4,2,7,1] a.sort() print(a)

[1,2,4,7] The 'sort()' extension method (fancy name for function which is called using the dot '.' notation), sorts the items in a list. This function does NOT apply on strings. And it sorts the list INPLACE. Which means the function does NOT return a new list but works on the original list. Therefore we don't need to assign the output back to the variable.

What is the expected output of the following code? a = [1, 2, 3, 4, 5] print(a[3:0:-1])

[4, 3, 2]

What is the expected output of the following code? list1 = [1, 3] list2 = list1 list1[0] = 4 print(list2)

[4, 3]

What is the following output: newList = [] for n in range(4): newList.insert(0, n+1) print(newList)

[4,3,2,1]

What is the expected output of the following code? w = [7, 3, 23, 42] x = w[1:] y = w[1:] z = w y[0] = 10 z[1] = 20 print(w)

[7, 20, 23, 42]

myList = [17, 7, 5, 3, 4] yourList = myList [1:-1] print yourList

[7, 5, 3]

What is the following output: myList = [5,7,4,9,6] print(myList[-4:-1])

[7,4,9]

myList = [7] yourList = myList[:] myList[0] = 5 print(yourList)

[7]

Which snippet of code will produce the following output: * ** *** **** *****

[print('*' * i) for i in range(1,6)]

Which slash is an escape character

\ back slash

If the following piece of code resides in the abc.py file what is the output while the file is run? class A: pass print(A._module_) 1. None 2. A 3. abc 4. _main_ 5.main

_main_ The '__module__' property holds the name of the module, the function/class was defined in. When a file is run on its own in python, the module is set to '__main__' but if the class had been referenced inside another file and then the code had been run, the output would have been 'abc'.

The folder created by Python used to store pyc files is named

_pyache_

def func(a): print(a) func()

a Type Error occurs AttributeError can be defined as an error that is raised when an attribute reference or assignment fails. Here none of that is happening. One handy way of deciding between value error and type error is by understanding that value error occurs when there is a problem with the content of the object you tried to assign the value to for example the statement int("a") produces a ValueError because the value being provided to int is of the wrong type (Don't associate with TypeError). Now the 'type' of the 'func' function in the question is such that it REQUIRES a value. It is the TYPE (read nature) of this function that it must need a value to work and if we call it simply like func() it violates its nature. Hence a TypeError occurs.

Select the two statements about the map() function: a. The map() function can only accept more than two arguments b. The second map() function argument can be a list c. The first map() function argument can be a list d. The map() function can accept only two arguments

a and b

Select the correct statements about 'None' in Python a. None is a keyword b. None can be assigned to a variable. c. None can be used to compare it with a variable d. None is not a keyword

a. None is a keyword b. None can be assigned to a variable. c. None can be used to compare it with a variable

Select two true statements a. The lambda function can evaluate only one expressions b. the lambda function can accept a max of two arguments c. The lambda function can evaluate mutiple expressions d. The lambda function can accept any number of arguments

a. The lambda function can evaluate only one expressions d. The lambda function can accept any number of arguments

Which of the following statements are true regarding the opening modes of a file? Choose three a. When you open a file for writing, if the file exists the existing file is overwritten with the new file b. When you open a file for reading, if the file does not exist, an error occurs c. When you open a file for reading, if the file does not exist, the program will open an empty file d. When you open a file for writing, if the file does not exist, an error occurs e. When you open a file for writing, if the files does not exist, a new file is created.

a. When you open a file for writing, if the file exists the existing file is overwritten with the new file b. When you open a file for reading, if the file does not exist, an error occurs e. When you open a file for writing, if the files does not exist, a new file is created. If you want to read from a file, the file needs to exist. If you want to write to a file, the file does not have to exist. It will be created, if it does not exist. If the file already exists, it will be overwritten. If you do not want to loose the old content of the file, you can use the append mode: open('myfile.txt', 'a') That will append the new content at the end of the file.

What is False about the assert keyword? Select 2 answers a. assert stops program execution if unhandled when the condition with it is True b. The assert keyword is used when debugging code c. assert stoops program execution of unhandled when the condition with it is False d. assert is an alternative to try/except block e. assert can cause an AssertionError

a. assert stops program execution if unhandled when the condition with it is True d. assert is an alternative to try/except block

UNICODE is a standard: a. like ASCII but much more expansive b. used by coders from universities c. honored by the whole universe d. for coding floating point numbers

a. like ASCII but much more expansive

Which of the following code snippets will print True to the monitor? a. print('is' in "This IS Python code.') b. x=42 y=42 print(x is not y) c. x = "Peter Wellert" y = "Peter Wellert".lower() print (x is y) d. x = ['Peter', 'Paul', 'Mary'] y= ['Peter', 'Paul', 'Mary'] print (x is y) e. print('t' in 'Peter')

a. print('is' in "This IS Python code.') e. print('t' in 'Peter') The membership operator works very good with strings. It looks for a string in a string. The identity operator with immutable data types (here int and string): The 42 in x and y will reference to the same object. Therefore they have the same identity and the not identity operator will evaluate to False One string will be changed by lower() to peter wellert and therefore they will not have the same identity. The identity operator with mutable data types (here list): A new list will be a new object even if the values are the same. Therefore they will not have the same identity. But they will have the same values, which you can check with the equal to operator

What is the output of the following code snippet? a = "abcdef" a = a[0:2] print(a)

ab When we get the substring using the slice notation (string[start: end: step]), we get a NEW string, we are NOT modifying the original string. When we assign this new string to variable 'a' we are essentially replacing the reference of old string with new string. None of these operations are violating the immutability rule for strings so options 1 and 5 are out. When slicing a string, the end value of index is not included in the sub string so the items corresponding to index 0 and 1 get included in the output, therefore the output is 'ab'. The default value of step is 1.

What is the output of the following snippet of code? a = "abc" for i in a: i = 'x' print(a)

abc When we are iterating through the string, the variable 'i' gets assigned the value of a character in the string. We can modify the value of 'i' BUT by doing this we are NOT modifying the actual string therefore no error occurs nor does the value of the string gets changed, it remains 'abc'.

What is the output of the following snippet of code? a = "abcdef" b = a[:-2:2] print(b)

ac The substring specified has a starting value unspecified so it defaults at 0 index which is character 'a'. The end value is -2 which is the character 'e'. The step is positive 2. So first character in substring would be 'a', second character will be 2 index jumps after 'a' so it will be 'c'. Next when we try to jump by 2 indexes we reach the character 'e' (index = -2). Since this cannot be included in the substring because it was specified to be the end index value, we stop here. Final output is therefore 'ac'.

What is the expected output of the following code? def func(data): for d in data[::2]: yield d for x in func('abcdef'): print(x, end='')

ace The Yield keyword in Python is similar to a return statement used for returning values or objects in Python. However, there is a slight difference. The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value. Inside a program, when you call a function that has a yield statement, as soon as a yield is encountered, the execution of the function stops and returns an object of the generator to the function caller. In simpler words, the yield keyword will convert an expression that is specified along with it to a generator object and return it to the caller. Hence, if you want to get the values stored inside the generator object, you need to iterate over it.

When a module is imported, its contents:

are executed once

By which variable of the sys module can we access command line arguments?

argv

Which of the following variable names illegal? a. in_ b. in c. IN d. In

b , in

What is the correct way to instantiate an object of the following class? class B: def __init__(self, a): self.a = a

b = B(1) The first argument of every class method, including '__init__'(constructor), is always a reference to the current instance of the class. By convention, this argument is always named self . In the init method, self refers to the newly created object; in other class methods, it refers to the instance (object) whose method was called. Therefore when creating an object of the above class, we need to pass in only 1 value, which is for 'a'. Hence b = B(1) is correct.

Which of the following is an INCORRECT way to check whether a substring "ram" exists inside the string "program". (Select 2 Answers) a. 'program'.find('ram') != -1 b. 'ram' inside 'program' c. 'ram' in 'program' d.'program'.rfind('ram') != -1 e.'program'.contains('ram')

b. 'ram' inside 'program' e.'program'.contains('ram')

Consider the following code. import random data = [10, 20, 30] random.shuffle(data) print(data) Which of the following statements best describes the behavior of the random.shuffle() method? a. It will not modify the list. The function is a placeholder and yet to be implemented b. It shuffles the elements of the list in-place c. It returns a list where the elements 10, 20, and 30 would be at random positions d. it shuffles the elements for the number of times equal to the size of the list

b. It shuffles the elements of the list in-place The original list gets shuffled in-place. The return value is None

Select the true statements about the filter() function Choose two: a. The filter() function has the following syntax: filter(iterable, function) b. The filter() function has the following syntax: filter( function, iterable) c. The filter() function returns an iterator d. The filter() function does not return an iterator

b. The filter() function has the following syntax: filter( function, iterable) c. The filter() function returns an iterator The filter() function returns a filter object, which is an iterator.

Which of the following is a true statement? a. UTF-8 is a standard b. Unicode is a standard c. Unicode is an encoding d. UTF-8 is an encoding e. UTF-8 is the only encoding part from ASCII

b. Unicode is a standard d. UTF-8 is an encoding

What is the expected output of the following code? def func(x): try: x = x / x except: print('a', end='') else: print('b', end='') finally: print('c', end='') func(1) func(0)

bcac

Which of the following is false? a. A try statement can have a finally clause and an except clause b. A try statement can have a finally clause without an except clause c. A try statement can have one or more finally clauses d. A try statement can have one or more except clauses

c. A try statement can have one or more finally clauses

Which of the following is incorrect about UTF-8 and ASCII (select 2 answers) a. ASCII came before UTF-8 b. Each character is represented by a code point in UTF-8 c. UTF-8 came before ASCII d. UTF-8 is a variable-width character encoding used for electronic communication e. ASCII is only used in America

c. UTF-8 came before ASCII, e. ASCII is only used in America The correct answer choices are false statements about UTF-8 and ASCII while the incorrect choices are facts and should be memorized.

Which of the following statements is True? Select 2 Answers a. ord('A') > ord('a') b. ord('c') - ord('a') ==3 c. ord('c') - ord('a') ==2 d. len(chr(80)) == 2 e. ord('a') > ord('A')

c. ord('c') - ord('a') ==2 e. ord('a') > ord('A') The 'ord()' function in Python accepts a string of length 1 as an argument and returns the Unicode code point representation of the passed argument, which is an integer. The 2 facts that you must be familiar with to answer this question correctly are that the code point integer values for uppercase letters are always smaller than those for lower case letters. Second fact is that for consecutive alphabets, the code point value differs by 1. Using these facts you can see that ord('a') > ord('A') & ord('c') - ord('a') == 2 are correct while rest are incorrect. ord('c') - ord('a') == 3 is incorrect because 'c' is the 2nd character after 'a'. len(chr(80)) == 2 is incorrect because the 'chr()' function is the opposite of the 'ord()' function. It takes in a code point value and outputs the character representation of it. Since a character is of length 1, therefore this option is incorrect.

A keyword is a word that

cannot be used as a variable

Given the following classes class A: pass class B(A): pass class C(B): pass class D(A): pass Which is incorrect? a. class a1(C,D) b. class a1(B,A) c. class a1(A,B) d. class a1(D,C) e. class a1(B,C)

class a3(A, B), class a4 (B,C) To solve this question you need to be aware of the rule that when declaring a sub class which inherits from 2 (or more) classes which themselves are related through inheritance, the super class (class higher up in the inheritance hierarchy) needs to be passed after the sub class (class lower in the inheritance hierarchy)

What is the expected output of the following code? class A: def __init__(self): pass def func1(self): return 1 def func2(): return self.func1() x = A() print(x.func2())

code causes an error because fun2 should have self as a parameter

What is the expected output of the following code? class A: def __init__(self, x): self.__a = x + 1 a = A(0) print(a.__a)

code will raise an attribute error

The pyc file contains

complied Python code

What is the expected output of the following code? def increment(c, num): c.count += 1 num += 1 class Counter: def __init__(self): self.count = 0 counter = Counter() number = 0 for i in range(0, 100): increment(counter, number) print( "counter is " + str(counter.count) + ", number of times is " + str(number) )

counter is 100, number of times is 0 This question is about argument passing. It is a big difference, whether you pass a mutable or an immutable data type. When you pass the immutable integer, it gets copied to the parameter num The changes of num do not influence the variable number On the other hand when you pass the mutable object, it gets referenced to to parameter c c and counter point to the same object. You change one and the other is changed, too.

What is the expected output of the following code? class A: def __init__(self): self.i = 0 self.calc(10) print('i from A is', self.i) def calc(self, i): self.i = 2 * i class B(A): def __init__(self): super().__init__() def calc(self, i): self.i = 3 * i b = B() a. i from A is 20 b. i from A is 0 c. i from B is 30 d. i from A is 30

d. i from A is 30 When b is instantiated as an object of class B its constructor calls the constructor of its parent class A The classes A and B both have a method named calc() therefore the method in A gets overridden by the method in B Now the constructor in A (which is called from out of B) will instantiate the object variable i Then it will call the calc() method and pass 10 as a value. Because we are in B, the calc() method of B is called. The passed value will be multiplied by 3 and stored in b.i 10 * 3 -> 30 And in the end the print() function will print: i from A is 30

You want to write a code snippet to read the total data from a text file and print it to the monitor. What snippet would you insert in the line indicated below: try: file = open('data.txt', 'r') # insert your code here print(data) except: print('Something went wrong!')

data = file.read()

What is the output of the following snippet of code? a = "abcdef" b = a[3:10] print(b)

def

Which of the following is not a python version? a. CPython b. Cython c. Jython d. PyPy e. Zython

e. Zython CPython is the original Python implementation Cython is a compiler that enables to write C extensions for Python Jython is for Java PyPy is reimplementation of Python in Python using the RPython translation toolchain

Which of the following statements are true (Select 2 answers) a. errno.ENOSPC constant refers to no space on disk error b. errno.EEXIST constant refers to error when we try to open a file that doesn't exist c. errno.EACCES constant refers to permission error d. errno.EFBIG constant refers to large font error in file e. errno.ENOENT constant refers to large file erro

errno.EACCES constant refers to permission error is asking about errno.EACCES, which clearly shows that it must be related to some 'access' issues. Same is case for errno.ENOSPC constant refers to no space on disk error which is referring to No space on disk issue, it is in the name: errno.ENOSPC.

You want to write a new player to a file and print the whole file content to the monitor. What snippet would you insert in the line indicated below: customer = 'Peter Wellert' with open('customers.txt', 'a+') as f: f.write(customer) # insert your code here data = f.read() print(data)

f.seek(0)

Which of the following commands can be used to read n characters from a file? a. n=file.readline() b. n=file.read() c. file.read(n) d. file.readline(n)

file.read(n) The read() method has one optional parameter. If it is given, that number of characters are read. If it is not given, the whole file is read. file.readline([size]) The readline() method has also one optional parameter to specify the number of characters to be read. But it would only read that number of characters from the first line. If you want to read more characters, only the read() method will work.

Both file1.py and file2.py are in the same directory. Content of file1.py is print(_name_) and content of file2.py is import file1 What is the output when file2.py is ran

file1 The '__name__' variable gets its value depending on how we execute the containing script. Since it is contained inside the file1.py which is referenced inside file2.py, the output is 'file1'. If we had simply run file1.py then the output would have been '__main__'.

Both file1.py and file2.py are in the same directory. Content of file1.py is: print(__name__) Content of file2.py is:import file1 What is the output when file2.py is run followed by file1.py?

file1 _main_ The '__name__' variable gets its value depending on how we execute the containing script. Since it is contained inside the file1.py which is referenced inside file2.py, the output is 'file1'. When we run file1.py then the output would be '__main__'.

Which of the following is the correct way to open a file in read mode?

file=open('abc.txt', 'r') file=open('abc.txt') The second argument in the 'open' function specifies what mode to open the file in. It is by default 'r' i.e. read only hence options file = open('abc.txt', 'r') and file = open('abc.txt') are correct.

What is present in the function header?

function name and parameter list

Given the following snippet of code: class A: var = 1 def __init__(self): self.x = 1 a = A() Which of the following evaluates to False? (Select 2 Answers)

hasattr(a, 'self') hasattr(A, 'x') hasattr(A, 'x') is False because 'x' is an instance variable and belongs to the object of the class and not an attribute of the class itself. hasattr(a, 'x') is True because x is an instance variable of object a. hasattr(A, 'var') is True because 'var' is a class variable. hasattr(a, 'self') is False because 'self' is not an attribute but is a reference. hasattr(A, '__init__') is True because __init__ has been defined inside the class A

What is the expected output of the following code? class A: def __init__(self): self.calc(10) def calc(self, i): self.i = 3 * i class B(A): def __init__(self): super().__init__() print('i from B is', self.i) def calc(self, i): self.i = 2 * i b = B()

i from B is 20

Which program will produce the following output: Mo Tu We Th Fr Sa Su

import calendar print(calendar.weekheader(2))

I have a piece of code that works differently on Windows and Linux. What is the correct way to write it?

import platform as p if (p.system() == 'Windows'): ## Do something elif (p.system() == 'Linux'): ## Do something Or import platform as p if ('Windows' in p.platform()): ## DO something elif('Linux' in p.platform()): ## Do Something 'platform.machine()' function returns the machine type, e.g. 'i386'. Since we need information about the operating system. 'platform.platform()' function does contain information about the operating system BUT it has more information in it as well like the operating system version etc. (e.g. Windows-10-10.0.17763-SP0). Since we are using the equality operator to check whether this is equal to 'Windows' or 'Linux', we will always get False and it is because of this we need to use the IN operator to check whether the sub string 'Windows' or 'Linux' occur in this

You have the following file index.py: from sys import argv print(argv[0]) You run the file by executing the following command in the terminal. python index.py Hello What is the expected output?

index.py Explanation: You have to open the folder where you created the index.py file in a terminal and run the file by executing python index.py Hello The first index (the index 0) of the argv variable is always the filename. If you want Hello to be the output, you have to write print(argv[1])

What are the datatypes of each element in this list: data = [1, {}, (2,), (), {3}, [4, 5]]

integer, dictionary, tuple, tuple, set, list

How to check if a class is a subclass of another

issubclass()

What keyword would you use to define an anonymous function?

lambda

isalnum() checks if a string contains only letters and digits and this is: function, method, module

method

What is the expected output of the following code? import os os.mkdir('pictures') os.chdir('pictures') os.mkdir('thumbnails') os.chdir('thumbnails') os.mkdir('tmp') os.chdir('../') print(os.getcwd())

mkdir = make directory chdir = change into directory get_cwd= get current working directory the last line before os.getcwd() the code is returning to the parent directory which is pictures so its the path to the pictures directory

You know that a function named func() resides in a module named mod The module has been imported using the following line: import mod How can you invoke the function? a.mod.func() b. func() c. mod::func() d. mod ->func()

mod.func()

A function definition: 1. must be placed before the first invocation 2. must be placed after the first invocation. 3. can be placed anywhere in the code. 4. Has to be defined separately, not among other code

must be placed before the first invocation

If your List named myList contains 400 items when will you get the IndexError while accessing the list items 1.myList[-1] 2. myList[400] 3. myList[0] 4. myList[-2]

myList[400]

What are three words in which an object is characterized:

name, properties, activities

The 0o prefix means that the number after it is denoted as:

octal

The meaning of the positional parameter is determined by its:

position

Which of the following print command is correct in order to print the sum of two input numbers: x=input("Enter 1st number:") y=input(Enter 2nd number:"0

print(' the sum is: ' + str(int(x) + int(y)))

Where does the word pip came from?

python installs packages

What are the different modes of opening a txt file in Python

r: The r mode is used when we want to open the file for reading. The file pointer in this mode is placed at the starting point of the file. r+: The r+ mode is used to open a file for both reading and writing. Just like in the previous mode, the file pointer in this mode is placed at the starting point of the file as well. w: The w mode is used to open a file for the purpose of writing only. If the file already exists, it truncates the file to zero length and otherwise creates a new file if it doesn't exist yet. w+: The w+ mode opens the file for reading and writing. If the file already exists, it is truncated, and otherwise, a new file is created if it doesn't exist. The file pointer in this mode is placed at the starting point of the file. a: The a mode opens the file for the purpose of appending. The file pointer in this mode is placed at the end of the file if it already exists in the system. If the file does not exist, then it is created for writing. a+: The a+ mode opens the file for both reading and appending. The file pointer in this mode is placed at the end of the file if it already exists in the system. The file opens in the append mode. If the file does not exist, then it is created for writing. x: The x mode opens the file for exclusive creation, failing if the file with that name is already existent. When exclusive creation is specified, it means that this mode will not create a file if the file with the specified name already exists. In the x mode, the file is only writeable, but in x+ mode, the file is opened as both readable and writeable.

When an exception occurs we say that it has been

raised

What is the correct command to shuffle the following list? import random people = ['Peter', 'Paul', 'Mary', 'Jane']

random.shuffle(people)

Which module in Python supports regular expressions a. re b. regex c. pyregex d. None of the above

re

Assuming that the open() invocation has gone successfully, the following snippet will: for x in open('file', 'rt'): print(x)

read the file line by line

What describes res data = [4, 2, 3, 2, 1] res = data[0] for d in data: if d < res: res = d print(res)

res is the smallest number in the list

The operator // in python does what

returns the integral part of the quotient This is called floor division in python. The floor-function provides the lower-bound of an integral division. It divides it, and then makes it the integer below. To provide this behavior, integer division rounds towards negative infinity, rather than towards zero.

A list of package's dependencies can be obtained from pip using its command named

show

What is the correct way to sort the string "xrza"?

sorted('xrza') "xrza".sort() is incorrect because the 'sort()' extension method does not apply to strings. It only applies to lists. sort("xrza") is incorrect because there is not such function 'sort' sorted("xrza") is correct, the 'sorted' function returns a sorted list of the specified iterable object. You can specify ascending or descending order. "xrza".sorted() is incorrect because 'sorted()' is NOT an extension method i.e. it cannot be called using the dot notation (it is not the property of the object, it exists independently). ascending("xrza") is incorrect because there is no such function.

Select the correct sequence of literals in the following example: "5.2", 3.2, False, 32

string, float, boolean, integer

Which of sys function terminates a program

sys.exit()

What is the output of the following code for t1 and t2: tup = (7,14,21) t1 = tup + (28, ) t2 = tup * 3

t1 = (7,14,21,28) t2 = (7,14,21,7,14,21,7,14,21) A tuple is an ordered collection of values. Tuples are immutable - you can't add, delete, or change items after the tuple is defined. But you can make a tuple using another tuple. t1 will create new tuple by using tup and another value 28. similarly t2*3 will create a triple by having tup values 3 times.

The diagraph written as '#!' is used to

tell a Unix or Unix like OS how to execute the contents of a Python file

How many stars will the following code send to the monitor? x = 0 while x < 6: x += 1 if x % 2 == 0: continue print('*')

three Explanation: When x is 2, 4 and 6 the if condition is True and the continue gets triggered. The iteration ends directly and the print() function doesn't get executed. When x is 1, 3 and 5 the if condition is False the continue does not get triggered and those three times the print() function gets executed. Therefore there will be three stars printed.

def func(x): global y y = x * x func(2) print(y) def func(x): y = x * x return y func(2) print(y)

with global the y is assigned without needing a return inside and outside a function so the output is 4 the second one the y is defined in the function but not out therefore it causes an error

Consider the below variable declarations x = '5' y = '7' Which of the following are of type 'str' x+y x-y x*2 x*y

x + y x * 2

Are keys case-sensitive in a python dictionary

yes. Dictionary keys are case sensitive- Same key name but with the different cases are treated as different keys in Python dictionaries.

Assuming that all three files x.py, y.py, and z.py reside in the same folder, what will be the output produced by running the z.py file?x.py: print('x', end='') y.py: import x print('y', end='') z.py: print('z', end='') import x import y

zxy

What is the output of the following snippet of code? class A: var = 100 def __init__(self): pass a = A() print(a.__dict__)

{} Every object in python has an attribute which is denoted by '__dict__'. And this object contains all attributes defined FOR the object. Since var has not been defined with the self keyword, it is a CLASS variable and will be shared by ALL objects of class A. Due to this it will not appear in the 'dict' property of object a. 'var' will be present in the 'dict' property of class A. So output for above code will be an empty dictionary.

What are some characteristics about the variable 'var' in the following class? (Select 2 Answers) class A: var = 10 def __init__(self): pass

'var' will have the same value in all objects of class A 'var' is a class variable Any variable defined in a class WITHOUT the self keyword, is a class variable and will be shared throughout all instances (objects) of the class.

What is the output of the following snippet of code? class A: pass class B(A): pass class C(B): pass print(C.__bases__) ​

(<class '__main__.B'>,) You have to remember that the '__bases__' property holds the information about the immediate super class of the class. It is not aware of any other hierarchy. Also, it contains the super classes in a tuple and NOT a list.

What is the output of the following snippet of code: a = "television" print(a.find('Vision'))

-1 The 'find' function finds the exact match of substring in the main string, since the main string contains 'vision' but NOT 'Vision', it will return -1. This is important to remember about find that when it doesn't find a match, it returns -1. This -1 should not be confused with the index -1.

What is the output of the following snippet of code? a = "engineer" print(a.rfind('e',0,-3))

0 This is a really tricky one. You need to remember that 'find' and 'rfind' take in 3 arguments. The first argument is the substring to look for in target string and the 2nd and 3rd arguments (both optional) specify the slice of target string to look in for the substring entered in first argument. So in above question when we say: a.rfind('e',0,-3) , we are looking for the character 'e' in the slice of 'engineer' starting from index 0 and ending on (but not including) the index -3. This slice becomes 'engin' and when searching from the right the first 'e' is encountered at the 0th index therefore the answer is 0.

What is the content of the file xyz.txt after the following code is run? file = open('xyz.txt', 'w') a = [1,2,3,4,5] for i in a: file.write(str(i))

1,2,3,4,5

What is the output of the following snippet of code? def A(a): b = a**3 def B(): return b+2 return B x = A(2) print(x())

10 When function A is initialized, the value of b inside function B gets set to 2**3 = 8 (2 to the power of 3) and the function B get returned. When this gets called through x, output is 8+2 = 10. The function B 'remembers' the value of b that was set, this is a feature of closures.

What is the output of the following snippet code: a = "refrigerator" print(a.rfind('r'))

11 'rfind' is similar to 'find' except that it starts searching for the substring from the right of the target string. BUT even though it is searching from the right, the index it returns is still positive. Just like 'find' it also returns the index of the FIRST match and NOT all matches.

What is the output of the following code snippet? print(chr(70)))(Select 2 Answers) 1. An error will occur 2. The output will be a string 3. The output will be an integer 4. The output will have a length of 1 5. The output is '70'

2. The output will be a string 4. The output will have a length of 1 The 'chr' function converts a code point value (integer) to its respective character string.

What is the output of the following snippet of code? class MyException(Exception): def __init__(self, message): super().__init__(message) print("Hello", end=" ") def __str__(self): return "A" try: raise MyException("B") except Exception as e: print(e) ​

Hello A When the custom exception, 'MyException' is raised. Its instance is initialized and the '__init__' function is run, printing 'Hello ' on the screen. This exception is then caught in the 'catch' branch because 'MyException' inherits from the 'Exception' class. Then the exception gets printed. Since '__str__' is defined, whatever string this function returns will be printed when the exception is printed. So final output is 'Hello A'.

What is true about the output of the following snippet of code? class A: pass print(A.__dict__)

Output is a non empty dictionary Even though it seems that the class is empty and therefore its '__dict__' property should return an empty dictionary BUT this is not the case. It contains metadata about the class like the module info etc.

What is the output of the following snippet of code? from platform import python_implementation print(python_implementation())

Possible outputs are CPython, IronPython, PyPy The 'python_implementation()' function returns a string identifying the Python implementation. An "implementation" of Python should be taken to mean a program or environment which provides support for the execution of programs written in the Python language.

What is true about the following snippet of code? import random as r print(r.choice([1,2,3]))

The output can be 2 and is an integer The choice() method returns a randomly selected element from the specified sequence. So output cannot be a list. Since the output is random we cannot say for sure whether it will be 3. But we can say that output CAN be 2 or 3 or 1.

Which of the following statements are correct about the sys.path variable? (Select 2 Answers) The sys.path variable is a list of strings The sys.path variable is mutable The sys.path variable can be accessed without importing any module The sys.path variable is a dictionary of paths which python uses to look for modules The sys.path variable cannot be modified

The sys.path variable is a list of strings The sys.path variable is mutable The correct answer choices are facts about 'sys.path' variable. It is good to memorize them. Also pay close attention to the wrong choices as they can be used to confuse you on the real test

What is the output of the following snippet of code? class A: pass class B(A): pass class C(B): pass c = C() print(isinstance(c, A))

True The 'isinstance()' function checks if the object (first argument) is an instance or subclass of the class (second argument). Although object c is derived from class C but class C inherits from B which in turn inherits from A, hence c will be considered an instance of A. Consider it like your family tree. You will be considered related to your Great Grand Parents even though you are not directly their child.

The file abc.txt contains the following 3 lines of text: abc def ghi What is the output of the following snippet of code in abc.py file? file = open('abc.txt') a = [i for i in file] print(a)

['abc\n', 'def\n', 'ghi] The file object will be a generator that reads in file items line by line. So when we use it in list comprehension we get a list containing lines in the file. Since there are 3 lines, the first 2 lines will also have the '\n' character which specifies new line (although '\n' is not visible in the text file it represents next line).

The file abc.txt contains the following 3 lines of text: abc def ghi What is the output of the following snippet of code in the abc.py file? file = open('abc.txt') for i in file.read(): print(i) break

a The 'read()' function reads the contents of the file, 1 byte at a time. So when we iterate through its output and 'break' the loop after first iteration, only the first character (first byte) of file gets printed on screen which is 'a'.

Which of the following evaluates to True? Select 2 answers a. 'Abcdefghijkl' > 'a' b. 'abc' != 'aBc'.lower() c. 'aBC' > 'Abc' d. 'xyz' > 'xyz'.capitalize() e. 'abc'.upper() == 'abc

c. 'aBC' > 'Abc' d. 'xyz' > 'xyz'.capitalize() Strings in python are compared character by character from left to right and whenever a lower codepoint is encountered, the string with the higher code point value is declared greater. 'abc'!='aBc'.lower() is incorrect because all code points are equal from left to right because when the 'lower()' function gets applied to the string on the right, the string becomes 'abc' which is equal to string on the left. 'abc'.upper() == 'abc' is incorrect because when the 'upper()' function gets applied to the string on the left, it becomes, 'ABC', which is not equal to string on the right. 'aBC' > 'Abc' is correct because when comparing from left to right, the first character encountered is 'a' for the left string and 'A' for the string on the right. Since the code point value of lower case letters is greater than for upper case ones, the string on the left is declared greater, regardless of what comes afterwards. 'Abcdefghijkl' > 'a' is incorrect because of the same reason as for third option. Since string on the right has lower case 'a' as first character while left string has upper case 'A'. The string on the right is considered greater regardless of how long string on left is. 'xyz' > 'xyz'.capitalize() is correct because the 'capitalize()' function makes the first character into upper case and the rest of the characters lower case. When applied to the string on right, it becomes, 'Xyz'. Since string on left starts with lower case 'x' it is declared the greater one.

Which of the following are correct declarations of sub classes? class A: pass class B(A): pass class C(B): pass class D(A): pass

class a1 (C,D): class a2(D,C): To solve this question you need to be aware of the rule that when declaring a sub class which inherits from 2 (or more) classes which themselves are related through inheritance, the super class (class higher up in the inheritance hierarchy) needs to be passed after the sub class (class lower in the inheritance hierarchy). Using this rule lets analyze the answer choices: In class a3(A, B): pass when declaring class 'a3' we are passing in class A BEFORE class B even though class A is the super class while B is the sub class. Therefore this option is incorrect (remember, sub classes come before super classes!). These options are correct: class a1(C, D): pass class a2(D, C): pass because we are declaring class 'a2' and 'a1' with classes D and C, there are not directly related in the inheritance chain so their order does not matter. Consider the inheritance chain has a human analogy:Grand parents -> Parents -> Children. It is a linear relation. Using this analogy, D will be the uncle/aunt while C will be the nephew/niece. The above rule does not apply to this 'non-linear' relation. class a4(B, C): pass is incorrect because B comes before C even though B is the super class. class a5(A, D): pass is incorrect because A is the super class and should come after D.

What is the output of the following snippet of code? a = "abcdef" b = a[-1:-4] print(b)

empty string is the output The substring index specified has a starting value of -1 and end value of -4 but indexing in Python does not move in negative direction by DEFAULT. If the substring had been like: b = a[-1:-4:-1] , then the output would have been 'fed'. The third argument specifies the step magnitude and direction and since it was not provided in the original statement an empty string is returned because no substring corresponds to the indexes provided.

Which snippet of code will produce the following output: * ** *** **** *****

for i in range(1,6): print('*' * i)

How to get the python version (hint of different packages platform, info, version)

import platform as p print(p.python_version)

What is the output of the following snippet of code? a = "abcdef" b = a[-3:-1] print(b)

de In this we are getting the substring from 'a'. The substring is extracted starting from the '-3' index and ending on the '-1' index but NOT including the '-1' index. So the resulting substring will contain 2 characters. First corresponding to the -3 index of a and the second corresponding to -2 index of a. Now how to find these index values. Start from the right and start counting from -1. The following displays the indexes:1 2 3 4 5 6 a b c d e f -6 -5 -4 -3 -2 -1

Which of the following evaluates to True? (select 2 answers) "22.67".isdecimal() "76".isdigit() "367".isdecimal() "1.2".isdigit() "2.37".isalpha()

"76".isdigit() and "367".isdecimal() The 'isdigit' function checks if all the characters in the text are digits. Since '.' the decimal point is not a digit hence "1.2".isdigit() is incorrect. Strangely enough, the 'isdecimal' function also works the same way and hence "22.67".isdecimal() is also incorrect. The 'isalpha' function checks if all the characters in the text are letters, since '2.37' contains digits, hence "2.37".isalpha() is wrong.

What is true about the variable 'a' in the following class? (Select 2 Answers) class B: def __init__(self, a): self.a = a

'a' will be unique to each object of class of B 'a' is an instance variable The correct answer choices are facts about variables defined with the 'self' keyword.

What is the output of the following snippet of code? import math as m print(m.sqrt(25) - m.hypot(3,4))

0.0 The 'sqrt' function finds the POSITIVE square root of the number and the 'hypot' function finds the length of the hypotenuse from the given 2 arguments (Formula: c = √(a² + b²)).

The code and respective output are shown Code: import random as r r.seed(0) for i in range(3): print(r.random()) Output: 0.8444218515250481 0.7579544029403025 0.420571580830845 What is the output when the following code is run on the same machine? import random as r r.seed(0) print(r.random())

0.8444218515250481 The seed value ensures that whatever random sequence we get on one machine remains the same when the seed value is same on the same machine. So in this case, the first random value will be the same we got before.

What is the output of the following snippet of code? class A: __Var = 100 def __init__(self): pass def get_var(self): return A.__Var a = A() A._A__Var = 1 b = A() print(b.get_var())

1 The private class variable '__Var' has a value of 10. Although we cannot access this private variable outside the class as '__Var', we can access it using the syntax shown above which is _A__Var. In this, A is the class name. By using this format, we can access private variables. We set the value to 1 using this. Next we create another object 'b' and call the method that returns value for '__Var'. since '__Var' is a class variable, it has the value 1 which we set previously. So the output will be 1.

What is the output of the following snippet of code? a = [1,2,3] b = [[j for j in range(i)] for i in a] print(b[1][1])

1 This is a slightly complicated list comprehension question. Focus on the right side, we are iterating through the list 'a' using the variable 'i'. Next if you focus on left side, we are creating a new list, with numbers starting from 0 and ending on the value i-1 (The 'range()' function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops BEFORE a specified number, which in this case is 'i'. Since we are stopping BEFORE, that is why I said i-1). Now first item in list 'a' is 1, so left side outputs a list starting from 0 and ending on 1-1=0, therefore the list will only have 0 as the item, it will be [0]. Next item in list 'a' is 2, so left side outputs a list starting from 0 and ending on 2-1=1, therefore the list will be [0,1]. Last item in list 'a' is 3, so left side outputs a list starting from 0 and ending on 3-1=2, therefore the list will be [0,1,2]. Since a list comprehension statement outputs a list of items, here it will output a list of lists, the variable 'b' becomes: [[0], [0, 1], [0, 1, 2]] The indexing is such that first index value refers to the index of the outer list at which we want to access the item, for example if I want to access the 3rd item (index 2), I will write, b[2]. The next index value refers to the index value corresponding to the index of the inner list that was selected through previous index.If we selected the 3rd list using b[2], then b[2][1] refers to the '1' inside [0,1,2] because '1' is on index 1. Using this information we can know that b[1] would refer to list [0, 1], and b[1][1] would refer to 1 which is on the index 1 in list [0,1]. So output is 1.

Which of the following is an invalid string 1. "abcd/"xyz/"" 2. 'Bye\"take Care\"' 3. "Hellow !$%^&*(" 4. "There can't be anything wrong with this" 5. 'This can be the "answer"'

1. "abcd/"xyz/"" is correct because the string is INVALID. It uses forward slashes ('/') instead of back slashes ('\'). Back slashes are escape characters.

Which of the following is a true statement (select 2 answers) 1. ASCII came before UTF-8 2. UTF-8 came before ASCII 3. ASCII is only used in America 4. Characters are represented by Octal numbers in UTF-8 5. Each character is represented by a code point in UTF-8

1. ASCII came before UTF-8 5. Each character is represented by a code point in UTF-8

The file abc.txt contains the following 3 lines of text: abc def ghi What is the output of the following snippet of code in abc.py file? file = open('abc.txt', 'w') file.close() file = open('abc.txt') print(file.read())

An empty string is the output. When a file is opened in write mode ('w'), all previous contents are lost.

What is the output of the following snippet of code? for i in range(1,-1,-1): try: print(1/i, end=' ') except: print("ERROR", end=' ') else: print("SAFE", end=' ') finally: print("DONE", end=' ')

1.0 SAFE DONE ERROR DONE There are 2 concepts being tested in this question. First is that you should be familiar with how 'for' loops work in python and what each value passed to the for loop means. 'for(1,-1,-1)' means that initial value is 1, final value will be -1 and the steps will be of magnitude 1 and in negative direction. So value of 'i' will be 1, 0. Second concept being tested is how 'try', 'except', 'else' and 'finally' work. When 'i' is 1, '1' will be printed on screen and the statement inside 'else' and 'finally' will also be printed because 'else' branch runs when there is no error in the 'try' branch and 'finally' branch runs EVERY time whether there is error or not. When 'i' will be 0, the statement inside try block will result in error because of division by zero. Due to this the statement inside 'catch' branch is printed and the statement inside 'finally' is again printed because it runs every time.

What is the output of the following snippet of code? class A: def __init__(self): self.__var = 10 def get_var(self): return self.__var a = A() a.__var = 100 print(a.get_var())

10 Since the '__var' variable has been named starting with 2 underscores ('__'), it is a private variable and its value cannot be accessed nor set outside the class. If we had tried to print the variable outside the class it would have resulted in an exception here we are only trying to set its value outside class which does not throw an error and it also does NOT set/change its value. So when we call the class function to retrieve its value, it is still 10 with which it was initialized.

What is the output of the following snippet of code? class A: def __init__(self, var): A.var = var a = A(10) b = A(100) print(a.var)

100 If you focus on the constructor, you will see that the value of var gets assigned to 'A.var'. Since this is being referenced using the class name, A, it will be a CLASS variable. Therefore it will be COMMON to all instances of the class. When object 'a' gets created/instantiated, the variable 'var' gets set to 10 but when object 'b' gets created, the value of 'var' becomes 100 because it is shared between all objects of class A. So when we print the var variable of object a, its value is 100 and NOT 10.

What is the output of the following snippet of code? class A: __Var = 100 def __init__(self): print(A._A__Var) a = A() ​ None

100 Private class variables can be accessed inside and outside the class by using the way shown in question to access them. print(A.__Var) and print(A._A__Var) are equivalent statements.

What is the output of the following snippet of code? class A: def __init__(self): self.__var = 10 def get_var(self): return self.__var a = A() a._A__var = 100 print(a.get_var())

100 When we instantiate the object 'a', the private variable '__var' gets set to 10. Although we cannot access this private variable outside the class as '__var', we can access it using the syntax shown above which is _A__var. In this, A is the class name. By using this format, we can access private variables. We set the value to 100 using this and call the method that returns its value. Therefore the output is 100.

If the file, abc.py, resides inside the folder xyz, what is the correct import statement to load the variable, var, which is inside the abc.py module, and assign it a value of 1? (Select 2 Answers)

2 ways from xyz.abc import var from xyz.abc import * from xyz.abc import var() is wrong because import variables/functions should not have any parenthesis In Python 'from' always comes before 'import' * imports everything xyz contains abc and not the other way round in python from always comes before import

Which of the following is a true statement? (Select 2 Answers) 1. ASCII has more code points as compared to UTF-8 2. ASCII is a subset of UTF-8 3. ASCII stands for American standard code for information interchange 4. In UTF-8 the 8 represents 8 languages 5. ASCII and UTF-8 are mutually exclusive

2. ASCII is a subset of UTF-8 3. ASCII stands for American standard code for information interchange

Given the following snippet of code: class A: var = 1 def __init__(self): self.x = 1 a = A() Which of the following evaluates to True? (Select 2 Answers) 1. hasattr(a, 'self') 2. hassattr(A, 'var') 3. hassattr(a, 'x') 4. hasattr(A, 'self') 5. hasattr(A, 'x)

2. hassattr(A, 'var') 3. hassattr(a, 'x') Explanation hasattr(A, 'x') is wrong because 'x' is an instance variable and belongs to the object of the class and not an attribute of the class itself. hasattr(a, 'x') is correct because x is an instance variable of object a. hasattr(A, 'var') is correct because 'var' is a class variable. hasattr(A, 'self') & hasattr(a, 'self') are incorrect because 'self' is not an attribute but is a reference.

How to check whether a substring "lop" exists inside the string "envelope". (Select 2 Answers) ​1. 'envelope'.contains('lop') 2. 'lop' inside 'envelope' 3. 'envelope'.find('lop') != -1 4. 'envelope'.lookup('lop') 5. 'lop' in 'envelope'

3. 'envelope'.find('lop') != -1 5. 'lop' in 'envelope lookup, contains and inside are keywords/functions I made up and don't exist in Python. 'in' keyword can be used to test presence of substring and the find function can also be used. 'find' returns the index of the substring so we need to check that it is not equal to -1. An index of -1 means that substring was not found.

What is true about string comparison in Python? (Select 3 Answers) 1. Numbers have higher code point values as compared to Capital Letters 2. Capital Letters have higher code point values as compared to lowercase letters 3. Numbers have lower code point values as compared to Capital Letter 4. The longer string is always greater than shorter strings 5. Comparison ends when a character with higher code point is found as compared to the code point value of character at same index in second string 6. Comparison is based on sum of the code points of all the characters in the string 7. String are compared character by character from left to right

3. Numbers have lower code point values as compared to Capital Letter 5. Comparison ends when a character with higher code point is found as compared to the code point value of character at same index in second string 7. String are compared character by character from left to right

What is true about the assert keyword? (Select 2 Answers) 1. assert stops program execution if unhandled when the condition with it is True 2. assert can cause a ValueError 3. assert stops program execution if unhandled when the condition with it is False 4. assert is an alternative to try/except blocks 5. assert can cause an AssertionError

3. assert stops program execution if unhandled when the condition with it is False 5. assert can cause an AssertionError The correct answer choices are facts about 'assert' keyword. It is good to memorize them. Also pay close attention to the wrong choices as they can be used to confuse you on the real test.

What is the output of the following snippet of code? import math as m print(m.ceil(-2.3) + m.factorial(3))

4 The Math.ceil() function always rounds a number up to the next largest integer. For -2.3 the the next highest integer is -2 (NOT -3, be careful you are dealing with a negative number). For questions related to ceil and floor it is always better to draw a number line and place the numbers on it. The factorial function gives the product of all positive integers less than or equal to the input number. So factorial(3) = 3*2*1 = 6. So final answer = 6-2 = 4

Which of the following is True about bytearrays? (Select 2 Answers) 1. bytearrays cannot be written to files 2. bytearrays can store characters 3. bytearrays are immutable 4. The readinto() method can be used to read bytes from a file into an existing bytearray 5. bytearrays can only have integer values between 0 and 255 inclusive

4. The readinto() method can be used to read bytes from a file into an existing bytearray 5. bytearrays can only have integer values between 0 and 255 inclusive The correct answer choices are facts about 'bytearrays'. It is good to memorize them. Also pay close attention to the wrong choices as they can be used to confuse you on the real test.

Which of the following statements are true? (Select 2 Answers) 1. It is not possible to open a file in both read and write mode simultaneously 2. When opening a file in write mode, if it doesn't exist an error is thrown 3. When opening a file in read mode, if it doesn't exist, an empty file will be created 4. When opening a file in write mode, it deletes all previous content in that file 5. File doesn't have to exist when opening it in write mode

4. When opening a file in write mode, it deletes all previous content in that file 5. File doesn't have to exist when opening it in write mode The correct answer choices are facts and should be memorized. Do pay attention to the wrong choices.

What is the output of the following snippet of code? def A(a): b = a**2 def B(b): return b+3 return B x = A(2) print(x(2))

5 Function A is returning function B. Function B takes in 1 argument and it is local to it even though its name is same as the variable b inside function A. This means that when we call A(2), it has no effect on function B. So when we call x(2), it is as if we are simply running function B, i.e. 2+3 so answer is 5.

What is the output of the following snippet of code? a = "engineer" print(a.find('e', 1))

5 The 'find' function takes in 3 arguments. The first argument is the substring to look for in target string and the 2nd and 3rd arguments (both optional) specify the slice of target string to look in for the substring entered in first argument. 2nd argument specifies which index position (inclusive) to start looking for the sub string. Here the starting index is set to be 1, so the find function starts looking for 'e' from the character 'n' corresponding to index 1. The 'e' is found at index 5, so 5 is the output. IF starting index had not been specified THEN the answer would have been 0.

Which of the following is the correct way to declare a lambda function 1. lambda(x,y): x+ y 2. func x,y: x+y 3. def lambda x,y: x+y 4. lambda x,y: return x+y 5. lambda x, y : x+y

5. lambda x, y : x+y The correct answer is a fact please be familiar with it. Also see the wrong answers and remember them as how NOT to declare a lambda function!

What is the output of the following code snippet? a = "abcdef" a[1] = 'x' print(a)

A TypeError will occur A TypeError occurs because it is the nature of strings to be immutable and the above code is violating this.

Given the following snippet of code: class A: pass class B(A): pass How are the two classes, A and B, related?

A is the super class of B B is a sub class of A Since B is inheriting FROM A, it is the sub class. Think of it like a hierarchy, the class A sits at the top while B sits at the bottom, so A is the super class and B is the sub class.

What is the output of the following snippet of code? class MyException(Exception): pass try: raise MyException("A", "B") except MyException as e: print(e.args)

A tuple of length 2 The 'args' property is a tuple containing the values passed when the exception is raised.

What is the output of the following snippet of code: my_dict = {'a':1, 'b':2} try: my_dict['c'] except IndexError: print('A', end=' ') except Exception: print("B", end=' ') except KeyError: print("C", end=' ')

B When we try to access the dictionary using key: 'c', we will get a 'KeyError' because this key does not exist in the dictionary. If we check the first 'except' branch it will only catch 'IndexError' so this will not catch our error. Next we look at the 'Exception' branch. Since ALL exceptions are derived from this base class, it WILL catch the exception and 'B' will be printed on the screen. Since the exception has been caught, the program exists. You have to be mindful of the fact that only 1 except branch gets executed. Since exception was caught before we could reach the 'KeyError' branch, 'C' does NOT get printed on the screen.

What is the output of the following snippet of code? class A: def func(self): return "A" class B: def func(self): return "B" class C(B,A): pass c = C().func() print(c)

B You need to remember this rule that whenever there are more than 2 classes from which a class is inheriting from and both classes contain a function/variable with same name then the class name on the left is given priority and its functions/variables are called so in this case 'B' is first so its function is called.

What is the output of the following snippet of code? class A: pass class B(A): pass class C(B, A): def __init__(self): pass def get_bases(self): for c in C.__bases__: print(c.__name__, end=" ") C().get_bases()

B A When the 'get_bases' method gets called, it iterates through the built in class attribute '__bases__'. This attribute returns the tuple of base classes of a class. We iterate through this tuple and for each class info, we print the class name which is found in the '__name__' attribute for that class. Therefore the output is 'B A' because classes B and A are the base classes of class C (class C inherits from both).

The fact that the following snippet of code throws an Attribute error depicts which phenomena of OOP? class B: def __init__(self): self.__var = 1 b = B() print(b.__var)

Encapsulation In Python, Polymorphism lets us define methods in the child class that have the same name as the methods in the parent class. In inheritance, the child class inherits the methods from the parent class. In this question, there is no child class so both these options are out. Abstraction is the process of hiding the real implementation of a function from the user and emphasizing only on how to use the function. This is also not happening in this question. When a variable name is defined starting with __ (2 underscores), it is a private variable. So it cannot be accessed outside the class. This concept of public and private variables is related to encapsulation. Encapsulation is restricting access to methods and variables based on their requirement. Data hiding is just a term I made up to confuse although it is the essence of encapsulation but it is not the correct option.

The file abc.txt contains the following 1 line of text: Hello World What is the output of the following snippet of code in abc.py file? file = open('abc.txt') print(file.read(4))

Hell The 'read()' method returns the specified number of bytes from the file. Default is -1 which means the whole file. Since we are providing it the number 4, it will read 4 bytes of data from the file. As each character takes up 1 byte of space, 4 characters will be read from the file and they will be as they are present in the file.

What is the output of the following snippet of code: a = [1,2,3] print(a[3])

Index Error Occurs Remember! Indexes in Python start from 0 so the list has indexes 0,1 and 2 corresponding to the numbers, 1,2 and 3 respectively. Since index 3 is not present in the list, when we try to call the list by using 3 as index, we get an IndexError. Fun fact: If we try using indexing like this: print(a[5:10]) It will NOT throw any error, although these indexes don't exist in the list. Output of this will be an empty list.

What is true about the following string: "/n" a. It adds a newline in the string b. It has a length of 2 c. It cannot be used inside the print statement d. It has a length of 1 e. It adds a tab space in the string

It adds a newline in the string It has a length of 1 Although '\n' looks like it has 2 characters but since '\' is considered the escape character, when it is combined with another character, the combination is considered to be a single character. '\n' is used to represent a new line in the string. Fun fact: In order to print '\' in a string, you need to 'escape' it by using another '\' so the print statement becomes: print("\\"). This will print a single '\' on the screen

What will be the result of running the following snippet of code? print(dir(math))

It will print a list of names of all entities inside the math module. The 'dir' function will return all the properties and methods, even built-in properties for any entity passed to it. In this case it is the 'math' module

Which of the following statements are true a. Opening a file in 'a' mode allows writing to the end of file, preserving the previous content b. It is possible to open a read only file in 'r+' mode c. Opening a file in 'a' allows reading and writing both d. Opening a file that doesn't exist throws the FILENOTFOUNDERROR e. 'w+' and 'r+' modes of opening a file are essentially the same

Opening a file in 'a' mode allows writing to the end of file, preserving the previous content Opening a file that doesn't exist throws the FILENOTFOUNDERROR 'w+' and 'r+' modes of opening a file are essentially the same is incorrect because although both open the file for reading and writing, the difference is that w+ truncates the file to zero length (deletes previous content) if it exists or creates a new file if it doesn't. While r+ neither deletes the content nor creates a new file if it doesn't exist. It is possible to open a read only file in 'r+' mode this option is incorrect because r+ mode opens the file in read and write both, so if file is read only then we can't open it for writing. If we try, we get PermissionError. Opening a file in 'a' mode allows reading and writing both This is incorrect because opening a file in mode 'a' means appending and does not include reading. The correct choices are facts so should be memorized

What is the output of the following snippet of code? try: print(i = 1/0) except TypeError as e: print("Hi!", end= " ") finally: print("Bye!") ​ Hi! Bye! (Incorrect)

The code breaks due to unhandled exception The statement inside 'try' branch produces a 'ZeroDivisionError'. Since the 'catch' branch is set to catch only 'TypeErrors' it will not "catch" the exception and it will break the code because it is unhandled.

What is the output of the following code snippet? print(ord('c'))

The output is a Unicode code point point and will be an integer. The 'ord' function outputs the Unicode code point (which is an integer) for the entered character.

What is true about the following snippet of code? (Select 2 Answers) import random as r print(r.sample([1,2,3], 1))

The output is a list and the output can be [2] Explanation The 'sample()' function takes in 2 arguments, the first is the sequence from which we want to draw the random sample and the second argument which specifies how many items we need to draw. The second argument cannot be greater than the length of the sequence otherwise a ValueError occurs, in this case it is not true. This function always returns a list containing the sample even if the second argument is 1.

What is the output of the following snippet of code? class A: pass class B(A): pass b1 = B() b2 = B() a1 = A() a2 = a1 print(b2 is not b1, a2 is a1, a1 is b1, sep=' ')

True True False The 'is' operator compares the IDENTITY of two objects while the '==' operator compares the VALUES of two objects. The 'is' operator evaluates to True if the variables on either side of the operator point to the same object and false otherwise. Pointing to the same object means both variables hold the same reference in memory. Since 'b2' and 'b1' objects are not same, the first statement is True. When we assign 'a2' to 'a1', we are basically saying that 'a2' should point to the same object in memory that 'a1' is pointing to so the statement is True. Finally since 'a1' and 'b1' are different objects the last statement is False.

What is the output of the following code snippet? a = "abcdef" del a[0:2] print(a) ​

Type Error Strings are immutable so deleting any characters is not possible.

What is the output of the following snippet of code? class A: def func(): print("Hello!") a = A() a.func()

Type Error f a function inside a class does not have 'self' as one of the arguments, it can only be called by reference of the class. So if the last line above had been: A.func() the output would have been 'Hello!'. Self is required for objects to call the function because self is basically a reference. When we use the dot notation to call the function i.e. a.func(), we are basically saying that call the function 'func' with reference/self equal to object a. The error is TypeError because it is the nature/type of function 'func' that it accepts NO arguments but when we call the function as a.func(), we are passing it the reference value which is against the nature/type of the function.

What is the output of the following snippet of code? def func(a): print(a) func()

TypeError occurs. AttributeError can be defined as an error that is raised when an attribute reference or assignment fails. Here none of that is happening. One handy way of deciding between value error and type error is by understanding that value error occurs when there is a problem with the content of the object you tried to assign the value to for example the statement int("a") produces a ValueError because the value being provided to int is of the wrong type (Don't associate with TypeError). Now the 'type' of the 'func' function in the question is such that it REQUIRES a value. It is the TYPE (read nature) of this function that it must need a value to work and if we call it simply like func() it violates its nature. Hence a TypeError occurs.

What is the output of the following snippet of code? a = [1,2,3,4,5,6] b = list(filter(lambda x: x%2 == 0, a)) print(b)

[2, 4, 6] The 'filter' function is taking in 2 arguments, the first is the predicate, which is a fancy way of calling a function that returns a Boolean and the second argument is the object to apply the predicate. In this case we are passing in the lambda function that checks whether a number is divisible by 2 (Divisibility is checked by returning true when the number divided by 2 has remainder 0). The function is then applied to each member of the list a. And the final result contains the numbers which returned true i.e. which are even numbers (divisible by 2).

What is the output of the following snippet of code? a = ['aBc', 'def', 'gHi'] b = list(map(lambda x: x.capitalize(), filter(lambda y: y[1].isupper(), a))) print(b)

['Abc', 'Ghi'] The correct approach for this is first considering the filter function. A lambda function has been passed as the first argument which specifies how the list (second argument) needs to be filtered. The function is applied to each item of the list and items for which the function returns 'True' are made part of the output from the filter function. Pay close attention to the lambda, it takes in the argument y (consider it a single item from list e.g. aBc) it gets the element on index 1 of the item and it then checks whether that element is an upper case character or not (using isupper() function). If we apply this function to the items in list a, the output list will be:['aBc', 'gHi'] because these are the 2 items for which the character on index 1 is upper case so these 2 items return True when lambda is applied on them.Next we must consider the map function. Which also takes in a lambda function as the first argument and a list as its second argument. Here the list will be what we got from the above filter function. The function of the map function is to apply the lambda function to all the items in the list and return the output list. This sounds similar to what the filter function does but map function does not remove results. Its lambda function also does not have to necessarily return Booleans. Therefore the capitalize() function gets applied to all the items in the list. The capitalize() function makes the first character of a string into upper case and rest of the characters into lower case. Therefore the final answer is the first option.

What is true about __init__.py file?

_init_.py allows you to define any variable at the package level Files named _init_.py are used to mark directories on disk as Python package directories The correct answer choices are facts about '__init__.py' file. It is good to memorize them. Also pay close attention to the wrong choices as they can be used to confuse you on the real test.

If the following piece of code resides inside the abc.py file, what is the output when the file is run? class A: pass print(A.__module__) ​

_main_. The '__module__' property holds the name of the module, the function/class was defined in. When a file is run on its own in python, the module is set to '__main__' but if the class had been referenced inside another file and then the code had been run, the output would have been 'abc'.

What is the output of the following snippet of code? a = 'abcdefg' b = 'decaf' for i in a: if i not in b: print(i, end=" ") ​ a c d e f (Incorrect)

a c d e f This code is simply checking which of the characters in string a do NOT occur in string b. By iterating through all the characters in string a, it checks whether that character is NOT present in string b by using the 'not in' statement. It then simply prints the characters which are not present in b. Since the characters 'b' and 'g' are not present in 'decaf', they get printed on screen.

Which of the following statements are correct about the sys.path variable? (Select 2 Answers) a. Appending a path does not permanently modify it. We have to append the path for every execution. b. For adding the path 'C:\\test' to sys.path the following is the correct format sys.path.append('C:\\test') c. For adding the path 'C:\\test' to sys.path the following is the correct format sys.path[path = 'C:\\test' d. Appending a path to it, permanently modifies it and we don't have to append the path for next execution e. For adding the path 'C:\\test' to sys.path the following is the correct format: sys.path = sys.path.append('C:\\test')

a. Appending a path does not permanently modify it. We have to append the path for every execution. b. For adding the path 'C:\\test' to sys.path the following is the correct format sys.path.append('C:\\test') The correct answer choices are facts about 'sys.path' variable. It is good to memorize them. Also pay close attention to the wrong choices as they can be used to confuse you on the real test.

Which of the following evaluates to True given the following code? (Select 2 Answers) a = "television"

a.index('ele') == 1 a.index('e', 2) == 3 The index() method is similar to find() method for strings. The only difference is that find() method returns -1 if the substring is not found, whereas index() throws an exception. The 'index' function takes in 3 arguments. The first argument is the substring to look for in target string and the 2nd and 3rd arguments (both optional) specify the slice of target string to look in for the substring entered in first argument.

What is the output of the following snippet of code? a = "ab cd" print('*'.join(a.split()))

ab*cd Here knowledge of 2 functions is being tested, the first one is the 'split' function. This function splits the string on the string specified in the argument and returns a list. If no character is specified then it splits on empty space i.e. " ". So "ab cd" becomes ['ab', 'cd']. Next the join function is applied, which joins the list members with the character specified, hence the answer becomes 'ab*cd'.

The file abc.txt contains the following 3 lines of text: abc def ghi What is the output of the following snippet of code in abc.py file? file = open('abc.txt') print(file.readline(3))

abc The 'readline()' method returns ONE line from the file. You can also specify how many bytes from the line to return, by using the size parameter, which in this case is 3. So it will read the first 3 bytes from the first line hence answer is 'abc'.

The file abc.txt contains the following 3 lines of text: abc def ghi What is the output of the following snippet of code in the abc.py file? file = open('abc.txt') print(file.read(5))

abc d The 'read' function has been called to read in 5 bytes of data from the file. The characters 'abc' make up 3 bytes, the new line character '\n' takes up the 4th byte and the 'd' on second line makes up the 5th character therefore the fourth option is correct.

What is the output of the following snippet of code? a = "abc" for i in a: a += 'z' print(a)

abczzz Although strings are immutable, this immutability means that we cannot alter any characters present in the string but we CAN append new characters to the string so abczzz is correct.

What is the output of the following snippet of code? a = "abcdef" b = a[:-2:2] print(b)

ac The substring specified has a starting value unspecified so it defaults at 0 index which is character 'a'. The end value is -2 which is the character 'e'. The step is positive 2. So first character in substring would be 'a', second character will be 2 index jumps after 'a' so it will be 'c'. Next when we try to jump by 2 indexes we reach the character 'e' (index = -2). Since this cannot be included in the substring because it was specified to be the end index value, we stop here. Final output is therefore 'ac'

Which of the following evaluates to True? (Select 2 Answers) ​ a. "ABC$D1".isalnum() b. "ABCD1".isalnum() c. "".isspace() d. "ABCD".isupper() e. "aBcd".islower()

b. "ABCD1".isalnum() d. "ABCD".isupper() "aBcd".islower() is incorrect because the 'islower()' extension method checks whether all ALPHABETS in the string are lower case, which is not the case in the option. The emphasis on alphabets is there because even if the string contains numbers or other characters, it will ignore them and consider only the alphabets. "ABCD".isupper() is correct because all alphabets are upper case which is checked by the 'isupper()' extension method. The 'isalnum()' extension method checks whether the string contains only alphabets and/or numbers. If any other characters are present then the function returns False. Since this option: "ABCD1".isalnum() contains only alphabets and numbers, it returns True. So it is incorrect. "ABC$D1".isalnum() And since string in this option contains the character '$' it returns False so this option is incorrect. "".isspace() is incorrect because it contains an empty string, NOT a space. so the 'isspace()' method returns False.

The fact that output of the following code is B and NOT A, depicts what? (Select 2 Answers) class A: def func(self): print("A") class B(A): def func(self): print('B') b = B() b.func() a. Encapsulation b. Overriding c. Overloading d. Polymorphism e. Inheritance

b. Overriding d. Polymorphism Overriding is when you call a method on an object with the same signature (name + parameters) as the one in the superclass. The method in base class is 'overriding' the method in super class. Overriding is a way to achieve polymorphism and polymorphism is the result of this overriding. Polymorphism is just a principle that can be achieved by overriding, overloading and dynamic (late) binding. Polymorphism is where you are not sure of the objects type at runtime and the most specific method is called. Therefore the behavior of the method called may differ, depending on the objects type at runtime. Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different. Since this is not happening here, it is not one of the correct answer choices.

Given the following snippet of code: class A: var = 1 def __init__(self): self.x = 1 def get_var(): return A.var class B(A): new_var = 1 def __init__(self): super().__init__() b = B() Which of the following is True (2 answers) a. hasattr(B, 'x') b. hasattr(b, 'var') c. hasattr(b, 'B') d. hasattr(b, 'A') e. hasattr(b, 'get_var')

b. hasattr(b, 'var') e. hasattr(b, 'get_var') The 'hasattr()' method returns true if an object has the given named attribute and false if it does not. One handy rule for determining whether any thing is an attribute of an object is by considering whether we can access that thing using the dot notation (object.attribute). hasattr(b, 'A') and hasattr(b, 'B') are incorrect because 'A' and 'B' are class names and not attributes of object b. hasattr(b, 'var') is correct because, 'var' is an attribute of the object b. Even though 'var' is a class variable it is still considered an attribute of the object (We can access it using the dot notation). hasattr(B, 'x') is incorrect because 'x' is not an attribute of class B but is an instance variable for objects of class B or A. hasattr(b, 'get_var') is correct because objects of class B inherit the methods of class A so 'get_var' is an attribute of object 'b'. Fun fact: 'hasattr()' function returns FALSE for private variables/attributes.

I have a python file, abc.py, inside the following directory: 'C:\\test\\abc.py' which is NOT in the python path. I want to use the function func() in this module. I am working in the directory: 'D:\\project' Which code snippet allows me to do this correctly?

from sys import path path.append(*C:\\test") import abc abc.func()

Which of the following code snippet is correct? ('num' is a variable inside 'test' module) ​

from test import num as m print(m)

Given the following snippet of code: class A: var = 1 def __init__(self): self.x = 1 class B(A): def __init__(self): super().__init__() b = B() Which of the following evaluates to True? (Select 2 Answers) hasattr(B, '_init_') hasattr(A, 'new_var') hasattr(b, '_init_') hasattr(B, 'super') hasattr(B, 'A')

hasattr(B, '_init_'), hasattr(b, '_init_') '__init__' is the attribute of both classes and objects.Note: Even though __init__ is the attribute of objects, it is NOT present in the __dict__ property of objects but IS present in the __dict__ property of class. hasattr(B, 'A') is incorrect because A is not an attribute of B but is the super class of B. hasattr(B, 'super') is incorrect because the super() function is used to give access to methods and properties of a parent class and is not an attribute of child class.


Related study sets

Module 7 Textbook Study Questions

View Set

Chapter 12: Products and services strategies

View Set

Health Informatics Final (All Quizzes)

View Set

Chapter 3 : Groups, Teams, & Powerful Meetings

View Set

Contemporary social problems chapter 2

View Set

Critical Thinking and Nursing Process

View Set

AP World Unit 6 Practice Quizzes

View Set