Javatpoint Logo
Javatpoint Logo

Python Interview Questions

Python Interview Questions

A list of frequently asked Python interview questions with answers for freshers and experienced are given below.

1) What is Python?

Python 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. 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.


2. 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 Interview Questions

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.


3. What are the advantages of Python?

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

4. What is PEP 8?

PEP 8 is a coding convention which specifies a set of guidelines, about how to write Python code more readable.

It's a set of rules to guide how to format your Python code to maximize its readability. Writing code to a specification helps to make significant code bases, with lots of writers, more uniform and predictable, too.


5. 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.

E.g.:

"Aman", '12345'.

Numeric Literals

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

Boolean Literals

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


6. 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 two 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.

Example: A general syntax of user defined function is given below.


7. What is zip() function in Python?

The Python zip() function is used to transform multiple lists, i.e., list1, list2, list3 and many more into a single list of tuples. This method takes an iterable and returns a tuple of the iterable. If we don't pass iterable, it returns an empty iterator. See this example:

Note: If the given lists are of different lengths, zip stops generating tuples when the first list ends. It means two lists are having 3, and 5 lengths will create a 3-tuple.


8. 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.

Python Interview Questions

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 Interview Questions

Python has a default argument concept which helps to call a method using an arbitrary number of arguments.


9. 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.


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

The del statement is used to remove list, dictionary or a key. We need to pass an index which we want to delete. Del is a fast way to remove elements from the list.

The remove() method is used to remove elements from the list. It searches the element before deleting which makes it slower than del. Del and remove both are used to remove element but del has a performance edge over remove. See an example.

Output:

[50, 100, 12, 300, 20, 10] 
[50, 100, 12, 300, 10]
 [50, 100, 300, 20, 10]

11. 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.

it is in lowercase. 
IT IS IN UPPERCASE. 

12. 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.

javatpoint 
    javatpoint        
       javatpoint

After stripping all have placed in a sequence:

javatpoint

javatpoint

javatpoint


13. 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.

javatpoint 
    javatpoint        
After stripping all leading whitespaces:
javatpoint 
javatpoint
Python Interview Questions

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

Python Interview Questions

14. Why do we use join() function in Python?

This method is used to concatenate a string with an iterable object. It returns a new string which is the concatenation of the strings in iterable. It throws an exception TypeError if iterable contains any non-string value. See an example below.

aRohanb

15) 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.

[12, 25, 15, 65, 58, 14, 5] 
Reshuffled list :
 [58, 15, 5, 65, 12, 14, 25] 

16) What is the use of break statement?

It 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.

2
4
6
8
10
odd value found 11
Python Interview Questions

Python Break statement flowchart.


17. 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.

(2, 4, 6, 8)
6
Python Interview Questions

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

   tup[2]=22 
TypeError: 'tuple' object does not support item assignment 
(2, 4, 6, 8)
Python Interview Questions

18. Which are the file related libraries/modules in Python?

Python provides libraries/modules including functions that facilitate us to manipulate text files and binary files on the file system. By using these libraries, we can create files, update their contents, copy, and delete files.

These libraries are os, os.path, and the shutil.

os and os.path: os and os.path libraries include functions for accessing the filesystem.

shutil: This library is used to copy and delete the files.


19. What are the different file processing modes supported by Python?

Python provides three modes to open files. The read-only, write-only, read-write and append mode. '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 : Open a file for reading. It is the default mode.
  • Write-only mode: Open a file for writing. If the file contains data, data would be lost. Other a new file is created.
  • Read-Write mode: Open a file for reading, write mode. It means updating mode.
  • Append mode: Open for writing, append to the end of the file, if the file exists.

20. What is an operator in Python?

An operator is a particular symbol which is used on some values and produces an output as a result. An operator works on operands. Operands are numeric literals or variables which hold some values. Operators can be unary, binary or ternary. An operator which require a single operand known as a unary operator, which require two operands known as a binary operator and which require three operands is called ternary operator.

Python Interview Questions

For example:


21. What are the different types of operators in Python?

