Python Programs
Python Programs
class Acc:
def __init__(self, id):
self.id = id
id = 555
acc = Acc(111)
print(acc.id)
Explanation: Instantiation of the class “Acc” automatically calls the method __init__
and passes the object as the self parameter. 111 is assigned to data attribute of the
object called id.
The value “555” is not retained in the object as it is not assigned to a data attribute of
the class/object. So, the output of the program is “111”
Program 9: Which of the options below could possibly be the output of the following
program?
from random import randrange
L = list()
for x in range(5):
L.append(randrange(0, 100, 2)-10)
# Choose which of outputs below are valid for this code.
print(L)
a) [-8, 88, 8, 58, 0]
b) [-8, 81, 18, 46, 0]
c) [-7, 88, 8, 58, 0]
d) [-8, 88, 94, 58, 0]
Ans. (a)
Explanation: The for loop will result in appending 5 elements to list L. Range of the
elements lies from [0, 98] – 10 = [-10, 88], which rules out option (d). The upper range is
98 because the step size is 2, thus option (c) and (b) are invalid. Also, note that each time
you may not get the same output or the one in the options as the function is random.
Program 13: Which of the options below could possibly be the output of the following
program?
import math
import random
L = [1, 2, 30000000000000]
for x in range(3):
L[x] = math.sqrt(L[x])
# random.choices() is available on Python 3.6.1 only.
string = random.choices(["apple", "carrot", "pineapple"], L, k = 1)
print(string)
a) [‘pineapple’]
b) [‘apple’]
c) ‘pineapple’
d) both a and b
Ans. (d)
Explanation: Two modules math and random are used, L after the for loop will be [1.0,
1.4142135623730951, 5477225.575051662]. choices() has a choice as 1st parameter and
their weights as the second parameter, k is the number valued needed from choice. The
answer will come out to ‘pineapple’ almost always due to its the weight but ‘apple’ and
‘carrot’ may turn out to be the output at times.
Program 16: Which of the options below could possibly be the output of the following
program?
D = {1 : [1, 2, 3], 2: (4, 6, 8)}
D[1].append(4)
print(D[1], end = " ")
L = list(D[2])
L.append(10)
D[2] = tuple(L)
print(D[2])
a) [1, 2, 3, 4] [4, 6, 8, 10]
b) [1, 2, 3] (4, 6, 8)
c) ‘[1, 2, 3, 4] TypeError: tuples are immutable
d) [1, 2, 3, 4] (4, 6, 8, 10)
Ans. (d)
Explanation: In the first part key-value indexing is used and 4 is appended into the list.
As tuples are immutable, in the second part the tuple is converted into a list, valued 10
is added and then converted back to list.