Python Interview Questions

Interviewing for Python can be quite intimidating.  If you are appearing for a technical round of interview for Python, here’s a list of 69 interview questions with answers to help you prepare. The first set of questions and answers are curated for freshers while the second set is designed for advanced users. These questions cover all the basic applications of Python and will showcase your expertise in the subject.
Before going through the questions, here’s a quick video to help you refresh your memory on Python. 

1. What are the key features of Python? 

Python is one of the most popular programming languages used by data scientists and AIML professionals. This popularity is due to the following key features of Python:

  • Python is easy to learn due to its clear syntax and readability
  • Python is easy to interpret, making debugging easy
  • Python is free and Open-source
  • It can be used across different languages
  • It is an object-oriented language which supports concepts of classes
  • It can be easily integrated with other languages like C++, Java and more

2. What are Keywords in Python? 

Keywords in Python are reserved words which are used as identifiers, function name or variable name. They help define the structure and syntax of the language. 

There are a total of 33 keywords in Python 3.7 which can change in the next version, i.e., Python 3.8. A list of all the keywords is provided below:

Keywords in Python

Falseclassfinallyisreturn
Nonecontinueforlambdatry
Truedeffromnonlocalwhile
anddelglobalnotwith
aselififoryield
assertelseimportpass
breakexcept


3. What are Literals in Python and explain about different Literals?

Literals in Python refer to the data that is given in a variable or constant. Python has various kinds of literals including:

  1. String Literals: It is a sequence of characters enclosed in codes. There can be single, double and triple strings based on the number of quotes used. Character literals are single characters surrounded by single or double-quotes. 
  2. Numeric Literals: These are unchangeable kind and belong to three different types – integer, float and complex.
  3. Boolean Literals: They can have either of the two values- True or False which represents ‘1’ and ‘0’ respectively. 
  4. Special Literals: Special literals are sued to classify fields that are not created. It is represented by the value ‘none’.

4. How can you concatenate two tuples?

  Solution ->

Let’s say we have two tuples like this ->

tup1 = (1,”a”,True)

tup2 = (4,5,6)

Concatenation of tuples means that we are adding the elements of one tuple at the end of another tuple.

Now, let’s go ahead and concatenate tuple2 with tuple1:

All you have to do is, use the ‘+’ operator between the two tuples and you’ll get the concatenated result.

Similarly, let’s concatenate tuple1 with tuple2:

5. How can you find the minimum and maximum values present in a tuple?

 Solution ->

We can use the min() function on top of the tuple to find out the minimum value present in the tuple:

We see that the minimum value present in the tuple is 1.

Analogous to the min() function is the max() function, which will help us to find out the maximum value present in the tuple:

We see that the maximum value present in the tuple is 5

6. If you have a list like this -> [1,”a”,2,”b”,3,”c”]. How can you access the 2nd, 4th and 5th elements from this list?

Solution ->

We will start off by creating a tuple which will comprise of the indices of elements which we want to access:

Then, we will use a for loop to go through the index values and print them out:

Below is the entire code for the process:

7. If you have a list like this -> [“sparta”,True,3+4j,False]. How would you reverse the elements of this list?

Solution ->

We can use  the reverse() function on the list:

8. If you have dictionary like this – > fruit={“Apple”:10,”Orange”:20,”Banana”:30,”Guava”:40}. How would you update the value of ‘Apple’ from 10 to 100?

Solution ->

 This is how you can do it:

Give in the name of the key inside the parenthesis and assign it a new value.

9. If you have two sets like this -> s1 = {1,2,3,4,5,6}, s2 = {5,6,7,8,9}. How would you find the common elements in these sets.

Solution ->

You can use the intersection() function to find the common elements between the two sets:

We see that the common elements between the two sets are 5 & 6.

10. Write a program to print out the 2-table using while loop.

Solution ->

Below is the code to print out the 2-table:

We start off by initializing two variables ‘i’ and ‘n’. ‘i’ is initialized to 1 and ‘n’ is initialized to ‘2’.

Inside the while loop, since the ‘i’ value goes from 1 to 10, the loop iterates 10 times.

Initially n*i is equal to 2*1, and we print out the value.

Then, ‘i’ value is incremented and n*i becomes 2*2. We go ahead and print it out.

This process goes on until i value becomes 10.

11. What are functions in Python? 

