Join us

Python Interview Questions and Answers | dridhOn

Python Interview Questions and Answers | dridhOn

Python Interview Questions

1) What is Python?

Python was created by Guido van Rossum, and released in 1991.

It is a general-purpose computer programming language. It is a high-level, object-oriented language which can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh. Its high-level built-in data structures, combined with dynamic typing and dynamic binding. It is widely used in data science, machine learning and artificial intelligence domain.

It is easy to learn and require less code to develop the applications.

It is widely used for:

  • Web development (server-side).
  • Software development.
  • Mathematics.
  • System scripting.

2) Why Python?

  • Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
  • Python is compatible with different platforms like Windows, Mac, Linux, Raspberry Pi, etc.
  • Python has a simple syntax as compared to other languages.
  • Python allows a developer to write programs with fewer lines than some other programming languages.
  • Python runs on an interpreter system, means that the code can be executed as soon as it is written. It helps to provide a prototype very quickly.
  • Python can be described as a procedural way, an object-orientated way or a functional way.
  • The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.

3) What are the applications of Python?

Python is used in various software domains some application areas are given below.

  • Web and Internet Development
  • Games
  • Scientific and computational applications
  • Language development
  • Image processing and graphic design applications
  • Enterprise and business applications development
  • Operating systems
  • GUI based desktop applications

Python provides various web frameworks to develop web applications. The popular python web frameworks are Django, Pyramid, Flask.

Python’s standard library supports for E-mail processing, FTP, IMAP, and other Internet protocols.

Python’s SciPy and NumPy helps in scientific and computational application development.

Python’s Tkinter library supports to create a desktop based GUI applications.

4) What are the advantages of Python?

  • Advantages of Python are:
    • Python is Interpreted language
    • Interpreted: Python is an interpreted language. It does not require prior compilation of code and executes instructions directly.
    • It is Free and open source
    • Free and open source: It is an open-source project which is publicly available to reuse. It can be downloaded free of cost.
    • It is Extensible
    • Extensible: It is very flexible and extensible with any module.
    • Object-oriented
    • Object-oriented: Python allows to implement the Object-Oriented concepts to build application solution.
    • It has Built-in data structure
    • Built-in data structure: Tuple, List, and Dictionary are useful integrated data structures provided by the language.
    • Readability
    • High-Level Language
    • Cross-platform
    • Portable: Python programs can run on cross platforms without affecting its performance.

5) What is PEP 8?

PEP 8 stands for Python Enhancement Proposal, it can be defined as a document that helps us to provide the guidelines on how to write the Python code. It is basically a set of rules that specify how to format Python code for maximum readability. It was written by Guido van Rossum, Barry Warsaw and Nick Coghlan in 2001.

6) What do you mean by Python literals?

Literals can be defined as a data which is given in a variable or constant. Python supports the following literals:

String Literals

String literals are formed by enclosing text in the single or double quotes. For example, string literals are string values.


# in single quotes
single = ‘JavaTpoint’
# in double quotes
double = “JavaTpoint”
# multi-line String
multi = ””’Java


Numeric Literals

Python supports three types of numeric literals integer, float and complex.


# Integer literal
a = 10
#Float Literal
b = 12.3
#Complex Literal
x = 3.14j

Boolean Literals

Boolean literals are used to denote Boolean values. It contains either True or False.


p = (1 == True)
q = (1 == False)
r = True + 3
s = False + 7

print(“p is”, p)
print(“q is”, q)
print(“r:”, r)
print(“s:”, s)

p is True
q is False
r: 4
s: 7
Special literals

Python contains one special literal, that is, ‘None’. This special literal is used for defining a null variable. If ‘None’ is compared with anything else other than a ‘None’, it will return false.


word = None


7) Explain Python Functions?

A function is a section of the program or a block of code that is written once and can be executed whenever required in the program. A function is a block of self-contained statements which has a valid name, parameters list, and body. Functions make programming more functional and modular to perform modular tasks. Python provides several built-in functions to complete tasks and also allows a user to create new functions as well.

There are three types of functions:

Built-In Functions: copy(), len(), count() are the some built-in functions.
User-defined Functions: Functions which are defined by a user known as user-defined functions.
Anonymous functions: These functions are also known as lambda functions because they are not declared with the standard def keyword.
Example: A general syntax of user defined function is given below.

