Q1. What will be the output of the following code:
1
len("AILearner")
8
9
10
Error!
Answer: 2 Explanation: In Python language, len() function gives the length of an object. When the object is a string, it will output the number characters in the string.
Answer: 4 Explanation: D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple. But in this question only one argument is given to popitem() method.
Q4. Which of the following statements is not true?
We can change the value of a private variable of superclass in the subclass
Superclass non-private method can be overridden.
The constructor of a class in invoked automatically.
A derived class is a subclass of superclass
Answer: 1 Explanation: We can not change the value of a private variable of superclass in the subclass.
Q5. What type of error will be raised when the imported module is not found?
ImportError
NullPointerError
NameError
IndexNotFoundError
Answer: 1 Explanation: ImportError will be raised when the imported module is not found.
Q6. How does Python treat a string literal when it is not assigned to any variable?
It will ignore the string literal.
It will automatically assings a variable to it.
It will through an error.
None of the above.
Answer: 1 Explanation: In Python language, if you do not assign a string literal to a variable, it will ignore the string literal while in other languages like Java it will throw a compile time error.
Q7. In Python, which of the following variable is not of a integer data type?
x = 435757438
x = 5
x = 23.45
x = -5
Answer: 3 Explanation: Int is a whole number, it can be either positive or negative. It can not have decimal values also it can be of unlimited length.
Q8. Which of the following statement will extract the percentage of the mentioned student?
Answer: 2 Explanation: json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. json.loads() in Python => print(data[‘School’][‘student’][‘result’][‘percentage’]) => 70%
Special method __add()__ is called when + operator is used.
In Python, same operator may behave differently depending upon operands.
__init__() function is called when a new object is instantiated.
All of the above
Answer: 4 Explanation: All of the given three options are correct.
Q2. In Python, which of the following statement will print a random number between 1 and 10 (both 1 and 10 included)?
print(random.randrange(1, 10))
print(random.random(1, 10))
print(random.randint(1, 10))
None of the above.
Answer: 3 Explanation: 1. print(random.randrange(1, 10)) -> This will print a random integer between 1 and 10 where 10 is not included. 2. print(random.random(1, 10)) -> This will throw an error because random does not take any argument but two are given. 3. print(random.randint(1, 10)) -> This will print a random number between 1 and 10 (both 1 and 10 included).
Q3. Which of the following is not true of global variable in Python?
global keyword can be used to create a global variable inside a local scope.
Accessible only in the block they are defined in.
A variable created in the main body of the Python code is a global variable.
Accessible from anywhere in the script.
Answer: 2 Explanation: Global variables are available from within any scope, either it is global or local.
Q4. If x = 2**4/2+3-1, then what will be the data type of x?
int
float
Answer: 2 Explanation: Division operator is used in x = 2**4/2+3-1 and division operator gives the value including the decimals which will be of float data type.
Q5. Which of the following method can be used to combine strings and numbers?
concatenate()
join()
append()
format()
Answer: 4 Explanation: The format() method format the passed arguments and places them in the string according to the placeholders {}. Fancier Output Formatting
Q6. Suppose x = 6.3, then which of the following statement will throw an error?
y = float(x)
y = int(x)
y = complex(x)
None of the above.
Answer: 4 Explanation: int, float and complex are numeric data types. These will cast ‘x’ into it’s respective data types.
Q7. What will be the output of print(ord(‘the’))?
116 104 101
116 116 116
104 104 104
TypeError
Answer: 4 Explanation: Python ord() function returns the Unicode code from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. Reference: ord() function in Python
Q8. In Python, which of the following character is used to add at the start of a line to make it a comment?
#
“
//
&
Answer: 1 Explanation: In Python language comments start with # and the rest of the line will be rendered as comment.
string="The current world population is 7.9 billion as of December 2021"
y=[xforxin(xforxinstringifx.isdigit())]
print(y)
[7, 9, 2, 0, 2, 1]
[‘7’, ‘9’, ‘2’, ‘0’, ‘2’, ‘1’]
[7, 2, 0, 2, 1]
Runtime error!
Answer: 2 Explanation: This is an example of list comprehension in Python. List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. List Comprehensions
Q2. What are the name of the operators |, &, >> and << respectively?
AND, OR, RIGHT SHIFT and LEFT SHIFT
AND, OR, LEFT SHIFT and RIGHT SHIFT
OR, AND, LEFT SHIFT and RIGHT SHIFT
OR, AND, RIGHT SHIFT and LEFT SHIFT
Answer: 4 Explanation: OR, AND, RIGHT SHIFT and LEFT SHIFT are name of the |, &, >> and << operators respectively.
Q3. What will be the output of following code:/code/
1
2
3
4
a=[1,2]
b=a
b+=[3,4]
print(a,b)
[1, 2] [1, 2, 3, 4]
[1, 2, 3, 4] [1, 2, 3, 4]
[1, 2, 3, 4] [1, 2]
[1, 2] [3, 4]
Answer: 2 Explanation: In Python language, assigning one variable to another variable creates an alias of each variable. Here variable b is an alias of variable a. It means both variable a and b points to the same object in the memory. That’s why when you are updating the value of variable b, value of variable a is also changing.
Q4. Python is an object oriented programming language.
True
False
Answer: 1 Explanation: Python is an object oriented programming language. Almost everything in Python is an object. A class in Python is a blueprint for creating objects.
Q5. What will be the output of following code:
1
2
3
num=(1,2,3,4,5)
(a,b,*c)=num
print(a,b,c)
1 2 (3, 4, 5)
1 2 3
1 2 [3, 4, 5]
ValueError
Answer: 3 Explanation: *variable is basically extended iterable unpacking. It will assign a list of all items not assigned to a regular variable name. So from tuple “num”, 1 is assinged to a, 2 is assigned to b and rest all items will be assigend as list to c. Extended Iterable Unpacking
Q6. Which of the following statement is the correct way of assigning an integer value to a variable in Python?
x = ‘6’
int x = 6;
x = 6
Integer x = 6;
Answer: 3 Explanation: x = ‘6’ -> will create a string data type. int x = 6; and Integer x = 6; -> It is a way of assignment and declaration in Java language.
In Python there is no need to declare the data type using int or Integer. It will create a variable with respect to the type of data you assing to it.
Q7. What is the syntax for multiline comment in Python?
Use /* at the start of the first line and use */ at the end of the last line.
Use <-- at the start of the first line and use --> at the end of the last line.
Python does not have syntax for multiline comment. You can either use # at the start of every line or make it as multiline string (triple quote).
None of the above.
Answer: 3 Explanation: Since Python does not have syntax for multiline comments, there is a workaround. As Python ignores the string literal if it is not assigned to a variable, we can add multiline string in our code and place the multiline comment inside it.
Q8. What will be the output of following code:
1
2
3
4
5
6
7
8
i=1
whilei<5:
print(i,end=" ")
i+=1
ifi==4:
break
else:
print(i+1)
1 2 3
1 2 3 4
1 2 3 5
1 2 3 4 5
Answer: 1 Explanation: while loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed. The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed. Reference: While Loop
Q1. if x = [1, 2, 5, 3, 4], what will be the output of print(x[0:3:2])?
[1, 5, 4]
[1, 5]
[1, 2, 5, 3, 4]
List index out of range exception!
Answer: 2 Explanation: Slice in Python list here refer to list[::]. So x[0:3:2] will start at index 0, stop at index 3 at take a step of 2.
Q2. What is the difference between a method and a function in Python?
Functions can be called only by its name but methods can not be called by its name only.
we don’t need a class to define a function but methods are defined inside a class.
Functions are independent entities in a program while methods are dependent on the class they belong to.
All of the above.
Answer: 4 Explanation: All the given three options are correct.
Q3. What will be the output of following code:
1
2
3
x=[10,20,30,40]
x+=[10]
print(x)
[20, 30, 40, 50]
[10, 20, 30, 40, 10]
Answer: 2 Explanation: In Python language, + operator append the elements to the original array.
Q4. What will be the output of following code:
1
2
3
def fun(x=3,y):
print(x,y)
fun(2)
3 2
2 2
2 3
SyntaxError
Answer: 4 Explanation: It will raise an error. In function definition, non-default arguments should be written before the default arguments.
Q5. Which of the following is true when you open a file using with keyword?
File reading and writing are faster using the with statement.
The file is automatically closed after leaving the block, and all the resources that are tied up with the file are released.
You need not to handle exception anymore in the whole script.
Answer: 2 Explanation: When you open a file using with keyword, the file is automatically closed after leaving the block, and all the resources that are tied up with the file are released.
Q6. A class can serve as base class for many derived classes.
True
False
Answer: 1 Explanation: yes a class can serve as base class for many derived classes. It is also call as Hierarchical inheritance.
Q7. The following code will throw an error.
1
2
3
def fun(**x):
print(x[a])
fun(a=1,b=2,c=3)
True
False
Answer: 1 Explanation: **kwargs are used as arbitrary keyword arguments. If we do not know how many keyword arguments that will be passed into our function then we can add two asterisk ** before the parameter name in the function definition. In the given function definition x will be a dictinary of arguments. That’s why print(x[a]) will raise an error.
Q8. Which of the following statement will create a variable of string type?
a = ”’AILearner”’
a = “AILearner”
a = ‘AILearner’
All of the above.
Answer: 4 Explanation: In Python language, a string can be created by using any of the single, double or triple quotation marks. Usually three quotes are used to create a multiline string.
Q1. In Python, which of the following is the super class of all created classes?
Super class
Object class
Integer class
Base class
Answer: 2 Explanation: Object class is the super class of all created classes.
Q2. What will be the output of following code:
1
2
3
4
x=[1,2,3]
y=x
y.pop()
print(x,y)
[1, 2] [1, 2, 3]
[1, 2, 3] [1, 2]
[1, 2, 3] [1, 2, 3]
[1, 2] [1, 2]
Answer: 4 Explanation: pop(index) method remove the item of a list at specified index. If index is not specified it will remove the first element of the list. Also as x is assigned to variable y and both refer to the same object in the memory, value of x and y will be same.
Q3. What will be the output of following code:
1
2
3
4
5
x={1:'a',2:'b',3:'c'}
delx[1]
x[1]=5
delx[2]
print(len(x))
2
1
4
3
Answer: 1 Explanation: del x[1] => x = {2: ‘b’, 3: ‘c’} x[1] = 5 => x = {2: ‘b’, 3: ‘c’, 1: 5} del x[2] => x = {3: ‘c’, 1: 5}
Q4. What will be the output of following code:
1
2
3
4
5
6
def func(**kwargs):
print(type(kwargs),end=" ")
foriinkwargs:
print(i,end=" ")
func(x=1,y=2)
x y
1 2
x y
1 2
Answer: 3 Explanation: **kwargs are used as arbitrary keyword arguments. If we do not know how many keyword arguments that will be passed into our function then we can add two asterisk ** before the parameter name in the function definition. Arbitrary Keyword Arguments (**kwargs) make the way for the function to receive the dictionary of arguments.
Q5. In Python, which of the following is a numeric data type?
int
float
complex
All of the above.
Answer: 4 Explanation: In Python language, there are three types of numeric data. 1. int (Example : 0, 2, -1, etc.) 2.float (Example : 0.0, 2.3, -1.5, etc.) 3.complex(Example : 0j, 2j, -1.5j, etc.)
Q6. What will be the output of following code:
1
2
3
x1={1,2,3}
x2=x1.add(4)
print(x1,x2)
{1, 2, 3} {1, 2, 3, 4}
{1, 2, 3, 4} None
{1, 2, 3, 4} {1, 2, 3, 4}
Error
Answer: 2 Explanation: add() method does not return any value, that’s why x2 will be None.
Q7. What will be the output of following code”
1
2
3
4
5
foriinrange(5):
with open("a.txt","r")asfile:
ifi>2:
break
print(file.closed,i)
False 5
True 5
False 3
True 3
Answer: 4 Explanation: When you open a file using with keyword, the file is automatically closed after leaving the block, and all the resources that are tied up with the file are released.
Q8. What is the difference between a global variable and a local variable?
Global variable can be used inside a function only while local variable can be used both inside and outside the function.
Local variable can be used inside a function only while global variable can be used both inside and outside the function.
Both are same.
Both are different name for same variables.
Answer: 2 Explanation: As stated, Local variable can be used inside a function only while global variable can be used both inside and outside the function.
Answer: 3 Explanation: To build a class/object as an iterator, we need the methods __iter__() and __next__(). The __next__() method return the next item in the sequence. myiter = iter(a) => Creates an iterator. next(myiter) will execute the __next__() method of class A. Python Iterators
Q2. The following code will throw an error.
1
2
3
4
def fun(*x):
print(x[2])
fun("a","b","c")
True
False
Answer: 2 Explanation: *args are used as arbitrary Arguments. If we do not know how many arguments that will be passed into our function then we can add a * before the parameter name in the function definition.
Q3. What will be the output of following code:
1
print(len(" TheAI "),len(" TheAI ".strip()))
8 5
8 6
7 6
7 5
Answer: 4 Explanation: strip() method removes any leading and trailing characters from a string.
Q4. What will be the output of following code:
1
print(('AILearner')*3)
(‘AILearner’,’AILearner’,’AILearner’)
AILearnerAILearnerAILearner
(‘AILearner3’)
Error
Answer: 2 Explanation: Here, * operator will multiply the content of string ‘AILearner’ 3 times.
Q5. What will be the output of following code:
1
2
3
4
5
classLanguage:
def get_lang(self,line='Python'):
print(line)
obj=Language()
obj.get_lang('Java')
Python
Java
Java Python
Python Java
Answer: 2 Explanation: Java is the correct answer.
Q6. What will be the output of following code:
1
2
3
x=[1,2]
x[3:4]=[3]
print(x)
[1, 2, 3]
[1, 3]
[1, 2]
Throws an error!
Answer: 1 Explanation: As the len(x) = 2, x[3:4] will add the data at the end of the list. Extending a list in Python
Q7. Which of the following data types can have only two values (either True or False)?
integer
Strings
Boolean
Float
Answer: 3 Explanation: Booleans can only have one of two values: True of False.
Q8. What will be the output of print(2 * 3 ** 3 * 2)?
108
432
1458
36
Answer: 1 Explanation: ** is a power operator and it has higher precedence than * multiplication operator. So the equation will be solved as follows: => 2 * 3 ** 3 * 2 => 2 * 27 * 2 => 54 * 2 => 108
Q1. Which of the following statement will read entire content of a text file as string?
txtfile = open(‘a.txt’, ‘r’) txtfile.read()
txtfile = open(‘a.txt’, ‘r’) txtfile.readline()
txtfile = open(‘a.txt’, ‘r’) txtfile.readlines()
txtfile = open(‘a.txt’, ‘r’) txtfile.reads()
Answer: 1 Explanation: txtfile.read() Read at most n characters from stream. This method will read from underlying buffer until we have n characters or we hit End of file. If n is negative or omitted, read until End of file.
Q2. Which of the following creates iterable elements?
continue
range
break
pass
Answer: 2 Explanation: range(stop) -> range object range(start, stop[, step]) -> range object Return an object that produces a sequence of integers from start (inclusive)to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).
Q3. Which of the following is default mode in open() function?
‘a’ – append
‘w’ – write
‘r’ – read
‘x’ – create
Answer: 3 Explanation: ‘r’ => open for reading (default).
Q4. In s1 = “theai” and s2 = “learner”. Output of the print(2*s1[:2]+s2) will be:
Q6. In Python, which of the following rule is used to decide the order in which the namespaces are to be searched for scope resolution?
LEGB rule (Local, Enclosed, General, Built-in)
LEGB rule (Local, Enclosed, Global, Built-in)
ELGB rule (Enclosed, Local, Global, Built-in)
ELGB rule (Enclosed, Local, Genral, Built-in)
Answer: 1 Explanation: Since x1 and x2 refers to the same object in the memory, adding the items in the x2 will also add items in x1.
Q8. if x = [2, 4, 6, 8], which of the following operation will change x to [2, 4, 8]?
del x[2]
x.remove(6)
x[2:3] = []
All of the above!
Answer: 4 Explanation: del x[2] => will delete the item at index 2. x.remove(6) => will remove the first occurance of value 6. x[2:3] = [] => will replace the value at index 2 to nothing.
Answer: 3 Explanation: continue keyword will skip the rest of the statements after it in the loop and make the loop to run for the next iteration.
Q2. What will be the output of following code:
1
2
3
4
5
6
7
def func(x,y=2,z=3):
def in_fun(a,b):
x=a+b
returnx
returnx+in_fun(y,z)
print(func(3,6))
18
12
9
Error
Answer: 2 Explanation: function which is defined inside another function is known as inner function or nested function. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. This process is also known as Encapsulation. Reference: Inner Functions Default arguments in Python
Q3. What are the dunder(magic) methods in Python?
Methods that start with single underscore.
Methods that start with double underscore and ends with double underscore.
Methods that start with double underscore.
Methods that ends with single underscore.
Answer: 2 Explanation: Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc. Reference: Dunder or magic methods in Python
Q4. Which of the following option gives the value of rating2 from the code?
Answer: 3 Explanation: A function which is defined inside another function is known as inner function or nested function. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. This process is also known as Encapsulation. Reference: Inner Functions
Q2. Which of the following function is used inside a for loop in Python?
Answer: 2 Explanation: If “if” condition is not True then only “elif” condition will execute.
Q4. What will be the output of following code:
1
2
x=("a",2,3,2,2.3,[1,2,3])
print(len(x))
5
8
6
TypeError!
Answer: 3 Explanation: len() function gives the length of the tuple.
Q5. Which of the following statement will return False?
bool(-1)
bool(1)
bool(0)
bool(12E5)
Answer: 3 Explanation: Any number is True, except 0.
Q6. Which of the following brackets can be used to create lists in Python?
[]
{}
()
<>
Answer: 1 Explanation: list1 = [] will create a list in Python.
Q7. In Python, what is the correct way of casting an integer value to a string?
x = str(6)
x = Integer.toString(6);
Both of the above.
None of the above.
Answer: 1 Explanation: In Python language, you can cast an integer to a string by using ‘str’ keyword.
Q8. What will be the output of following code:
1
"TheAILearner".count("a",0,5)
0
1
2
Throws an error!
Answer: 1 Explanation: count() method returns the number of times a specified value occurs in a string. “a” occurs one time in “”TheAILearner”. But in count method start (0) and end (5) index of the string is given where it will search for “a”.
Q1. Which of the following is true for a lambda function in Python?
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Lambda functions are used for functional programming.
All of the above.
Answer: 4 Explanation: All of the statements regarding the Python lambda functions are correct.
Q2. Which of the following is the recommended way to ensure that a file object is properly closed after usage?
Use close() function after the use of file object.
Use try/finally block
Use with statement
All of the above.
Answer: 3 Explanation: When you open a file using with keyword, the file is automatically closed after leaving the block, and all the resources that are tied up with the file are released.
Answer: 3 Explanation: sys.getsizeof(object, default) return the size of object in bytes.
Q4. Which of the following list assignment in Python will throw an exception?
x = [1, 2, ‘python’]
x = [1, 2, [1, 2]]
x = [‘a’, ‘b’, ‘c’, ‘a’, ‘4.5’, int(3.4)]
None of the above.
Answer: 4 Explanation: in Python language, list items can be of any data types and also a list can contain different data types.
Q5. What will be the output of following code:
1
2
x=("TheAILearner")
print(type(x))
<class ‘tuple’>
<class ‘str’>
<class ‘list’>
<class ‘int’>
Answer: 2 Explanation: To create a tuple with single item, we need to add comma(,) at the end of the item.
Q6. If str = “AILearner”, what will be the output of print(str == ‘AILearner’, str is “AILearner”)?
False False
True False
False True
True True
Answer: 4 Explanation: In Python language, “is” keyword is used to test if the two variables refers to the same object.
Q7. What will be the output of print(13//2)?
6.5
6
7
Throws an error.
Answer: 2 Explanation: In Python language, // is a floor division operator. This operator will divide the two numbers and round up it to the previous lower integer.
Q8. What will be the output of following code:
1
2
x=(1120,'a',-1120)
print(max(x))
1120
‘a’
-1120
TypeError
Answer: 4 Explanation: max() does not support comparison between instances of ‘str’ and ‘int’.