Practise qus Flashcards
Class A:
A = 1
def __init__(self):
self.a = 0
print(hasattr(A,’a’)
False
try:
raise Exception
except:
print(‘c’)
except Exception:
print(‘b’)
Syntax Error
as except should be last branch
try:
raise Exception(1,2,3)
except Exception as e:
print(len(e.args))
3
Class A:
def __init__(self, v):
self.__a = v+1
a = A(0)
print(a.__a)
Attribute Error
__a private so have to be called like
_A__a
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()
b
try:
raise Exception
except BaseException:
print(‘c’)
except Exception:
print(‘b’)
except:
print(‘h’)
c
Base Exception is main exception
assert var != 0
will stop the program when var == 0
as raises exception with var !=0 == False
my_str = ‘race’
my_str = my_str.copy()
AttributeError
my_str = ‘race’
my_str = my_str.insert(3,q)
Error
for i in range(10):
pass
print(i)
9
list1= [i for i in range(1,10)]
list2 = list1[-1:1:-1]
[9, 8, 7, 6, 5, 4, 3]
Remember the end range value is not included therefore the list reverses and stops at index = 2
Can tuples store tuples?
yes
Can tuples store lists?
yes
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
b,d
The first parameter of each method:
a) holds a reference to the currently processed object
i = 5
while i>0:
i = i//2
if i % 2 = 0:
break
else:
i+=1
print(i)
should be:
i % 2 == 0
i = 9
i =+ 2
What does i equal?
2
as i = +2
just means i equals positive 2
to add you need +=
for i in range(1,3):
print(‘ * ‘,end=’’)
else:
print(‘ * ‘)
Star star star
* * *
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?
<generator object f at 0x7f53e1f7fc10>
__________________________
NameError as I is not defined
you need to loop through generators
How many stars () does the snippet print?
s = ‘****’
s = s - s[2]
print(s)
Error
strings support concatenation. ‘-‘ is not supported in strings
Which can you do to this tuple: tup = ()
a) tup[:]
b) tup.append(0)
c) tup[0]
d) del tup
a and d
issubclass(B,B)
True
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)
4
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)
Type error as no self parameter in multiplier
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
When will isinstance() error?
When the second argument is not a class
‘a’*0
’’
len(234)
TypeError: object of type ‘int’ has no len()
1//2
0
-1//2
-1
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)
LOOK OUT FOR PRIVATE VARIABLES!!!!!!
CAN ONLY CALL THEM _CLASS__VARIABLE
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
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
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
class A:
def __init__(self):
pass
a = A(1)
print(hasattr(a,’A’))
Output?
Error
__init__ has no argument
class A:
def __init__(self):
pass
a = A()
print(hasattr(a,’A’))
False
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
listy = [x for x in range(5)]
listy = list(filter(lambda x: x-3 and x-1,listy))
[0,2,4]
hasattr(str,’__iter__’)
True
What element can you not iterate through?
integers and floats
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)]
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()()
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())
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)
f = open(‘file.txt’, ‘a+b’)
We opened the file stream in binary, to be appended and updated
What is the difference between a and + ?
updating is updating/changing existing data
a is just adding data
- 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 - Do we want to change its contents?
## NO: We don’t need to add anything (DEFAULT)
## YES: + (update) – changing data - How do we want to read it?
## b = binary format
## t = text format (DEFAULT)
We opened the file stream in binary, to write, read or update?
‘w+b’
a = [1]
b=a[:]
a[0]=0
b?
1
This works for LISTS
a = [1]
b=a
a[0]=0
b?
0
This works for LISTS
Can you do this ‘python’.sort()?
NOOOOOOOOOO
sort() is for lists
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’]
‘python’.index(‘th’)
2
sorted(‘python’)
[‘h’, ‘n’, ‘o’, ‘p’, ‘t’, ‘y’]
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()
Second argument of hassatr is a ….
string
Second argument of isinstance is
class variable name (not a string)
l =[0,1,2,3]
l[:3]
[0,1,2]
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
val = ‘2’ or 1
val *= 3
print(val)
‘222’
val = 1 or ‘2’
val *= 3
print(val)
3
num = 12
num2 = num
num = num + 1
print(num2)
12
Integer
Bytes are immutable
Slicing a bytes object returns a bytes object
class A:
A=1
def __init__(self):
self.a = 0
print(hasattr(A,’a’))
False
’’ in ‘ ‘
True
not []
True
not ‘’
True
not 0
True
class Class_A:
def __init__(self,var):
return var
obj = Class_A(20)
print(obj)
Error
__init__ cannot return a value
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
turning a dictionary into a list…
creates a list of the keys
cannot change back
i = ‘ ‘
for i in ‘ ‘:
print(‘python’,end=i)
pythonpythonpythonpythonpythonpython
for i in ‘number of spaces’
i = ‘ ‘
while i in ‘ ‘:
print(‘python’,end=i)
pythonpythonpythonpythonpythonpython………………..infinte
while creates infinite loop
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
li = [1,2,3,4,5,6]
li[-100:]
[1,2,3,4,5,6]
int(‘100’,2)
int(‘0b100’,2)
4
base 2 so binary 100
first argument has to be string
{2+3}*5
Error
cant multiply set
(2+3,)*5
(5, 5, 5, 5, 5)
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
from math import *
dir(math)
Name Error
we have not imported math, we have imported maths contents
What does Python Standard Library contain?
Storage space for the base Python packages and types
Print(True or False)
True
Print(True and False)
False
l = [[c for c in range(r)] for r in range(3)]
[[], [0], [0, 1]]