def function_name(parameters list):
#— statements—
return a_value

8) What is zip() function in Python?

Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, convert into iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples.


  1. zip(iterator1, iterator2, iterator3 …)    


iterator1, iterator2, iterator3: These are iterator objects that are joined together.


It returns an iterator from two or more iterators.

9) What is Python's parameter passing mechanism?

  • There are two parameters passing mechanism in Python:
    • Pass by references
    • Pass by value
    • By default, all the parameters (arguments) are passed “by reference” to the functions. Thus, if you change the value of the parameter within a function, the change is reflected in the calling function as well. It indicates the original variable. For example, if a variable is declared as a = 10, and passed to a function where it’s value is modified to a = 20. Both the variables denote to the same value.
      The pass by value is that whenever we pass the arguments to the function only values pass to the function, no reference passes to the function. It makes it immutable that means not changeable. Both variables hold the different values, and original value persists even after modifying in the function.
      Python has a default argument concept which helps to call a method using an arbitrary number of arguments.

10) How to overload constructors or methods in Python?

Python’s constructor: _init__ () is the first method of a class. Whenever we try to instantiate an object __init__() is automatically invoked by python to initialize members of an object. We can’t overload constructors or methods in Python. It shows an error if we try to overload.


class student:
def __init__(self, name): = name
def __init__(self, name, email): = name = email

# This line will generate an error
#st = student(“rahul”)

# This line will call the second constructor
st = student(“rahul”, “”)
print(“Name: “,
print(“Email id: “,

11) What is the difference between remove() function and del statement?

The user can use the remove() function to delete a specific object in the list.


  1. list_1 = [ 3, 5, 7, 3, 9, 3 ]   
  2. print(list_1)  
  3. list_1.remove(3)   
  4. print(“After removal: “, list_1)  


[3, 5, 7, 3, 9, 3]
After removal: [5, 7, 3, 9, 3]

If you want to delete an object at a specific location (index) in the list, you can either use del or pop.


  1. list_1 = [ 3, 5, 7, 3, 9, 3 ]   
  2. print(list_1)  
  3. del list_1[2]  
  4. print(“After deleting: “, list_1)  


[3, 5, 7, 3, 9, 3]
After deleting: [3, 5, 3, 9, 3]

12) What is swapcase() function in the Python?

It is a string’s function which converts all uppercase characters into lowercase and vice versa. It is used to alter the existing case of the string. This method creates a copy of the string which contains all the characters in the swap case. If the string is in lowercase, it generates a small case string and vice versa. It automatically ignores all the non-alphabetic characters. See an example below.


  1. string = “IT IS IN LOWERCASE.”
  2. print(string.swapcase())  
  3. string = “it is in uppercase.”
  4. print(string.swapcase())  


it is in lowercase.

13) How to remove whitespaces from a string in Python?

To remove the whitespaces and trailing spaces from the string, Python providies strip([str]) built-in function. This function returns a copy of the string after removing whitespaces if present. Otherwise returns original string.


  1. string = ”  javatpoint “
  2. string2 = ”    javatpoint        “
  3. string3 = ”       javatpoint”
  4. print(string)  
  5. print(string2)  
  6. print(string3)  
  7. print(“After stripping all have placed in a sequence:”)  
  8. print(string.strip())  
  9. print(string2.strip())  
  10. print(string3.strip())  


After stripping all have placed in a sequence:

14) How to remove leading whitespaces from a string in the Python?

To remove leading characters from a string, we can use lstrip() function. It is Python string function which takes an optional char type parameter. If a parameter is provided, it removes the character. Otherwise, it removes all the leading spaces from the string.


  1. string = ”  javatpoint “
  2. string2 = ”    javatpoint        “
  3. print(string)  
  4. print(string2)  
  5. print(“After stripping all leading whitespaces:”)  
  6. print(string.lstrip())  
  7. print(string2.lstrip())  


After stripping all leading whitespaces:

After stripping, all the whitespaces are removed, and now the string looks like the below:

15) Why do we use join() function in Python?

The join() is defined as a string method which returns a string value. It is concatenated with the elements of an iterable. It provides a flexible way to concatenate the strings. See an example below.


  1. str = “Rohan”
  2. str2 = “ab”
  3. # Calling function
  4. str2 = str.join(str2)    
  5. # Displaying result
  6. print(str2)  



