Table of Contents
A thorough grasp of Python’s foundations, libraries, and best practices is necessary to prepare for a technical interview in the language. Whether you’re a novice or an experienced Python developer, this book will help you answer the most often asked Python Technical Interview questions.
We’ll go over a number of subjects that are frequently asked in technical Python interviews in this article. Our curriculum covers everything from fundamental syntax and data structures to more complex ideas like object-oriented programming and algorithm design. With this knowledge, you’ll be ready to crush your next interview.
Experience the power of our python programming course with a free demo – enroll now!
Introduction
Guido van Rossum created Python, which was initially made available on February 20, 1991. Being interpretive in nature, it is one of the most popular and frequently used programming languages, offering flexibility in integrating dynamic semantics. It has a relatively straightforward syntax and is free and open-source. Python learning is made easier for developers as a result. Python is mostly used for general-purpose programming, but it can also support object-oriented programming.
Python is becoming more and more popular because of its ease of use and capacity to accomplish more tasks with fewer lines of code. Python’s ability to enable strong calculations utilising strong libraries makes it useful in a variety of other disciplines, including machine learning, artificial intelligence, web development, and web scraping.
What is python?
Python is a programming language that facilitates the execution of specified tasks on a computer by giving it commands in the form of programmes. It’s an object-oriented, high-level programming language with interpreted capabilities. Beginners found it to be an obvious choice to begin their programming career because of its syntax, which is easy to understand.
Python is an object-oriented, interpreted programming language that is also regarded as high-level. Python is used by people for software development, web development, and competitive programming. It is suggested for those who are new to the field of software engineering because of its simplest syntax. Because of its many applications in contemporary technological domains such as Data Science, Machine Learning, and Automation Tasks, its demand is expanding at an extremely fast rate.
Experience the power of our python programming course with a free demo – enroll now!
Top Python Technical Interview Questions
Q. To find the sum of a list of numbers, write a Python programme.
Answer:
def
sum
(num):
if
len
(num) =
=
1
: return
num[0
] # The total result will equal the element if the list has just one element.
else
: return
num[0
] +
sum
(num[1
:])
print
(sum
([2
, 3,4
, 5
, 6
, 7
]))
Q. Write a palindrome checker using Python. Making use of an empty array for item assignment?
Answer:
string
=
'Mome'
res
=
[]
def
checker(a): res=
a[::-
1
]if
res=
=
a:else
:Word not
a palindrome
Q. Write a Python programme that, without utilising the len() function, prints the length of an array.
X
=
[
1
,
2
,
3
,
4
,
5
] count
=
0
for
iin
X: count=
count+
1
Output:
5
Q. Write a Python program to find the largest of two numbers?
Answer:Â
a
=
4b
=
8(
"x is greater"
)
if
a > b
else
(
'Both are equal'
)
if
a
=
=
b
else
(
'b is greater'
) Output: b
is
greater a=
12 b=
4"a is greater"
)if
a > belse
'Both are equal'
)if
a=
=
belse
is greater'
) Output: ais
greater a=
12 b
=
12"a is greater"
)if
a > belse
'Both are equal'
)if
a=
=
belse
'b is greater'
)
Output:
Both a and b are equal
Q. To determine whether the input is an Armstrong number or not, write a Python programme.
Answer:Â
def
armstrong(num):
sum
=
0
temp=
numwhile
temp >0
: x=
temp%
10
sum
=
sum
+
a*
*
3 temp=
temp/
/
10"armstrong"
)if
sum
=
=
numelse
"not armstrong"
) armstrong( 407)
Output:
The number is Armstrong
Q. Write a Python program to depict list comprehension?
Answer:Â
Here’s a basic example of using list comprehension to generate a list.
[a**2 for a in range(0,100,10)]
Output:
[0, 100, 400, 900, 1600, 2500, 3600, 4900, 6400, 8100]Q. Write a Python program that will depict dictionary comprehension in Python?
Answer:Â
Here’s a basic example of using list comprehension to generate a list.
{a: a**2 for a in range(0,100,10)}
{0: 0,
10: 100,
20: 400,
30: 900,
40: 1600,
50: 2500,
60: 3600,
70: 4900,
80: 6400,
90: 8100}
Q. Write a Python program to demonstrate abstraction in Python?
Answer:Â
from
xyz
import
XYZ, abstractmethod
class
X(XYZ):
@abstractmethod
def
sum
(self
):pass class Y(X): def
sum
(self
, x, y):self
.x = xself
.y = yreturn
self
.x
/
/
self
.y obj
=
Y() obj.sum
(20,2)
Output:
10.
Q. Write a Python program to find the largest of the two numbers using NumPy?
Answer:
Using the code below, we can extract the indices of N maximum values from a NumPy array:
import
numpy as np ar
=
np.array([1
, 2, 3,4
,5
,6
])-
3
:][::-
1
])
Q. What is the easiest way to calculate percentiles when using Python?
Answer:
Using NumPy arrays and associated functions to calculate percentiles in Python is the simplest and most effective method available.
Look on the following example:
import
numpy as np x
=
np.array([1
,2
,3
,4
,5
,6
,7
]) y=
np.percentile(x,50
)#Returns the 50th percentile, which is also the median
Q. Write a Python programme that, without the need for an iterative process, determines if a given string is a palindrome or not.
Answer:Â
When a word, phrase, or sequence reads the same both forward and backward—for example, Malayalam, Mom, madam etc.— it is called a palindrome.
Look on the below code:
def
fun(string): a1
=
string a=
string[::-
1
]if
a1=
=
a:return
True
else
:return
False"malayalam"
))
Q. Write a function in Python that accepts an arbitrary amount of arguments.
def function_name(*arg_list)
def func(*var):
for x in var:
print(x)
func(2)
func(10,2,3)
Variable arguments in the function are represented by the * in the function argument.
Q. Write a programme (WAP) that accepts a series of numbers and determines whether or not each one is unique.
def check_distinct(data_list):
if len(data_list) == len(set(data_list)):
return True
else:
return False;
print(check_distinct([1,1,1,1])) #Prints True
print(check_distinct([2,3,2,3,6,7])) #Prints False
Q. Write a program for counting the number of every character of a given text file.
import programs
import pprint
with open("sample_file.txt", 'q+') as data:
count_data = collections.Counter(data.read().upper())
count_value = pprint.pformat(count_data)
print(count_value)
Q. Write a programme that will identify and return all pairs in a given array ar whose sum equals a desired number X.
def print_pairs(ar, X):
# hash set
hash_set = set()
for i in range(0, len(ar)):
val = X-ar[i]
if (val in hash_set): #check if X-x is there in set, print the pair
print("Pairs " + str(ar[i]) + ", " + str(val))
hash_set.add(ar[i])
# driver code
ar = [2, 3, 20 , 4, 8, 5]
X = 2
print_pairs(ar, X)
Q. Create a programme that adds two numbers greater than 0 without requiring the plus sign.
def add_X(x1, x2):
while x2 != 0:
data = x1 & x2
x1 = x1 ^ x2
x2 = data << 1
return x1
print(add_X(2, 5))
Q. Assuming that a, b, c, x, y, and z are constants, write a programme to solve the preceding equation:
a1 + b1 = c
x1 + y1 = z
By solving the equation, we get:
a, b, c, x, y, z = 4, 8, 5, 7, 8, 4
temp = a*y - b*x
if y != 0:
x = (c*y - b*z) / temp
y = (a*z - x*c) / temp
print(str(p), str(q))
Q. Write a programme that matches a string consisting of 2 to 4 “y’s” after the letter “x”.
import pq
def match_text(txt_data):
pattern = 'xy{2,4}'
if pq.search(pattern, txt_data): #search for pattern in txt_data
return 'Match found'
else:
return('Match not found')
print(match_text("xyz")) #prints Match not found
print(match_text("xyyz")) #prints Match found
Q. Write a programme that converts dates in the format yyyy-mm-dd to dd-mm-yyyy.
import pq
def transform_date_format(date):
return pq.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\3-\\2-\\1', date)
date_input = "2024-05-16"
print(transform_date_format(date_input))
The datetime module can also be utilised as demonstrated below:
from datet import datet
new_date = datet.strpt("2024-05-16", "%Y-%m-%d").strftime("%d:%m:%Y")
print(new_data)
Q. Create a programme that combines two distinct dictionaries. If you locate the same keys throughout the combining process, you can sum their values together. Give the updated dictionary.
from collections import Counter
a1 = {'key1': 100, 'key2': 200, 'key3':300}
a2 = {'key1': 300, 'key2': 200, 'key4':400}
new_dict = Counter(a1) + Counter(a2)
print(new_dict)
Q. How are you going to retrieve the dataset from a Google Drive spreadsheet that is publicly published and in CSV format?
After reading from the Google Drive link using the StringIO module from the io module, we can use the pandas library with the data source we had previously acq uired.
from io import StringIO
import pandas
csv_link = "https://docs.google.com/spreadsheets/d/..."
data_source = StringIO.StringIO(requests.get(csv_link).content))
dataframe = pd.read_csv(data_source)
print(dataframe.head())
Q. Write a Python programme that, given an array of 0s and 1s, will print the longest sequence of 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 LastCountofOne LastCountofOne
=
0 # For Loop to traverse through all the element in the arrayfor
iin
range
(len
(a)):# Check if the element is 1
if
a[i]=
=
1: # Count increased by 1 countofOne+
=
1Â Â
else
:Â
# Checking if countofOne &gt; LastCountofOneif
(LastCountofOne &lt; countofOne): # Swapping the value to LastCountofOne if the above condition is True # Set countofOne to zero as we are interrupted by zero countofOne=
0 # Comparing the last value of countofOne with LastCountofOneif
(LastCountofOne &gt; countofOne): # Print LastCountofOneelse
: # Print countofOne
Output:
8
Q. Create a function that takes an array as input and outputs distinct lists with even and odd elements in them.
Answer:
Let’s examine the programme; in this case, our strategy is expressed as follows:
- Verify whether the supplied element is odd or even.
- Provide two distinct lists with elements that are even and odd.
# Defining a Function
def
EvenOdd(Data):
# Checking if the number is even
print
([x for
x in
Data if
x%
2
=
=
0
])
# Cheking if the number is odd
print
([x for
x in
Data if
x%
2
!=
0
])
# 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]Experience the power of our python programming course with a free demo – enroll now!