Ans: Functions in Python refer to blocks that have organised, and reusable codes to perform single, and related events. Functions are important to create better modularity for applications which reuse high degree of coding. Python has a number of built-in functions like print(). However, it also allows you to create user-defined functions.

12. Write a function, which will take in a value and print out if it is even or odd.

Solution ->

The below code will do the job:

Here, we start off by creating a method, with the name ‘even_odd()’. This function takes a single parameter and prints out if the number taken is even or odd.

Now, let’s invoke the function:

We see that, when 5 is passed as a parameter into the function, we get the output -> ‘5 is odd’.

13. Write a python program to print the factorial of a number.

Solution ->

Below is the code to print the factorial of a number:

We start off by taking an input which is stored in ‘num’. Then, we check if ‘num’ is less than zero and if it is actually less than 0, we print out ‘Sorry, factorial does not exist for negative numbers’.

After that, we check,if ‘num’ is equal to zero, and it that’s the case, we print out ‘The factorial of 0 is 1’.

On the other hand, if ‘num’ is greater than 1, we enter the for loop and calculate the factorial of the number.

14. Write a python program to check if the number given is a palindrome or not

Solution ->

Below is the code to Check whether the given number is palindrome or not:

We will start off by taking an input and store it in ‘n’ and make a duplicate of it in ‘temp’. We will also initialize another variable ‘rev’ to 0. 

Then, we will enter a while loop which will go on until ‘n’ becomes 0. 

Inside the loop, we will start off by dividing ‘n’ with 10 and then store the remainder in ‘dig’.

Then, we will multiply ‘rev’ with 10 and then add ‘dig’ to it. This result will be stored back in ‘rev’.

Going ahead, we will divide ‘n’ by 10 and store the result back in ‘n’

Once the for loop ends, we will compare the values of ‘rev’ and ‘temp’. If they are equal, we will print ‘The number is a palindrome’, else we will print ‘The number isn’t a palindrome’.

15. Write a python program to print the following pattern ->

1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

Solution ->

Below is the code to print this pattern:

We are solving the problem with the help of nested for loop. We will have an outer for loop, which goes from 1 to 5. Then, we have an inner for loop, which would print the respective numbers.

16. What do you understand by object oriented programming in Python?

Object oriented programming refers to the process of solving a problem by creating objects. This approach takes into account two key factors of an object- attributes and behaviour.

17. How can you initialize a 5*5 numpy array with only zeroes?  

Solution ->

We will be using the .zeros() meethod

Use np.zeros() and pass in the dimensions inside it. Since, we want a 5*5 matrix, we will pass (5,5) inside the .zeros() method.

This will be the output:

18.  Pattern questions. Print the following pattern

#
# #
# # #
# # # #
# # # # #

Solution –>

def pattern_1(num): 
      
    # outer loop handles the number of rows
    # inner loop handles the number of columns 
    # n is the number of rows. 
    for i in range(0, n): 
      # value of j depends on i 
        for j in range(0, i+1): 
          
            # printing hashes
            print("#",end="") 
       
        # ending line after each row 
        print("\r")  
num = int(input("Enter the number of rows in pattern: "))
pattern_1(num)

19. Print the following pattern

  # 
      # # 
    # # # 
  # # # #
# # # # #

Solution –>

       
Code:
def pattern_2(num): 
      
    # define the number of spaces 
    k = 2*num - 2
  
    # outer loop always handles the number of rows 
    # let us use the inner loop to control the number of spaces
    # we need the number of spaces as maximum initially and then decrement it after every iteration
    for i in range(0, num): 
        for j in range(0, k): 
            print(end=" ") 
      
        # decrementing k after each loop 
        k = k - 2
      
        # reinitializing the inner loop to keep a track of the number of columns
        # similar to pattern_1 function
        for j in range(0, i+1):  
            print("# ", end="") 
      
        # ending line after each row 
        print("\r") 
  

num = int(input("Enter the number of rows in pattern: "))
pattern_2(num)

20. Print the following pattern:

0
0 1
0 1 2
0 1 2 3
0 1 2 3 4

Solution –>

Code: 
def pattern_3(num): 
      
    # initialising starting number  
    number = 1
    # outer loop always handles the number of rows 
    # let us use the inner loop to control the number 
   
    for i in range(0, num): 
      
        # re assigning number after every iteration
        # ensure the column starts from 0
        number = 0
      
        # inner loop to handle number of columns 
        for j in range(0, i+1): 
          
                # printing number 
            print(number, end=" ") 
          
            # increment number column wise 
            number = number + 1
        # ending line after each row 
        print("\r") 
 