16) Give an example of shuffle() method?

This method shuffles the given string or an array. It randomizes the items in the array. This method is present in the random module. So, we need to import it and then we can call the function. It shuffles elements each time when the function calls and produces different output.


  1. # import the random module
  2. import random  
  3. # declare a list
  4. sample_list1 = [‘Z’, ‘Y’, ‘X’, ‘W’, ‘V’, ‘U’]  
  5. print(“Original LIST1: “)  
  6. print(sample_list1)  
  7. # first shuffle
  8. random.shuffle(sample_list1)  
  9. print(“\nAfter the first shuffle of LIST1: “)  
  10. print(sample_list1)  
  11. # second shuffle
  12. random.shuffle(sample_list1)  
  13. print(“\nAfter the second shuffle of LIST1: “)  
  14. print(sample_list1)  


Original LIST1:
['Z', 'Y', 'X', 'W', 'V', 'U']

After the first shuffle of LIST1:
['V', 'U', 'W', 'X', 'Y', 'Z']

After the second shuffle of LIST1:
['Z', 'Y', 'X', 'U', 'V', 'W']

17) What is the use of break statement?

The break statement is used to terminate the execution of the current loop. Break always breaks the current execution and transfer control to outside the current block. If the block is in a loop, it exits from the loop, and if the break is in a nested loop, it exits from the innermost loop.


  1. list_1 = [‘X’, ‘Y’, ‘Z’]  
  2. list_2 = [11, 22, 33]  
  3. for i in list_1:  
  4. for j in list_2:  
  5. print(i, j)  
  6. if i == ‘Y’ and j == 33:  
  7. print(‘BREAK’)  
  8. break
  9. else:  
  10. continue
  11. break


X 11
X 22
X 33
Y 11
Y 22
Y 33

Python Break statement flowchart.

18) What is tuple in Python?

A tuple is a built-in data collection type. It allows us to store values in a sequence. It is immutable, so no change is reflected in the original data. It uses () brackets rather than [] square brackets to create a tuple. We cannot remove any element but can find in the tuple. We can use indexing to get elements. It also allows traversing elements in reverse order by using negative indexing. Tuple supports various methods like max(), sum(), sorted(), Len() etc.

To create a tuple, we can declare it as below.


  1. # Declaring tuple
  2. tup = (2,4,6,8)  
  3. # Displaying value
  4. print(tup)  
  5. # Displaying Single value
  6. print(tup[2])  


(2, 4, 6, 8)

It is immutable. So updating tuple will lead to an error.


  1. # Declaring tuple
  2. tup = (2,4,6,8)  
  3. # Displaying value
  4. print(tup)  
  5. # Displaying Single value
  6. print(tup[2])  
  7. # Updating by assigning new value
  8. tup[2]=22
  9. # Displaying Single value
  10. print(tup[2])  


TypeError: 'tuple' object does not support item assignment
(2, 4, 6, 8)

19) Which are the file related libraries/modules in Python?

The Python provides libraries/modules that enable you to manipulate text files and binary files on the file system. It helps to create files, update their contents, copy, and delete files. The libraries are os, os.path, and shutil.

Here, os and os.path – modules include a function for accessing the filesystem

while shutil – module enables you to copy and delete the files.

20) What are the different file processing modes supported by Python?

Python provides four modes to open files. The read-only (r), write-only (w), read-write (rw) and append mode (a). ‘r’ is used to open a file in read-only mode, ‘w’ is used to open a file in write-only mode, ‘rw’ is used to open in reading and write mode, ‘a’ is used to open a file in append mode. If the mode is not specified, by default file opens in read-only mode.

  • Read-only mode (r): Open a file for reading. It is the default mode.
  • Write-only mode (w): Open a file for writing. If the file contains data, data would be lost. Other a new file is created.
  • Read-Write mode (rw): Open a file for reading, write mode. It means updating mode.
  • Append mode (a): Open for writing, append to the end of the file, if the file exists.

Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies, reach more readers and earn rewards!

Join other developers and claim your FAUN account now!


dridhOn Services


"World's #1 Online Certification IT Courses! dridhOn will provide you Best Software Training with Placement on all IT Courses."
User Popularity



Total Hits