Practise qus Flashcards

1
Q

Class A:
A = 1
def __init__(self):
self.a = 0

print(hasattr(A,’a’)

A

False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

try:
raise Exception
except:
print(‘c’)
except Exception:
print(‘b’)

A

Syntax Error

as except should be last branch

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

try:
raise Exception(1,2,3)
except Exception as e:
print(len(e.args))

A

3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Class A:
def __init__(self, v):
self.__a = v+1

a = A(0)
print(a.__a)

A

Attribute Error

__a private so have to be called like

_A__a

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

class A:
def a(self):
print(‘a’)

class B:
def a(self):
print(‘b’)

class C(B,A):
def c(self):
self.a()

o = C()
o.c()

A

b

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

try:
raise Exception
except BaseException:
print(‘c’)
except Exception:
print(‘b’)
except:
print(‘h’)

A

c

Base Exception is main exception

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

assert var != 0

A

will stop the program when var == 0

as raises exception with var !=0 == False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

my_str = ‘race’

my_str = my_str.copy()

A

AttributeError

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

my_str = ‘race’

my_str = my_str.insert(3,q)

A

Error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

for i in range(10):
pass

print(i)

A

9

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

list1= [i for i in range(1,10)]
list2 = list1[-1:1:-1]

A

[9, 8, 7, 6, 5, 4, 3]

Remember the end range value is not included therefore the list reverses and stops at index = 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Can tuples store tuples?

A

yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Can tuples store lists?

A

yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What can you deduce from the following statement?
(Select two answers)
str = open(‘file.txt’, “rt”)

a) str is a string read in from the file named file. txt
b) a new line character translation will be performed during the reads
c) if file. txt does not exist, it will be created
d) the opened file cannot be written with the use of the str variable

A

b,d

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

The first parameter of each method:

A

a) holds a reference to the currently processed object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

i = 5
while i>0:
i = i//2
if i % 2 = 0:
break
else:
i+=1
print(i)

A

should be:

i % 2 == 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

i = 9
i =+ 2

What does i equal?

A

2

as i = +2
just means i equals positive 2

to add you need +=

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

for i in range(1,3):
print(‘ * ‘,end=’’)
else:
print(‘ * ‘)

A

Star star star
* * *

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

def f(n):
for i in range(1,n+1):
yield I

print(f(2))

_______________________________________
def f(n):
for i in range(1,n+1):
yield I

print([i for i in f(2)])

What is the difference in these two outputs? What do you need to remember?

A

<generator object f at 0x7f53e1f7fc10>

__________________________

NameError as I is not defined

you need to loop through generators

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How many stars () does the snippet print?
s = ‘
****’
s = s - s[2]
print(s)

A

Error

strings support concatenation. ‘-‘ is not supported in strings

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Which can you do to this tuple: tup = ()
a) tup[:]
b) tup.append(0)
c) tup[0]
d) del tup

A

a and d

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

issubclass(B,B)

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

class C():
Z = 15
def __init__(self):
self.c = 2
def multiplier(self):
self.c *= 2

y = C()
x = C()
x.multiplier()
y.multiplier()
y.multiplier()
print(x.c)

A

4

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

class C():
Z = 15
def __init__(self):
self.c = 2
def multiplier():
self.c *= 2

y = C()
x = C()
x.multiplier()
y.multiplier()
y.multiplier()
print(x.c)

A