num = int(input("Enter the number of rows in pattern: "))
pattern_3(num)

21. Print the following pattern:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Solution –>

Code: 

def pattern_4(num): 
      
    # initialising starting number  
    number = 1
    # outer loop always handles the number of rows 
    # let us use the inner loop to control the number 
   
    for i in range(0, num): 
      
        # commenting the reinitialization part ensure that numbers are printed continuously
        # ensure the column starts from 0
        number = 0
      
        # inner loop to handle number of columns 
        for j in range(0, i+1): 
          
                # printing number 
            print(number, end=" ") 
          
            # increment number column wise 
            number = number + 1
        # ending line after each row 
        print("\r") 
  

num = int(input("Enter the number of rows in pattern: "))
pattern_4(num)

22. Print the following pattern:

A
B B
C C C
D D D D

Solution –>

def pattern_5(num): 
    # initializing value of A as 65
    # ASCII value  equivalent
    number = 65
  
    # outer loop always handles the number of rows 
    for i in range(0, num): 
      
        # inner loop handles the number of columns 
        for j in range(0, i+1): 
          
            # finding the ascii equivalent of the number 
            char = chr(number) 
          
            # printing char value  
            print(char, end=" ") 
      
        # incrementing number 
        number = number + 1
      
        # ending line after each row 
        print("\r") 
  
num = int(input("Enter the number of rows in pattern: "))
pattern_5(num)

23. Print the following pattern:

A
B C
D E F
G H I J
K L M N O
P Q R S T U

Solution –>

def  pattern_6(num): 
    # initializing value equivalent to 'A' in ASCII  
    # ASCII value 
    number = 65
 
    # outer loop always handles the number of rows 
    for i in range(0, num):
        # inner loop to handle number of columns 
        # values changing acc. to outer loop 
        for j in range(0, i+1):
            # explicit conversion of int to char
# returns character equivalent to ASCII. 
            char = chr(number) 
          
            # printing char value  
            print(char, end=" ") 
            # printing the next character by incrementing 
            number = number +1    
        # ending line after each row 
        print("\r") 
num = int(input("enter the number of rows in the pattern: "))
pattern_6(num)

24. Print the following pattern

  #
    # # 
   # # # 
  # # # # 
 # # # # #

Solution –>

Code: 
def pattern_7(num): 
      
    # number of spaces is a function of the input num 
    k = 2*num - 2
  
    # outer loop always handle the number of rows 
    for i in range(0, num): 
      
        # inner loop used to handle the number of spaces 
        for j in range(0, k): 
            print(end=" ") 
      
        # the variable holding information about number of spaces
        # is decremented after every iteration 
        k = k - 1
      
        # inner loop reinitialized to handle the number of columns  
        for j in range(0, i+1): 
          
            # printing hash
            print("# ", end="") 
      
        # ending line after each row 
        print("\r") 
 
num = int(input("Enter the number of rows: "))
pattern_7(n)

25. What is pandas?

Pandas is an open source python library which has a very rich set of data structures for data based operations. Pandas with it’s cool features fits in every role of data operation, whether it be academics or solving complex business problems. Pandas can deal with a large variety of files and is one of the most important tools to have a grip on.

26. What are dataframes?

A pandas dataframe is a data structure in pandas which is mutable. Pandas has support for heterogeneous data which is arranged across two axes.( rows and columns).

Reading files into pandas:-

Import pandas as pd

df=p.read_csv(“mydata.csv”)

Here df is a pandas data frame. read_csv() is used to read a comma delimited file as a dataframe in pandas.

27. What is a pandas Series?

Series is a one dimensional pandas data structure which can data of almost any type. It resembles an excel column. It supports multiple operations and is used for single dimensional data operations.

Creating a series from data:

28. What is pandas groupby?

A pandas groupby is a feature supported by pandas which is used to split and group an object.  Like the sql/mysql/oracle groupby it used to group data by classes, entities which can be further used for aggregation. A dataframe can be grouped by one or more columns.

29. How to create a dataframe from lists?

To create a dataframe from lists ,

1)create an empty dataframe

2)add lists as individuals columns to the list

30. How to create dataframe from a dictionary?

A dictionary can be directly passed as an argument to the DataFrame() function to create the data frame.

31. How to create a new column in pandas by using values from other columns?

