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
Q

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)

A

C. isinstance(b,A) Ture

D. isinstance(a,A) True

E. isinstance(B,b) Error

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

When will isinstance() error?

A

When the second argument is not a class

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

‘a’*0

A

’’

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

len(234)

A

TypeError: object of type ‘int’ has no len()

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

1//2

A

0

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

-1//2

A

-1

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

class C():
__C=3

def \_\_string_amplify(self,char='b',times=1):
    self.a += char*times

c = C()
c.__string_amplify(‘d’, 2)

A

Error

needs to be c._C__string_amplify(‘d’, 2)

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

LOOK OUT FOR PRIVATE VARIABLES!!!!!!

CAN ONLY CALL THEM _CLASS__VARIABLE

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

How do you make a class an exception?

A

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

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

class A():
pass
class B(A):
pass
class C(A):
pass
class D(C,B,A):
pass

D.__bases__

A

(__main__.C, __main__.B, __main__.A)

This is a tuple and contains the classes not just the names

35
Q

class A():
pass
class B(A):
pass
class C(A):
pass
class D(C,B,A):
pass

D.__bases__[1].__bases__[0].__bases__

A

(object,)

A is the root class, so its base is type object

36
Q

class A:
def __init__(self):
pass

a = A(1)
print(hasattr(a,’A’))

Output?

A

Error

__init__ has no argument

37
Q

class A:
def __init__(self):
pass

a = A()
print(hasattr(a,’A’))

A

False

38
Q

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)

A

ex

39
Q

listy = [x for x in range(5)]
listy = list(filter(lambda x: x-3 and x-1,listy))

A

[0,2,4]

40
Q

hasattr(str,’__iter__’)

A

True

41
Q

What element can you not iterate through?

A

integers and floats

42
Q

lambda x: x*2 if hasattr(x, ‘__iter__’) else x**2, [‘ku’, 9, [3,8,3], (2,)]

A

[‘kuku’, 81, [3,8,3,3,8,3], (2,2)]

43
Q

def update_dict():
dict2 = {‘R’:’Best Language’}
dict2.update({‘Python’:’Second best’})
return lambda: dict2

How do you print the dict2?

A

print(update_dict()())

or update_dict()()

44
Q

def update_dict():
dict2 = {‘R’:’Best Language’}
dict2.update({‘Python’:’Second best’})
return lambda: dict2

fun = update_dict()
How do you print the dict2?

A

fun()

or print(fun())

45
Q

What does os.chdir(“..”) mean?

os.chdir(“./folder2/subfolder1”)
os.chdir(“..”)
os.getcwd()

A

os.chdir(“..”) goes up one folder- folder 2

’./’ means parent directory
‘..’ move to parent folder (move one level up)

46
Q

f = open(‘file.txt’, ‘a+b’)

A

We opened the file stream in binary, to be appended and updated

47
Q

What is the difference between a and + ?

A

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
Q

We opened the file stream in binary, to write, read or update?

A

‘w+b’

49
Q

a = [1]
b=a[:]
a[0]=0

b?

A

1

This works for LISTS

50
Q

a = [1]
b=a
a[0]=0

b?

A

0

This works for LISTS

51
Q

Can you do this ‘python’.sort()?

A

NOOOOOOOOOO

sort() is for lists

52
Q

import sys
sys.path

Output?

A

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
Q

‘python’.index(‘th’)

A

2

54
Q

sorted(‘python’)

A

[‘h’, ‘n’, ‘o’, ‘p’, ‘t’, ‘y’]

55
Q

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()

A
56
Q

Second argument of hassatr is a ….

A

string

57
Q

Second argument of isinstance is

A

class variable name (not a string)

58
Q

l =[0,1,2,3]
l[:3]

A

[0,1,2]

59
Q

pair1 = (‘a’,’b’,’c’)
pair2 = (‘d’,’e’,’f’)
index = 0

while index < len(pair1):
for item in pair2:
print(pair2[index] , item)
index += 1

A

d d
d e
d f
e d
e e
e f
f d
f e
f f

60
Q

val = ‘2’ or 1
val *= 3
print(val)

A

‘222’

61
Q

val = 1 or ‘2’
val *= 3
print(val)

A

3

62
Q

num = 12
num2 = num
num = num + 1
print(num2)

A

12

Integer

63
Q

Bytes are immutable
Slicing a bytes object returns a bytes object

A
64
Q

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

print(hasattr(A,’a’))

A

False

65
Q

’’ in ‘ ‘

A

True

66
Q

not []

A

True

67
Q

not ‘’

A

True

68
Q

not 0

A

True

69
Q

class Class_A:
def __init__(self,var):
return var

obj = Class_A(20)
print(obj)

A

Error

__init__ cannot return a value

70
Q

i = 0
while i <4:
print(i, end=’-‘)
i +=1.5
if ((i<4) == False):
break
else:
print(0, end=’ ‘)

A

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
Q

turning a dictionary into a list…

A

creates a list of the keys

cannot change back

72
Q

i = ‘ ‘
for i in ‘ ‘:
print(‘python’,end=i)

A

pythonpythonpythonpythonpythonpython

for i in ‘number of spaces’

73
Q

i = ‘ ‘
while i in ‘ ‘:
print(‘python’,end=i)

A

pythonpythonpythonpythonpythonpython………………..infinte

while creates infinite loop

74
Q

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

A

0

as A.__init__(self) is after self.b =5 the self.b = 0 in class A overrides it

75
Q

li = [1,2,3,4,5,6]
li[-100:]

A

[1,2,3,4,5,6]

76
Q

int(‘100’,2)

int(‘0b100’,2)

A

4

base 2 so binary 100

first argument has to be string

77
Q

{2+3}*5

A

Error

cant multiply set

78
Q

(2+3,)*5

A

(5, 5, 5, 5, 5)

79
Q

class calc:
A = 20
B = 20
def __init__(self,a,b):
A = a
B= b
print(self.A + self.B)

calc(4,5)

A

40

as the variables in the __init__ don’t do anything they are not assigned to instance or class variables

80
Q

from math import *

dir(math)

A

Name Error

we have not imported math, we have imported maths contents

81
Q

What does Python Standard Library contain?

A

Storage space for the base Python packages and types

82
Q

Print(True or False)

A

True

83
Q

Print(True and False)

A

False

84
Q

l = [[c for c in range(r)] for r in range(3)]

A

[[], [0], [0, 1]]