Python uses a rich set of operators to perform a variety of operations. Some individual operators like membership and identity operators are not so familiar but allow to perform operations.

  • Arithmetic OperatorsRelational Operators
  • Assignment Operators
  • Logical Operators
  • Membership Operators
  • Identity Operators
  • Bitwise Operators
Python Operator Interview Questions

Arithmetic operators perform basic arithmetic operations. For example "+" is used to add and "?" is used for subtraction.

Relational Operators are used to comparing the values. These operators test the conditions and then returns a boolean value either True or False.

# Examples of Relational Operators

Assignment operators are used to assigning values to the variables. See the examples below.

Logical operators are used to performing logical operations like And, Or, and Not. See the example below.

Membership operators are used to checking whether an element is a member of the sequence (list, dictionary, tuples) or not. Python uses two membership operators in and not in operators to check element presence. See an example.

Identity Operators (is and is not) both are used to check two values or variable which are located on the same part of the memory. Two variables that are equal does not imply that they are identical. See the following examples.

Bitwise Operators are used to performing operations over the bits. The binary operators (&, |, OR) work on bits. See the example below.


22) How to create a Unicode string in Python?

In Python 3, the old Unicode type has replaced by "str" type, and the string is treated as Unicode by default. We can make a string in Unicode by using art.title.encode("utf-8") function.


23) is Python interpreted language?

Python is an interpreted language. The Python language program runs directly from the source code. It converts the source code into an intermediate language code, which is again translated into machine language that has to be executed.

Unlike Java or C, Python does not require compilation before execution.

Python Interview Questions

24) How is memory managed in Python?

Memory is managed in Python by the following way:

  • Python uses private heap space to manage Python programs into memory. All Python objects and data structures located in a private heap. The programmer does not have access to this private heap and interpreter takes care of this Python private heap.
  • Python memory manager is responsible for allocating Python heap space for Python objects.
  • Python also has an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

25) What is the Python decorator?

Python decorator is a concept which allows to call or declare a function inside a function, pass a function as an argument, return a function from the function. The decorator provides extra facility to the function. It also helps to organize a piece of code within a function.

Functions vs. Decorators

A function is a block of code that performs a specific task whereas a decorator is a function that modifies other functions.


26) What are the rules for a local and global variable in Python?

In Python, variables that are only referenced inside a function are called implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and we need to declare it as 'global' explicitly. To make a variable globally, we need to declare it by using global keyword. Local variables are accessible within local body only. Global variables are accessible anywhere in the program, and any function can access and modify its value.


27) What is the namespace in Python?

In Python, every name has a place where it lives. It is known as a namespace. It is like a box where a variable name maps to the object placed. Whenever the variable is searched out, this box will be searched, to get the corresponding object.


28) What are iterators in Python?

In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are the collection of items, and it can be a list, tuple, or a dictionary. Python iterator implements __itr__ and next() method to iterate the stored elements. In Python, we generally use loops to iterate over the collections (list, tuple).


29) What is a generator in Python?

In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that it yields expression in the function. It does not implements __itr__ and next() method and reduce other overheads as well.

If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current execution by saving its states and then resume from the same when required.


30) What is slicing in Python?

Slicing is a mechanism used to select a range of items from sequence type like list, tuple, and string. It is beneficial and easy to get elements from a range by using slice way. It requires a : (colon) which separates the start and end index of the field. All the data collection types List or tuple allows us to use slicing to fetch elements. Although we can get elements by specifying an index, we get only single element whereas using slicing we can get a group of elements.

Python Interview Questions

31) What is a dictionary in Python?

The Python dictionary is a built-in data type. It defines a one-to-one relationship between keys and values. Dictionaries contain a pair of keys and their corresponding values. It stores elements in key and value pairs. The keys are unique whereas values can be duplicate. The key accesses the dictionary elements.

Keys index dictionaries.

Let's take an example.

The following example contains some keys Country Hero & Cartoon. Their corresponding values are India, Modi, and Rahul respectively.


32) What is Pass in Python?

Pass specifies a Python statement without operations. It is a placeholder in a compound statement. If we want to create an empty class or functions, this pass keyword helps to pass the control without error.


33) Explain docstring in Python?

A Python documentation string is called docstring. It is used for documenting Python functions, modules and classes. It should be the first statement in a module, class or function.