We can perform column based mathematical operations on a pandas dataframe. Pandas columns containing numeric values can be operated upon by operators.

32. What are the different functions that can be used by grouby in pandas ?

grouby() in pandas can be used with multiple aggregate functions. Some of which are sum(),mean(), count(),std().

Data is divided into groups based on categories and then the data in these individual groups can be aggregated by the aforementioned functions.

33. How to combine dataframes in pandas?

Two different data frames can be stacked either horizontally or vertically by the concat(), append() and join() functions in pandas.

Concat works best when the dataframes have the same columns and can be used for concatenation of data having similar fields and is basically vertical stacking of dataframes into a single dataframe.

Append() is used for horizontal stacking of dataframes. If two tables(dataframes) are to be merged together then this is the best concatenation function.

Join is used when we need to extract data from different dataframes which are having one or more common columns. The stacking is horizontal in this case.

34. What kind of joins does pandas offer?

Pandas has a left join, inner join, right join and an outer join.

35. How to merge dataframes in pandas?

Merging depends on the type and fields of different dataframes being merged. If data is having similar fields data is merged along axis 0 else they are merged along axis 1.

36. Given the below dataframes form a single dataframe by vertical stacking.

We use the pd.concat and axis as 0 to stack them horizontally.

37. Given the below dataframes stack them horizontally to form a single data frame.

We use the pd.concat and axis as 0 to stack them horizontally.

38. How to select columns in pandas and add them to a new dataframe? What if there are two columns with the same name?

If df is dataframe in pandas df.columns gives the list of all columns. We can then form new columns by selecting columns.

If there are two columns with the same name then both columns get copied to the new dataframe.

39. How to delete a columns or group of columns in pandas? Given the below dataframe drop column “col1”.

drop() function can be used to delete the columns from a dataframe. 

40. Give the below dataframe drop all rows having Nan.

The dropna function can be used to do that.

41. Given the following data frame drop rows having column values as A.

42. Given the below dataset find the highest paid player in each college in each team.

43. Given the above dataset find the min max and average salary of a player collegewise and teamwise.

44. What is reindexing in pandas?

Reindexing is the process of re-assigning the index of a pandas dataframe.

45. How to access the first five entries of a dataframe?

By using the head(5) function we can get the top five entries of a dataframe. By default df.head() returns the top 5 rows. To get the top n rows df.head(n) will be used.

46. How to access the last five entries of a dataframe?

By using tail(5) function we can get the top five entries of a dataframe. By default df.tail() returns the top 5 rows. To get the last n rows df.tail(n) will be used.

47. How to fetch a data entry from a pandas dataframe using a given value in index?

To fetch a row from dataframe given index x, we can use loc.

Df.loc[10] where 10 is the value of the index.

48. What are comments and how can you add comments in Python?

Comments in Python refer to a piece of text intended for information. It is especially relevant when more than one person works on a set of codes. It can be used to analyse code, leave feedback, and debug it. There are two types of comments which includes:

  1. Single-line comment
  2. Multiple-line comment

Codes needed for adding comment

#Note –single line comment
“””Note
Note
Note”””—–multiline comment

49. What is the difference between list and tuples in Python?

Lists are mutable, but tuples are immutable.

50. What is a dictionary in Python? Give an example

A Python dictionary is a collection of items in no particular order. Python dictionaries are written in curly brackets with keys and values. Dictionaries are optimised to retrieve value for known keys.

Example

d={“a”:1,”b”:2}

51. If you have a dictionary like this -> d1={“k1″:10,”k2″:20,”k3”:30}. How would you increment values of all the keys ?

d1={"k1":10,"k2":20,"k3":30}
 
for i in d1.keys():
  d1[i]=d1[i]+1

52. What do you understand by lambda function? Create a lambda function which will print the sum of all the elements in this list -> [5, 8, 10, 20, 50, 100]

from functools import reduce
sequences = [5, 8, 10, 20, 50, 100]
sum = reduce (lambda x, y: x+y, sequences)
print(sum)

53. How are classes created in Python? Give an example

class Node(object):
  def __init__(self):
    self.x=0
    self.y=0

Here Node is a class

54. What is inheritance in Object oriented programming? Give an example of multiple inheritance.

Inheritance is one of the core concepts of object-oriented programming. It is a process of deriving a class from a different class and form a hierarchy of classes that share the same attributes and methods. It is generally used for deriving different kinds of exceptions, create custom logic for existing frameworks and even map domain models for database.

