Python Interview Questions(100)
Python Interview Questions(100)
5//2 = 2
5/2 = 2.5
13. Can you name the two primary loop statements in Python?
Answer: The two major loop statements in Python are “for” and “while.”
The “for” loop iterates over a sequence, such as a list or range, while the
“while” loop continues executing as long as a specified condition remains
true. These loops are fundamental for repetitive tasks and control flow in
Python programs.
14. Can you define modules in Python?
Answer: Modules in Python are organizational units that group related
code together. They consist of Python files containing functions, classes,
and variables. Modules provide a way to organize and reuse code,
promoting modularity. They can be imported into other Python scripts,
enhancing code maintainability and readability.
import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
Check out a list of all the TCS interview questions with answers and
impress your recruiters with ease.
29. Can you explain the location of source files, such as math.py,
socket.py, and regex.py, within the Python standard library?
Answer: The source files for standard Python modules like math.py,
socket.py, and regex.py are part of the Python standard library. They are
typically located in the Lib directory of the Python installation. Users can
access and explore these files to understand the implementation details of
the corresponding modules.
31. Can a Python class inherit from more than one parent class?
Answer: Yes, a Python class can inherit from more than one parent class,
thereby supporting multiple inheritance. It can be achieved by listing
multiple parent classes in the class definition.
34. Can you describe the split(), sub(), and subn() methods found
within Python’s ‘re’ module?
Answer: The re-module in Python provides several methods for working
with regular expressions. Here’s a description of the split(), sub(), and
subn() methods:
split() Method: The split() method is used to split a string into a list based
on a specified regular expression pattern. It takes the pattern as an
argument and returns a list of substrings.
sub() Method: The sub() method is used for replacing occurrences of a
pattern in a string with a specified replacement. It takes three arguments:
the pattern to search for, the replacement string, and the input string.
subn() Method: The subn() method is similar to sub(), but it returns a tuple
containing the modified string and the number of substitutions made.
The __iter__() method returns the iterator object itself and is called when
an iterator is initialized.
The __next__() method returns the next element in the sequence and is
called for each subsequent iteration. When there are no more elements, it
raises the StopIteration exception.
39. What is the purpose of the “is”, “not” and “in” operators?
Answer: In Python, the “is” operator, the “not” operator, and the “in”
operator serve different purposes:
“is” Operator: The “is” operator in Python is used for identity comparison.
It checks if two objects refer to the same memory location, determining if
they are the same object.
“not” Operator: The “not” operator is a logical operator in Python used for
negation. It returns True if the operand is False, and vice versa. It negates
the truth value of the given expression.
“in” Operator: The “in” operator is used to test membership. It checks if a
specified value exists in a sequence (like a string, list, or tuple), returning
True if the value is present and False otherwise.
def reverse_string(input_string):
return input_string[::-1]
# Example
original_string = "Hello, World!"
reversed_string = reverse_string(original_string)
x=5 # integer
x = 'hello' # string
x = [1, 2, 3] # list
Here, x dynamically changes its type as it is assigned different values.
This flexibility simplifies code but requires careful consideration to avoid
unexpected behavior.
try:
result = 10 / 0
except ZeroDivisionError:
print("Can't divide by zero")
You can also include an optional else block after the except block, which
will be executed if no exception was raised in the try block.
You can catch multiple exceptions in one except block using parentheses,
like this:
try:
result = 10 / 0
except (ZeroDivisionError, TypeError):
print("An error occurred")
In Python, it’s also possible to raise an exception manually using the raise
statement.
Examples:
Input: [1, 1, 2, 2, 2]
Output: [1,2]
Input: [1, 2, 3, 1, 2, 4, 5, 6, 5]
Output: [1, 2, 3, 4, 5, 6]
Answer – You can remove duplicate elements from a list in Python using
the set data structure, which only stores unique elements. Here’s the
python code for this:
Python
numbers = [1, 1, 2, 2, 2]
unique_numbers = set(numbers)
unique_numbers = list(unique_numbers)
print(unique_numbers)
Output:
[1,2]
Another way to remove duplicates from a list is to use a loop and check if
an element is already in a new list. If it is not, add it to the new list. Here’s
the python code for this:
Python
numbers = [1, 2, 3, 1, 2, 4, 5, 6, 5]
unique_numbers = []
for number in numbers:
if number not in unique_numbers:
unique_numbers.append(number)
print(unique_numbers)
Output:
[1, 2, 3, 4, 5, 6]
For example, you can have multiple constructors with different sets of
arguments by using default values for some of the arguments. Here’s an
example:
class Rectangle:
def __init__(self, width=0, height=0):
self.width = width
self.height = height
class Calculator:
def add(self, a, b=0):
return a + b
calculator = Calculator()
result = calculator.add(10, 20)
result = calculator.add(10)
In this example, the add method acts as multiple methods, as it can be
called with different sets of arguments, and the default value for b
ensures that the method can be called even if b is not specified.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
The self parameter is not explicitly passed when you call a method on an
instance, as it is automatically passed by Python. When you call
rect.area(), the rect instance is passed as the self parameter to the area
method, so you can use self to access the rect instance within the
method.
# Defining a function
def LargestAndSecondLargest(Data):
# Sorting the list in Ascending Order
Data = sorted(Data)
# Extracting the last element (Largest Element)
largestElement = Data[-1]
# Extracting the second last element (Second Largest Element)
SecondlargestElement = Data[-2]
# Returning the variables containing the elements.
return largestElement, SecondlargestElement
Data = [20,15,8,12,19]
LargestAndSecondLargest(Data)
Output:
(20, 19)
57. Create a Python program that will print the highest sequence
of 1s in an array of 0s and 1s?
Answer:
a = [1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1]
# Variable to Store the count of one
countofOne = 0
# Variable to Store the previous count only if the countofOne is greater than the L
LastCountofOne = 0
58. In the given array, write a list comprehension that will print
the sum of even numbers.
Answer:
Output:
30
# Sample Data
Data = [1,2,3,4,5,6,7,8,9,10]
# Function Call
EvenOdd(Data)
Output:
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]
The above program will create two separate lists after checking if the
elements are even or odd in the given sample, and print both the lists at
the end of the execution.
2. If not less than one, check if the number has some other factors or
not. If it has returned that it is not a prime number.
Now let’s have a look at the program to check if the number is a prime
number or not.
# Defining a Function
def isPrime(num):
# Checking if num > 1 because there are no prime numbers less than 1
for i in range(2,num):
if(num % i == 0):
break
else:
flag = True
else:
flag = False
return flag
# Sample input
num = 5
if (isPrime(num)):
else:
# If Flag is False print
Output:
taapilletnI
70. What would be the output if I ran the following code block?
list1 = [2, 33, 222, 14, 25]
print(list1[-2])
1. 14
2. 33
3. 25
4. Error
Answer: output:14
In Python, negative indexing allows you to access elements from the end
of the list. The index -1 represents the last element, -2 represents the
second-to-last element, and so on.
In the given code, list1[-2] refers to the second-to-last element in the list
list1, which is 14. Therefore, the output of the code will be 14.
my_list.sort()
print (my_list)
Output:
2,3,4,6,8
74. Which one of the following is not the correct syntax for
creating a set in Python?
1. set([[1,2],[3,4],[4,5]])
2. set([1,2,2,3,4,5])
3. {1,2,3,4}
4. set((1,2,3,4))
Answer:
set([[1,2],[3,4],[4,5]])
Explanation: The argument given for the set must be iterable.
if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Output:
13 is a prime number
class Snakes(Animals):
def eats(self):
print("eats insects")
obj = Snakes()
obj.House()
obj.eats()
Output:
lives in Jungle
eats insects
#multiple inheritance
class Maths:
def Marks(self):
self.maths = 90
class English:
def Marks(self):
self.english = 85
class Result(Maths, English):
def __init__(self):
Maths.Marks(self)
English.Marks(self)
def result(self):
self.res = (self.maths + self.english) // 2
print("The result is : {}%".format(self.res))
obj = Result()
obj.result()
Output:
The result is : 87%
#multi-level inheritance
class Vehicle:
def __init__(self):
self.Type = "Commercial"
print("Vehicle Type : {}".format(self.Type))
class Name(Vehicle):
def __init__(self):
self.Name = "Ashok Leyland"
print("Vehicle Name: ".format(self.Name))
class Final(Name):
def __init__(self):
Name.__init__(self)
Vehicle.__init__(self)
self.Tyres = 8
print("Number of tyres is: {}".format(self.Tyres))
obj = Final()
Output:
Vehicle Name:
Vehicle Type : Commercial
Number of tyres is: 8
'Virat Kohli',
'Shubman Gill',
'Ravindra Jadeja',
'KL Rahul'])
sample.str.upper()
Output:
0 ROHIT SHARMA
1 VIRAT KOHLI
2 SHUBMAN GILL
3 RAVINDRA JADEJA
4 KL RAHUL
dtype: object
index=['Ramesh', 'Suresh'],
columns=['weight', 'height'])
sample.stack()
Output:
Ramesh weight 65
height 158
Suresh weight 92
height 183
dtype: int64
import pandas as pd
'harsha', 'ramya'],})
data.index = data['student_id']
del data['student_id']
data
Output:
print(arr1)
newarr1= arr1.reshape(3,2)
print(newarr1.shape)
Output:
[[35 61 24]
[20 38 31]]
(3, 2)
83. Create an array that will have days from an entire year in the
datetime format using the datetime64 Numpy method?
Answer:
from datetime import datetime
import random
darr = np.arange('2024-01-01', '2025-01-01',dtype='datetime64')
print(darr)
84. For the given two arrays A and B, find the correlation
coefficients?
Answer:
A = np.array([[11,17,42],[21,19,27]])
B = np.array([[12,44,39],[62,81,10]])
A = np.array([[11,17,42],[21,19,27]])
B = np.array([[12,44,39],[62,81,10]])
corr= np.corrcoef(A,B)
print(corr)
Output:
[[ 1. 0.9106039 0.53232532 -0.90264562]
[ 0.9106039 1. 0.13487934 -0.99982205]
[ 0.53232532 0.13487934 1. -0.11616343]
[-0.90264562 -0.99982205 -0.11616343 1. ]]
a = np.array([[2,9],[6,13]])
b = np.array([[1,4],[3,11]])
Cross Product
cross=np.cross(a,b)
print(cross)
Output:
[-1 27]
Dot Product
dot = np.dot(a,b)
print(dot)
Output:
[[ 29 107]
[ 45 167]]
Matrix multiplication
m_multi= np.multiply(a,b)
print(m_multi)
Output:
[[ 2 36]
[ 18 143]]
Square root
sq_a= np.sqrt(a)
print(sq_a)
Output:
[[1.41421356 3. ]
[2.44948974 3.60555128]]
string = 'madame'
res = []
def checker(x):
res = x[::-1]
if res == x:
print('Palindrome')
else:
print("not a palindrome")
checker(string)
Output:
not a palindrome
87. Write a Python program that will print the length of an array
without using the len() function?
a = [1,2,3,4,5]
count = 0
for i in a:
count = count + 1
print(count)
Output:
5
ar = np.array([1, 3, 2, 4, 5, 6])
print(ar.argsort()[-3:][::-1])
89. What is the easiest way to calculate percentiles when using
Python?
The easiest and the most efficient way you can calculate percentiles in
Python is to make use of NumPy arrays and its functions.
Consider the following example:
import numpy as np
a = np.array([1,2,3,4,5,6,7])
p = np.percentile(a, 50) #Returns the 50th percentile, which is also the median
print(p)
def fun(string):
s1 = string
s = string[::-1]
if s1 == s:
return True
else:
return False
print(fun("madam"))
Program 1:
l=input('enter values').split(" ")
a=input('enter value to be searched')
for i in range(0,len(l)):
if a is l[i]:
pass
print(“Position:”)
print(i)
print('count is: ',l.count(a))
Exact Output
enter values2 4 3 2 7 2
enter value to be searched2
Position: 0
Position: 3
Position: 5
count is: 3
Answer:
Python code:
Program 2:
i=1
s=0
while i==10:
s=s+1
i=i+1
avg=s/10
print("the sum of first 10 numbers is",s)
print("the average of first 10 numbers is", avg)
Exact Output
the sum of first 10 numbers is 10
the average of first 10 numbers is 1
Answer:
Python code:
i = 1
s = 0
while i <= 10:
s = s + i
i = i + 1
avg = s / 10
print("The sum of the first 10 numbers is", s)
print("The average of the first 10 numbers is", avg)
Python code:
Program 3:
def count_ch(s,c):
count=0
for i in s:
if i ==c:
count+=1
return count
string=input("\n Enter a string ")
c=int(input("\n Enter character to search "))
count=count_ch(string,c)
print("In",string,c,"occurs ",count,"times")
Exact output
Enter a string lovely flowers
Enter character to search o
In lovely flowers o occurs 2 times
Answer:
Python code:
count = count_ch(string, c)
print(f"In '{string}', '{c}' occurs {count} times")
1. def count_ch(s, c):: Defines a function count_ch that takes a string s and
a character c.
2. count = 0: Initializes the count variable.
3. for i in s:: Loops through each character in the string s.
4. if i == c:: Checks if the current character i is equal to the character c.
5. count += 1: Increments the count if the character matches.
6. return count: Returns the final count.
7. string = input("\nEnter a string: "): Gets the string input from the
user.
8. c = input("\nEnter character to search: "): Gets the character to
search from the user.
9. count = count_ch(string, c): Calls the function count_ch with the
string and character as arguments.
10. print(f"In '{string}', '{c}' occurs {count} times"): Prints
the result using an f-string for better readability.
Sql code:
Program 4:
def check_relation(a,b):
if a==b:
return 0
if a>b:
return 1
if a<b:
return -1
check_relation(3,5)
if res=='0':
print("a is equal to b")
if res=='1':
print("a is greater than b")
if res=='-1':
print("a is less than b")
Exact output
a is less than b
Answer:
1. The check_relation function is called, but its result is not stored in a variable.
2. The return values from check_relation are integers, not strings, so the comparison
should be made with integers, not strings.
3. Proper indentation and spacing are necessary.
Python code:
if res == 0:
print("a is equal to b")
elif res == 1:
print("a is greater than b")
elif res == -1:
print("a is less than b")
Css code:
a is less than b
Program 5:
for i in range(1,6):
print(i,end="")
for j in range(1,6):
print(j,end="")
print()
Exact output
12345
12345
12345
12345
12345
Answer:
The original code is almost correct, but the placement of the print() statement for a new
line is incorrect. It should be placed inside the outer loop but outside the inner loop to ensure
that a new line is printed after each row of numbers.
Python code:
Copy code
12345
12345
12345
12345
12345
Program 6:
# don’t add new line or don’t delete any line in this program
for i in range(1,10):
print(i,end="")
Exact output
13579
Answer:
To achieve the exact output 13579, we need to print only the odd numbers between 1 and 9.
The original loop iterates over all numbers in the range and prints them, but we need to add a
condition to print only the odd numbers.
Python code:
# don’t add new line or don’t delete any line in this program
for i in range(1, 10):
if i % 2 != 0: # Check if the number is odd
print(i, end="")
Explanation:
13579
Program 7:
string="python is easy"
yes=” “
print(yes+string[:-1])
Exact output
yes python is easy
Answer:
Bash code:
To achieve the exact output yes python is easy, there is no need to exclude the last
character. Here is the corrected code for the exact desired output:
Python code:
Bash code:
Program 8:
# Don’t remove any ‘+’ symbol from this program
a=float(input("enter any floating point value"))
print("The integer value of "+a+"="+int(a))
Exact output
enter any floating point value4.3
The integer value of 4.3=4
Answer:
The error in the code is that the + operator is used for string concatenation, but a and
int(a) are not strings. You need to convert a and int(a) to strings before concatenating
them with other strings.
Here is the corrected code:
Python code:
Arduino code:
Program 9:
max1=0
max2=0
n=int(input("Enter the number of element in the list"))
l=[]
for i in range(0,n):
L.append(int(input("Enter the number")))
for i in range(0,len(L)):
if L[i]>max1:
max1=max2
max1=L[i]
elif L[i]>max2 and L[i]<max1:
max1=L[i]
print("First max",max1)
print("Second max",max2)
Exact output
Enter the number of element in the list10
Enter the number10
Enter the number90
Enter the number90
Enter the number90
Enter the number90
Enter the number90
Enter the number90
Enter the number80
Enter the number70
Enter the number60
First max 90
Second max 80
Answer:
1. The list l is initialized, but the code attempts to append values to L (case-sensitive
issue).
2. The indentation of the if and elif blocks is incorrect.
3. The logic to update max2 is incorrect.
4. The elif block incorrectly updates max1 instead of max2.
Python code:
max1 = 0
max2 = 0
n = int(input("Enter the number of elements in the list: "))
l = []
for i in range(n):
l.append(int(input("Enter the number: ")))
for i in range(len(l)):
if l[i] > max1:
max2 = max1
max1 = l[i]
elif l[i] > max2 and l[i] < max1:
max2 = l[i]
Yaml code:
Program 10:
Exact output
Enter value of n: 10
***** *****
******* *******
********* *********
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
Answer:
The issue in the original code lies mainly in the indentation and the way loops are structured
to produce the desired pattern. Additionally, there are some inconsistencies with how spaces
and asterisks are printed. Here's the corrected code that should produce the exact output you
specified:
Python code:
This corrected code will produce the exact output pattern for n = 10 as specified in your
example.