String literals occurring immediately after a simple assignment at the top are called "attribute docstrings".

String literals occurring immediately after another docstring are called "additional docstrings".

Python uses triple quotes to create docstrings even though the string fits on one line.

Docstring phrase ends with a period (.) and can be multiple lines. It may consist of spaces and other special chars.

Example


34) What is a negative index in Python?

Python sequences are accessible using an index in positive and negative numbers. For example, 0 is the first positive index, 1 is the second positive index and so on. For negative indexes -1 is the last negative index, -2 is the second last negative index and so on.

Index traverses from left to right and increases by one until end of the list.

Negative index traverse from right to left and iterate one by one till the start of the list. A negative index is used to traverse the elements into reverse order.


35) What is pickling and unpickling in Python?

Pickling is a process in which a pickle module accepts any Python object, converts it into a string representation and dumps it into a file by using dump() function.

Unpickling is a process of retrieving original Python object from the stored string representation for use.

Pickle is a standard module which serializes and de-serializes a Python object structure.


36) Which programming language is a good choice between Java and Python?

Java and Python both are object-oriented programming languages. Let's compare both on some criteria given below:

Criteria Java Python
Ease of use Good Very Good
Coding Speed Average Excellent
Data types Static type Dynamic type
Data Science and Machine learning application Average Very Good

37) What is the usage of help() and dir() function in Python?

Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.

Help() function: The help() function is used to display the documentation string and also facilitates us to see the help related to modules, keywords, and attributes.

Dir() function: The dir() function is used to display the defined symbols.


38) How can we make forms in Python?

You have to import CGI module to access form fields using FieldStorage class.

Attributes of class FieldStorage for the form:

form.name: The name of the field, if specified.

form.filename: If an FTP transaction, the client-side filename.

form.value: The value of the field as a string.

form.file: file object from which data read.

form.type: The content type, if applicable.

form.type_options: The options of the 'content-type' line of the HTTP request, returned as a dictionary.

form.disposition: The field 'content-disposition'; None, if unspecified.

form.disposition_options: The options for 'content-disposition'.

form.headers: All of the HTTP headers returned as a dictionary.


40) What are the differences between Python 2.x and Python 3.x?

Python 2.x is an older version of Python. Python 3.x is newer and latest version. Python 2.x is legacy now. Python 3.x is the present and future of this language.

The most visible difference between Python2 and Python3 is in print statement (function). In Python 2, it looks like print "Hello", and in Python 3, it is print ("Hello").

String in Python2 is ASCII implicitly, and in Python3 it is Unicode.

The xrange() method has removed from Python 3 version. A new keyword as is introduced in Error handling.


41) How can you organize your code to make it easier to change the base class?

You have to define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. You can also use this method if you want to decide dynamically (e.g., depending on availability of resources) which base class to use.

Example


43) How Python does Compile-time and Run-time code checking?

In Python, some amount of coding is done at compile time, but most of the checking such as type, name, etc. are postponed until code execution. Consequently, if the Python code references a user-defined function that does not exist, the code will compile successfully. The Python code will fail only with an exception when the code execution path does not exist.


44) What is the shortest method to open a text file and display its content?

The shortest way to open a text file is by using "with" command in the following manner:


45) What is the usage of enumerate () function in Python?

The enumerate() function is used to iterate through the sequence and retrieve the index position and its corresponding value at the same time.


46) Give the output of this example: A[3] if A=[1,4,6,7,9,66,4,94].

Since indexing starts from zero, an element present at 3rd index is 7. So, the output is 7.


47) What will be the output of ['!!Welcome!!']*2?

The output will be ['!!Welcome!! ', '!!Welcome!!']


48) What will be the output of data[-2] from the list data = [1,5,8,6,9,3,4]?

In the list, an element present at the 2nd index from the right is 3. So, the output will be 3.


49. How to send an email in Python Language?

To send an email, Python provides smtplib and email modules. Import these modules into the created mail script and send mail by authenticating a user.

It has a method SMTP(smtp-server, port). It requires two parameters to establish SMTP connection.

A simple example to send an email is given below.

It will send an email to the receiver after authenticating sender username and password.