Example

class Node(object):
  def __init__(self):
    self.x=0
    self.y=0

Here class Node inherits from the object class.

55. What is multi-level inheritance? Give an example for multi-level inheritance?

If class A inherits from B and C inherits from A it’s called multilevel inheritance.
class B(object):
  def __init__(self):
    self.b=0
 
class A(B):
  def __init__(self):
    self.a=0
 
class C(A):
  def __init__(self):
    self.c=0

56. Find out the mean, median and standard deviation of this numpy array -> np.array([1,5,3,100,4,48])

import numpy as np
n1=np.array([10,20,30,40,50,60])
print(np.mean(n1))
print(np.median(n1))
print(np.std(n1))

57. What is vstack() in numpy? Give an example

vstack() is a function to align rows verticaly. All rows must have same number of elements.

58. What is Machine Learning?

Machine Learning refers to the technologies (AIML) that enable machines to automatically learn and improve from experience without explicit instructions or algorithms. ML methodologies use data to feed machines with prototypes, examples from which it can learn patterns and make decisions based on this learning. The end goal of machine learning is to eliminate or reduce human intervention while working with computers.

59. What is a classifier?

A classifier is used to predict the class of any data point. Classifiers are special hypotheses that are used to assign class labels to any particular data points. A classifier often uses training data to understand the relation between input variables and the class. Classification is a method used in supervised learning in Machine Learning.

60. What is Supervised Learning?

Supervised learning refers to the technique of aiding the machine in the learning process. Supervised learning uses labeled data to train the machines so that it understands the values assigned to the data set. Post the training process, when the machine is provided with a new set of data, it uses supervised learning algorithms to analyse and produce the correct result.

61. What is unsupervised learning?

Unsupervised learning refers to the process of training machines without explicit instructions. Unlike supervised learning, unsupervised learning doesn’t use labelled or classified data to train the machine. It allows the learning model to discover information on its own through unlabelled data. 

Unsupervised learning algorithms are used for more complex processing tasks where not much information is available.

62. What is linear regression?

Linear regression is one of the most commonly used types of predictive analysis. Linear regression is used to analyse the effectiveness of variables in a training model. Linear regression assumes that there is a linear relation between the input and output variables. There are two types of linear regression- 

  • Simple linear regression
  • Multiple linear regression

63. What are features?

A feature is a measurable component of the data set that machine learning sets out to analyse. Features appear as columns for datasets. The quality of features determine the quality of the insights that you can gain out of a data set. Features vary from one business case to another. Hence, it is important to understand the business goals of your machine learning project to optimise the features (through feature selection, feature engineering and more).

64. What is discrete data?

Discrete data refers to data that has a distinct set of values. Discrete data is countable and cannot be subdivided any further. Discrete data can take on only particular values and is generally numeric.

65. What is continuous data?

Continuous data cannot be restricted to just separate values but can occupy any value over a continuous range. There may be an infinite number of values between any two continuous data. Continuous data is not countable but is measurable. It is always represented in numeric values.

66. What are the assumptions of linear regression?

The basic assumptions of linear regression are as follows:

  • There is a linear relationship between the features and target
  • There is little or no Multicollinearity between the features
  • Homoscedasticity Assumption : When the error term is same across all values 
  • Errors follow a normal distribution
  • There is little or no autocorrelation in the residuals

67. What is the visualization technique best suited for representing counts?

Visualization techniques best suited for representing counts are as follows:

  • Countplot- It is similar to a bar graph or a histogram which shows the number of occurrences of an item based on a certain type of category.  
  • Barplot – It is one of the most common types of graphics. It represents the relationship between a numeric and a categorical value (where categorical value is represented through a bar and the numeric value through the height of the bar)

68. What is scatter plot and what is the use of it?

A scatter plot represents values for different numeric variables through dots where the position of each dot on the horizontal and vertical axis indicates values for individual data points.

Scatter plots are used to determine the relationship between different variables and understand how one variable is affected by another.

69. What is normalization?

Normalisation is a database design technique that reduces redundancy and dependency of data. This involves organising tables by diving bigger ones into smaller parts and linking them through relationships. This process ensures data is stored logically.

Great Learning offers extensive courses on Artificial Intelligence and Machine Learning. Upskilling in this domain can land you the job of your dreams.

1

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

four × 5 =