Makaut - Question Bank
Makaut - Question Bank
Think of a frozen binary as a self-contained package for your Python app. It bundles everything it needs to run—the
Python engine, your app's code, and any extra tools—into a single, neat file. This means users can simply download
and run your app, with no extra setup needed!
.
In Python, how is memory managed? 6
Steps in managing memory in Python are –
The Python memory is primarily managed by Python Private Heap Space.
All Python objects and data structures are located in a private heap.
The programmer does not have access to this private heap and interpreter takes care of this
Python private heap.
The allocation of Python heap space for python objects is done by Python memory manager.
The core API gives access to some tools for the programmer to code.
Python has an inbuilt garbage collector, that recycles all the unused memory and frees the
memory and makes it available to the heap space.
What is Python virtual machine? 5
The Python Virtual Machine, often referred to as the Python interpreter, is responsible for executing
Python code. It serves as an abstraction layer between the Python bytecode and the underlying hardware,
providing a consistent environment for running Python programs across different platforms. The Python
VM is implemented in CPython, the reference implementation of Python.
Module 2:
What will be the output of the following expression ?
Print(True+10)
Ans 11
A Python variable is a reserved memory location to store values.Every value in Python has a datatype. Different data
types in Python are Numbers, List, Tuple, Strings, Dictionary, etc.
x, y, z = 10,20,30
x = y = z = 10
Ans. 12345
Write a Program to print its digits in reverse order. The input is to be taken by user.
num = 1234
rev = 0
while num != 0:
digit = num % 10
rev = rev * 10 + digit
num //= 10
print("Reversed Number: " + str(rev))
Write an interactive ‘Python’ program to evaluate the series: 1 – 1/2 + 1/3 – 1/4 …±1/n, where n is
entered from keyboard.
n=int(input("Enter the number of terms: "))
sum1=0
for i in range(1,n+1):
sum1=sum1+(1/i)
print("The sum of series is", sum1)
What are the disadvantages of nested if-else statement?
if-else statements can become nested and complex, making the code harder to read and maintain.
Additionally, if-else statements can lead to code duplication if the same logic needs to be repeated in
multiple places.
Write a program which asks the user a number between 1 and 7 and prints the corresponding day of the
week. (1: Sunday, 2: Monday, …)
num = int(input("Enter any no. from 1 to 7 to display day of the week : "))
if num == 1:
print('Sunday')
elif num == 2:
print('Monday')
elif num == 3:
print('Tuesday')
elif num == 4:
print('Wednesday')
elif num == 5:
print('Thursday')
elif num == 6:
print('Friday')
elif num == 7:
print('Saturday')
else:
print('Invalid number !')
Write a program which asks for a integer from the user. It reverses the integer and prints “same” if after
reversal the number is same as old number otherwise it prints “not same”.
n=int(input(“Enter a number”))
m=n
s=0
while(n!=0)
r=n%10
s=s*10+r
n=n//10
if s==m:
print(“Same”)
else:
print(“Not same”)
Write a program to print all the Krishnamurti number from 1 to n. Here, n is user dependent. A
Krishnamurti number is a number whose sum of factorial of individual digits equals the number. For
example, 145 = 1! + 4! + 5! = 1 + 24+ 120 = 145.
def factorial(n) :
fact = 1
while (n != 0) :
fact = fact * n
n=n-1
return fact
# Driver code
n = 145
if (isKrishnamurthy(n)) :
print("YES")
else :
print("NO")
factorial = 1
n=5
if n > 1:
for i in range(2, int(n/2)+1):
if (n % i) == 0:
print(num, "is not a prime number")
break
else:
print(n, "is a prime number")
# If the number is less than 1, its also not a prime number.
else:
print(n, "is not a prime number")
What is the use of break, continue and pass statement in Python.
In Python, the break statement allows you to exit out of a loop when an external condition is triggered.
You’ll put the break statement within the code block under your loop statement, usually after a
conditional if statement.
The continue statement allows you to skip over the part of a loop where an external condition is triggered,
but to go on to complete the rest of the loop. The current iteration of the loop will be disrupted, but the
program will return to the top of the loop.
The continue statement will be within the code block under the loop statement, usually after a
conditional if statement.
When an external condition is triggered, the pass statement allows you to handle the condition without the
loop being impacted in any way; all of the code will continue to be read unless a break or other statement
occurs.
Explain what is range() function and how it is used in for loop?
he range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number.
Example
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
Module 4
How can you concatenate two strings in Python?
+
What is the output of the following Python code snippet?
string = "Hello, World!"
print(string[1:-1])
ello, World
Which method is used to find the index of the first occurrence of a substring in a string in Python?
find
What is the output of the following Python code snippet?
string = "Hello, World!"
print(string.replace("World", "Python"))
Hello, Python!
What will be the output? (1+1+3=5)
a) Select the correct output of the following String operations
Slicing in Python
Slicing is the process of accessing a sub-sequence of a sequence by specifying a starting and ending
index. In Python, you perform slicing using the colon : operator. The syntax for slicing is as follows:
sequence[start_index:end_index]
where start_index is the index of the first element in the sub-sequence and end_index is the index of the
last element in the sub-sequence (excluding the element at the end_index). To slice a sequence, you can
use square brackets [] with the start and end indices separated by a colon.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Write a program that takes a string from the user and then count the number of vowels separately.
vowels = set("aeiou")
ip_str = 'Hello, have you tried our tutorial section yet?'
ip_str = ip_str.lower()
count = {}.fromkeys(vowels,0)
for char in ip_str:
if char in count:
count[char] += 1
print(count)
Write a program to input a sentence from the user and prints the words that ends with “th” irrespective
of the case. Also prints the total count of such words
x=input("Enter a string")
x=x.casefold()
y=x.split()
k=0
for t in y:
if t.endswith("th"):
print (t)
k+=1
print(k)
Write a program that takes a string from the user and then check whether the string is palindrome or not
def isPalindrome(s):
return s == s[::-1]
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it was found
index() Searches the string for a specified value and returns the position of where it was found
Write a Python program to count Uppercase, Lowercase, special characters and numeric values in a given
string(without using string method)
str = "abcd 1234$#"
upper_ctr, lower_ctr, number_ctr, special_ctr = 0, 0, 0, 0
for i in range(len(str)):
if str[i] >= 'A' and str[i] <= 'Z':
upper_ctr += 1
elif str[i] >= 'a' and str[i] <= 'z':
lower_ctr += 1
elif str[i] >= '0' and str[i] <= '9':
number_ctr += 1
else:
special_ctr += 1
print(upper_ctr, lower_ctr, number_ctr, special_ctr)
Write a Python program to find the longest word in a sentence.
def longest_word(input_string):
words = input_string.split()
return max(words, key=len)
print(longest_word("It is a house"))
Module 5
What is the output of the following program ?
def myfunc(a) :
a=a+2
a=a*2
return a
print (myfunc(2))
Ans. 8
Python supports the creation of anonymous functions at runtime, using a construct called __________.
Ans lambda
What will be the output of the following Python code ?
def power(x, y=2):
r=1
for i in range(y):
r=r*x
return r
print (power(3))
print (power(3,3))
Ans 9 27
Predict and explain the output of following program 5
r=lambda q:q*2
s=lambda q:q*3
x=2
x=r(x)
x=s(x)
x=r(x)
print(x)
Ans 24
Write a recursive function to find the factorial of a number.
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
What is function? Explain the different type of arguments in functions with examples.
Python Functions is a block of statements that return the specific task. The idea is to put some commonly
or repeatedly done tasks together and make a function so that instead of writing the same code again and
again for different inputs, we can do the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
Increase Code Readability
Increase Code Reusability
Function arguments are values passed to a function when it is called. On the other hand, parameters are
the variables inside the function's parentheses. There are four types of function arguments in
Python: required arguments, default arguments, keyword arguments, and arbitrary arguments.
Differentiate between local and global variables in python with the help of a program
Exists only during the function’s Remains in memory for the duration
Lifetime
execution. of the program.
A lambda function is an anonymous function (i.e., defined without a name) that can take any number of
arguments but, unlike normal functions, evaluates and returns only one expression.
Note that, unlike a normal function, we don't surround the parameters of a lambda function with
parentheses. If a lambda function takes two or more parameters, we list them with a comma.
We use a lambda function to evaluate only one short expression (ideally, a single-line) and only once,
meaning that we aren't going to apply this function later. Usually, we pass a lambda function as an
argument to a higher-order function (the one that takes in other functions as arguments), such as Python
built-in functions like filter(), map(), or reduce().
Python *args
As in the above example we are not sure about the number of arguments that can be passed to a function. Python has
*args which allow us to pass the variable number of non keyword arguments to function.
In the function, we should use an asterisk * before the parameter name to pass variable length arguments.The
arguments are passed as a tuple and these passed arguments make tuple inside the function with same name as the
parameter excluding asterisk *.
def adder(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:",sum)
adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6)
Python **kwargs
Python passes variable length non keyword argument to function using *args but we cannot use this to pass keyword
argument. For this problem Python has got a solution called **kwargs, it allows us to pass the variable length of
keyword arguments to the function.
In the function, we use the double asterisk ** before the parameter name to denote this type of argument. The
arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the
parameter excluding double asterisk **.
def intro(**data):
print("\nData type of argument:",type(data))
Module 6
What data type is the object below ?
L=[1, 23, 'hello', 1]
Ans list
What is the output of the following Python code snippet?
my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
Ans [3,4]
What will be the output of the following Python code ?
list1 = [1, 3]
list2 = list1
list1[0] = 4
print(list2)
Ans [4,3]
What is the output of the following code snippet ?
print([i.lower() for i in "HELLO"])
Ans ['h', 'e', 'l', 'l', 'o']
Which function is used to add an element (5) in the list1 ?
Ans list1.append(5)
What is the output of the following ?
print(max([1, 2, 3, 4], [4, 5, 6], [7]))
Ans [7]
What is the output of the following code ?
M=[‘a’ * x for x in range(4)]
print(M)
Ans. ['', 'a', 'aa', 'aaa']
What will be the output of the following Python code snippet?
my_list = [1, 2, 3, 4, 5]
my_list.pop(2)
print(my_list)
Ans [1,2,4,5]
Assume a list L1=[12,5,7,80,33,65]
a. Remove the element 80
b. Add 120 at the end of the existing list
c. Insert 75 at the index 2 of the list L1
d. Print the last element of the list
e. Print the list in sorted order
Ans a) L1.remove(80)
b) L1.append(120)
c) L1.insert(2,75)
d) print(L1[-1])
e) print(sorted(L1))
Write a Python program that accepts a list from the user and print all elements of list using for loop
lst = []
Write a Python program that accepts a list from the user and print the smallest and largest number from a
list. 5
lst = []
# number of elements as input
n = int(input("Enter number of elements : "))
print(“Largest”,max(lst))
print(“Smallest”,min(lst))
Write a Python Program to Square Each Element of the List and Print List in Reverse Order. 5
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(len(a)):
a[i]= a[i]**2
print(a[::-1])
Write a Python program to count Even and Odd numbers in a List
list1 = [10, 21, 4, 45, 66, 93, 1]
even_count, odd_count = 0, 0
# iterating each number in list
for num in list1:
# checking condition
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
Write a Python program that accepts word from the user and store in list. Print the word that are
palindrome. 5
def isPalindrome(s):
return s == s[::-1]
s = ["malayalam",”madam”,”abcd”]
for i in s:
ans = isPalindrome(i)
if ans:
print(i)
Write a Python program to count the number of strings from a given list of strings. The string length is 2
or more and the first and last characters are the same.
Sample List:['abc', 'xyz', 'aba', '1221']
Expected Result : 2
def match_words(words):
ctr = 0
for word in words:
if len(word) > 1 and word[0] == word[-1]:
ctr += 1
return ctr
Write a Python function that takes two lists and returns True if they have at least one common
member.
def common_data(list1, list2):
result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result
For a list with simple elements (like integers or strings), you can use the copy() method to create a
shallow copy. However, this does not create a true copy of nested lists.
original_list = [1, 2, 3]
shallow_copy = original_list.copy()
shallow_copy[0] = 99
print(original_list) # Output: [1, 2, 3] (unaffected)
But if the list contains nested lists, changes to the inner lists will affect both the original and the shallow
copy:
original_list = [[1, 2], [3, 4]]
shallow_copy = original_list.copy()
shallow_copy[0][0] = 99
print(original_list) # Output: [[99, 2], [3, 4]] (affected)
Using copy.deepcopy() for Deep Copy:
The copy module provides the deepcopy() function, which creates a true copy of the entire list, including
all nested elements.
import copy
original_list = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(original_list)
deep_copy[0][0] = 99
print(original_list) # Output: [[1, 2], [3, 4]] (unaffected)
With deepcopy(), any modifications to the copied list, including changes to nested lists, do not affect the
original list.
# Check if the character "r" is present in the 'tuplex' tuple and print the result
print("r" in tuplex)
Write a Python program to reverse a tuple.
# Create another tuple containing a sequence of numbers
x = (5, 10, 15, 20)
y = reversed(x)
print(tuple(y))
What is the difference between list and tuple?
The key difference between tuples and lists is that while tuples are immutable objects, lists are mutable.
This means tuples cannot be changed while lists can be modified. Tuples are also more memory efficient
than the lists.
t = (4, 8, 3)
print(t)
# Unpack the values from the tuple into the variables n1, n2, and n3
n1, n2, n3 = t
# Calculate and print the sum of n1, n2, and n3
print(n1 , n2 , n3)
Write a Python program to get the 4th element from the last element of a tuple.
item1 = x[-4]
print(item1)
Write a Python program to remove an item from a tuple.
tuplex = ("w", e, "s", "t", "b", "e", "n", "g", "a","l")
listx = list(tuplex)
# Use the 'remove' method to eliminate the item "e" from the list
listx.remove("e")
# Convert the modified list back to a tuple to obtain 'tuplex' with the item removed
tuplex = tuple(listx)
# Print the final 'tuplex' tuple
print(tuplex)
Module 8
In the dictionary key and value pair which part holds the unique elements only?
Ans key
In the dictionary, which symbol is used to separate key and value pairs?
Ans :
How you make an empty dictionary in Python?
Ans. DICT={}
Ans yes
Which of the following function of dictionary gets all the keys from the dictionary ?
Ans keys()
Which line of code correctly adds an item to the fruits dictionary with a key of ‘grapes’ and a
value of 15?
Ans. fruits['grapes'] = 15
What will be the output of the following code?
D={1:7,2:"everyone"}
print(D[2])
Ans everyone
Apart from indexing which alternative function is used to access the value in dictionary?
Ans get()
dic3 = {}
dic3.update(d)
print(dic3)
Write a Python program to check whether a given key already exists in a dictionary.
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
def is_key_present(x):
if x in d:
print('Key is present in the dictionary')
else:
print('Key is not present in the dictionary')
is_key_present(5)
Write a Python program to iterate through the key-value pairs in the dictionary using a for loop
l1 = [1,2,3]
l2 = ["one","two","three"]
res = {}
for key in test_keys:
for value in test_values:
res[key] = value
print("Resultant dictionary is : " + str(res))
The following are the main differences between a tuple and a dictionary in python.
Tuple Dictionary
A tuple is a non-homogeneous data structure that can Dictionary is a non-homogeneous data structure
hold a single row as well as several rows and columns. that contains key-value pairs.
Tuples are represented by brackets (). Dictionaries are represented by curly brackets {}.
Tuple can be created using tuple() function. Dictionary can be created using the dict() function.
As tuples are immutable, the reverse() method is not Because the dictionary's entries are in the form of
defined in them. key-value pairs, the elements cannot be reversed.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Module 9:
Ravi opened a file in python using open( ) function but forgot to specify the mode. In which mode the file
will open ?
Ans. read
Which statement will move file pointer 10 bytes backward from current position ?
Ans. f.seek(-10,1)
Which statement will return one line from a file (file object is f)?
Ans. f.readline()
What will be the output of the following code ?
f=open("demo.txt","r")
print(f.tell())
Ans 0
Which method is used to check if a file exists in Python?
isfile()
Print a line with line numbers from a file
F1=open(“file1.txt”,”r”)
n=1
for line in F1:
print(str(n)+”:”+line)
n=n+1
F1.close()
Write a program code to open a data file. Save element values 2, 4, 9, 10, 11 in this data file and read the
numbers from file
n = [2,4,9,10,11]
with open('abc.txt', "w") as myfile:
for c in n:
myfile.write("%s\n" % c)
content = open('abc.txt')
print(content.read())
Differentiate between the following : (a) readline() and readlines() (b) tell() and seek()
Here,
offset – Required parameter. Sets the cursor to the specified position and starts reading after that position.
whence – Optional parameter. It is used to set the point of reference to start from which place.
0 – Default. Sets the point of reference at the beginning of the file. Equivalent to os.SEEK_SET.
1 – Sets the point of reference at the current position of the file. Equivalent to os.SEEK_CUR.
2 – Sets the point of reference at the end of the file. Equivalent to os.SEEK_END.
whereas the tell() function returns the position where the cursor is set to begin reading.
Syntax
tell()
Module 10:
-------- and ---------------- are the two main aspects of OOPs
Ans Class, Objects
_____ represents an entity in the real world with its identity and behavior.
Ans. An object
class change:
def __init__(self, x, y, z):
self.a = x + y + z
x = change(1, 2, 3)
y = getattr(x, 'a')
setattr(x, 'a', y + 1)
print(x.a)
Ans 7
Which access specifier in Python indicates that an attribute should not be accessed directly from outside
the class?
Ans. private
What is the process of defining a new class based on an existing class called?
Ans inheritance
What is the purpose of the __init__ method in Python classes?
Ans. The __init__ method is a special method in Python classes used to initialize newly created objects
with initial values.
Which feature of OOPS described the reusability of code?
Ans. Inheritance
In Python, a constructor is a special method called __init__() that is automatically invoked when a new
object of a class is created. It is used to initialize the object's state or set up initial values for its attributes.
class Car:
self.make = make
self.model = model
self.year = year
In Python, instance variables belong to instances of a class, representing the state of individual objects,
while class variables belong to the class itself, representing attributes shared by all instances of the class.
Instance variables are defined within methods using the self keyword and are unique to each instance,
whereas class variables are defined outside methods and are accessed using the class name. Instance
variables are specific to each object, while class variables are common to all objects of the class.
When a copy of a class is created that inherits all the class properties and functions, it is called
instantiating a class. To instantiate a class in Python, the class like it is called a function, passing the
arguments defined by the __init__ method. The newly created object is the return value.
Inheritance is the capability of one class to derive or inherit the properties from another class.
Inheritance allows you to inherit the properties of a class, i.e., base class to another, i.e., derived class.
The benefits of Inheritance in Python are as follows:
It provides the reusability of a code. We don’t have to write the same code again and again. Also, it
allows us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses
of B would automatically inherit from class A.
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
The super() function in Python is used to call methods and access attributes from the superclass (parent
class) within a subclass (child class). It allows subclasses to inherit and leverage behavior from their
superclass, facilitating code reuse and maintaining a clean and organized class hierarchy. By using
super(), developers can invoke superclass methods and constructors, ensuring that all necessary
initialization and functionality from the superclass are properly executed within the subclass.
Write a Python program to create a class representing a Circle. Include methods to calculate its area and
perimeter 10
class Circle:
# Initialize the Circle object with a given radius
def __init__(self, radius):
self.radius = radius
# Calculate and return the area of the circle using the formula: π * r^2
def calculate_circle_area(self):
return 3.1415 * self.radius**2
# Calculate and return the perimeter (circumference) of the circle using the formula: 2π * r
def calculate_circle_perimeter(self):
return 2 * 3.1415 * self.radius
# Example usage
# Prompt the user to input the radius of the circle and convert it to a floating-point number
radius = float(input("Input the radius of the circle: "))
What is Polymorphism?
Polymorphism is a very important concept in programming. It refers to the use of a single type entity