Type error as no self parameter in multiplier

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
class A: X=0 def __init__(self): self.x = 5 class B(A): Y=1 def __init__(self): self.y = 7 a = A() b = B() Which of the following do NOT output False? A. isinstance(A,A) B. isinstance(A.X,A) C. isinstance(b,A) D. isinstance(a,A) E. isinstance(B,b)
C. isinstance(b,A) Ture D. isinstance(a,A) True E. isinstance(B,b) Error
26
When will isinstance() error?
When the second argument is not a class
27
'a'*0
''
28
len(234)
TypeError: object of type 'int' has no len()
29
1//2
0
30
-1//2
-1
31
class C(): __C=3 def __string_amplify(self,char='b',times=1): self.a += char*times c = C() c.__string_amplify('d', 2)
Error needs to be c._C__string_amplify('d', 2)
32
LOOK OUT FOR PRIVATE VARIABLES!!!!!! CAN ONLY CALL THEM _CLASS__VARIABLE
33
How do you make a class an exception?
class my_exception(Exception) my exception is now a subclass of Exception you can raise it now can make it a subclass of any Error, e.g. LookUpError
34
class A(): pass class B(A): pass class C(A): pass class D(C,B,A): pass D.__bases__
(__main__.C, __main__.B, __main__.A) This is a tuple and contains the classes not just the names
35
class A(): pass class B(A): pass class C(A): pass class D(C,B,A): pass D.__bases__[1].__bases__[0].__bases__
(object,) A is the root class, so its base is type object
36
class A: def __init__(self): pass a = A(1) print(hasattr(a,'A')) Output?
Error __init__ has no argument
37
class A: def __init__(self): pass a = A() print(hasattr(a,'A'))
False
38
class Ex(Exception): def __init__(self,msg): Exception.__init__(self,msg +msg) self.args = (msg,) try: raise Ex('ex') except Ex as e: print(e)
ex
39
listy = [x for x in range(5)] listy = list(filter(lambda x: x-3 and x-1,listy))
[0,2,4]
40
hasattr(str,'__iter__')
True
41
What element can you not iterate through?
integers and floats
42
lambda x: x*2 if hasattr(x, '__iter__') else x**2, ['ku', 9, [3,8,3], (2,)]
['kuku', 81, [3,8,3,3,8,3], (2,2)]
43
def update_dict(): dict2 = {'R':'Best Language'} dict2.update({'Python':'Second best'}) return lambda: dict2 How do you print the dict2?
print(update_dict()()) or update_dict()()
44
def update_dict(): dict2 = {'R':'Best Language'} dict2.update({'Python':'Second best'}) return lambda: dict2 fun = update_dict() How do you print the dict2?
fun() or print(fun())
45
What does os.chdir("..") mean? os.chdir("./folder2/subfolder1") os.chdir("..") os.getcwd()
os.chdir("..") goes up one folder- folder 2 './' means parent directory '..' move to parent folder (move one level up)
46
f = open('file.txt', 'a+b')
We opened the file stream in binary, to be appended and updated
47
What is the difference between a and + ?
updating is updating/changing existing data a is just adding data 1. What do we want to do with the file? ## r - reading (DEFAULT) ## w - writing (go to byte 0) -- adding data ## a - appending (go to byte -1) -- adding data ## x - exclusive creation -- adding data 2. Do we want to change its contents? ## NO: We don't need to add anything (DEFAULT) ## YES: + (update) -- changing data 3. How do we want to read it? ## b = binary format ## t = text format (DEFAULT)
48
We opened the file stream in binary, to write, read or update?
'w+b'
49
a = [1] b=a[:] a[0]=0 b?
1 This works for LISTS
50
a = [1] b=a a[0]=0 b?
0 This works for LISTS
51
Can you do this 'python'.sort()?
NOOOOOOOOOO sort() is for lists
52
import sys sys.path Output?
list of strings ['/content', '/env/python', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.8/dist-packages/IPython/extensions', '/root/.ipython']
53
'python'.index('th')
2
54
sorted('python')
['h', 'n', 'o', 'p', 't', 'y']
55
uname_result(system='Linux', node='e7c812d8a0e6', release='5.10.147+', version='#1 SMP Sat Dec 10 16:00:40 UTC 2022', machine='x86_64', processor='x86_64') platform.uname() Linux-5.10.147+-x86_64-with-glibc2.27 platform.platform()
56
Second argument of hassatr is a ....
string
57
Second argument of isinstance is
class variable name (not a string)
58
l =[0,1,2,3] l[:3]
[0,1,2]
59
pair1 = ('a','b','c') pair2 = ('d','e','f') index = 0 while index < len(pair1): for item in pair2: print(pair2[index] , item) index += 1
d d d e d f e d e e e f f d f e f f
60
val = '2' or 1 val *= 3 print(val)
'222'
61
val = 1 or '2' val *= 3 print(val)
3
62
num = 12 num2 = num num = num + 1 print(num2)
12 Integer
63
Bytes are immutable Slicing a bytes object returns a bytes object
64
class A: A=1 def __init__(self): self.a = 0 print(hasattr(A,'a'))
False
65
'' in ' '
True
66
not []
True
67
not ''
True
68
not 0
True
69
class Class_A: def __init__(self,var): return var obj = Class_A(20) print(obj)
Error __init__ cannot return a value
70
i = 0 while i <4: print(i, end='-') i +=1.5 if ((i<4) == False): break else: print(0, end=' ')
0-1.5-3.0- as i is 4.5 before if statement within while loop so - is printed when i = 3 then i =4.5 and loop is broken with break
71
turning a dictionary into a list...
creates a list of the keys cannot change back
72
i = ' ' for i in ' ': print('python',end=i)
pythonpythonpythonpythonpythonpython for i in 'number of spaces'
73
i = ' ' while i in ' ': print('python',end=i)
pythonpythonpythonpythonpythonpython....................infinte while creates infinite loop
74
class A: A=1 def __init__(self): self.b = 0 class B(A): B=1 def __init__(self): self.b = 5 A.__init__(self) obj = B() obj.b
0 as A.__init__(self) is after self.b =5 the self.b = 0 in class A overrides it
75
li = [1,2,3,4,5,6] li[-100:]
[1,2,3,4,5,6]
76
int('100',2) int('0b100',2)
4 base 2 so binary 100 first argument has to be string
77
{2+3}*5
Error cant multiply set
78
(2+3,)*5
(5, 5, 5, 5, 5)
79
class calc: A = 20 B = 20 def __init__(self,a,b): A = a B= b print(self.A + self.B) calc(4,5)
40 as the variables in the __init__ don't do anything they are not assigned to instance or class variables
80
from math import * dir(math)
Name Error we have not imported math, we have imported maths contents
81
What does Python Standard Library contain?
Storage space for the base Python packages and types
82
Print(True or False)
True
83
Print(True and False)
False
84
l = [[c for c in range(r)] for r in range(3)]
[[], [0], [0, 1]]