For Course Enquiry -

+91 9985396677

Frequently Asked Python Interview Questions and Answers

1) What is Python?
Answer:

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 on different platforms such as Windows, Linux, UNIX, and Mac. 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 widely used for

a) Web development (server-side)

b) Software development

c) Mathematics

d) System scripting

2) Why Python?
Answer:

a) Python is an interpreted, object-oriented, high-level programming language with dynamic semantics

b) Python is compatible with different platforms like Windows, Mac, Linux, Raspberry Pi, etc.

c) Python has a simple syntax as compared to other languages.

d) Python allows a developer to write programs with fewer lines than some other programming languages.

e) Python runs on an interpreter system, means that the code can be executed as soon as it is written. 

f) Python can be described as a procedural way, an object-orientated way or a functional way.

g) 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 is a dynamically typed language?
Answer:

Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, will simply output "12" as result.

Type-checking can be done at two stages

a) Static - Data Types are checked before execution.

b) Dynamic - Data Types are checked during execution.

Python is an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language.

4) What is Scope in Python?
Answer:

Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix. 

A few examples of scope created during code execution in Python are as follows:

a) A local scope refers to the local objects available in the current function.

b) A global scope refers to the objects available throughout the code execution since their inception.

c) A module-level scope refers to the global objects of the current module accessible in the program.

d) An outermost scope refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced.

Note: Local scope objects can be synced with global scope objects using keywords such as global

5) What are the key features of Python?
Answer:

a) Free and Open Source: Python language is freely available at the official website and you can download it. Since it is open-source, this means that source code is also available to the public. So you can download it as, use it as well as share it.

a) Python is an interpreted language. That means that, unlike C & Java languages Python does not need to be compiled before it is run

b) Python is dynamically typed language, this means that you don’t need to state the types of variables when you declare them or anything like that. You can do things like x=111 and then x="I'm a string" without error

c) One of the key features of python is Object-Oriented programming. Python supports object-oriented language and concepts of classes, objects encapsulation, etc

d) GUI Programming Support: Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk in python. PyQt5 is the most popular option for creating graphical apps with Python.

e)Extensible feature: Python is a Extensible language. We can write us some Python code into C or C++ language and also we can compile that code in C/C++ language.

6) What type of language is python? Programming or scripting?
Answer:

Python is capable of scripting, but in general sense, it is considered as a general-purpose programming language.

7) How Python is an interpreted language?
Answer:

Python is an Interpreted Language because Python code is executed line by line at a time. Like other languages C, C++, Java, etc. there is no need to compile python code this makes it easier to debug our code. The source code of python is converted into an immediate form called bytecode.

8) What is pep 8?
Answer:

PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability.

9) What is Python? What are the benefits of using Python?
Answer:

Python is a programming language with objects, modules, threads, exceptions, and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure, and it is open-source.

10) How is Python interpreted?
Answer:

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

11) How is memory managed in Python?
Answer:

Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap, and the interpreter takes care of this Python private heap.

The allocation of Python heap space for Python objects is done by the Python memory manager. The core API gives access to some tools for the programmer to code.

Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space.

12) When is the else part of a try-except block executed?
Answer:

In an if-else block, the else part is executed when the condition in the if-statement is False. But with a try-except block, the else part executes only if no exception is raised in the try part.

13) If a list is nums=[0,1,2,3,4], what is nums[-1]?
Answer:

This code does not throw an exception. nums[-1] is 4 because it begins traversing from right

14) What is the PYTHONPATH variable?
Answer:

PYTHONPATH is the variable that tells the interpreter where to locate the module files imported into a program. Hence, it must include the Python source library directory and the directories containing Python source code. You can manually set PYTHONPATH, but usually, the Python installer will preset it.

15) What are the different file-processing modes with Python?
Answer:

We have the following modes

a) read-only – ‘r’

b) write-only – ‘w’

c) read-write – ‘rw’

d) append – ‘a’

We can open a text file with the option ‘t’. So to open a text file to read it, we can use the mode ‘rt’. Similarly, for binary files, we use ‘b’.

16) What happens if we do not handle an error in the except block?
Answer:

If we don’t do this, the program terminates. Then, it sends an execution trace to sys.stderr.

17) What are Python namespaces?
Answer:

A namespace in python refers to the name which is assigned to each object in python. The objects are variables and functions.

As each object is created, its name along with space(the address of the outer function in which the object is), gets created. 

The namespaces are maintained in python like a dictionary where the key is the namespace and value is the address of the object. 

There 4 types of namespace in python

a) Built-in namespace– These namespaces contain all the built in objects in python and are available whenever python is running.

b) Global namespace– These are namespaces for all the objects created at the level of the main program.

c) Enclosing namespaces– These namespaces are at the higher level or outer function.

d) Local namespaces– These namespaces are at the local or inner function.

18) Name four of the main data types in Python
Answer:

Numbers, strings, lists, dictionaries, tuples, files, and sets are generally considered the main types of data. Types, None, and Booleans are sometimes also classified this way. 

The integer, floating-point, complex, fraction and decimal are numerical data types and simple strings and Unicode strings in Python 2 and text strings and byte strings in Python 3 are the types of string data types.

19) What kind of language is Python?
Answer:

a) Python is a general-purpose programming language created by Guido Van Rossum in 1991. 

b) The official implementation of Python (CPython), is an interpreted language but other implementations allow you to compile your Python program as well.

c) Python is a strongly-typed language (since the interpreter keeps track of all the variables and their type) and a dynamically-typed language (since the type of the variables is checked at runtime by the Python interpreter).

d) It supports many programming paradigms and in particular procedural and object-oriented programming.

20) What’s the difference between a module and a package in Python?
Answer:

A module is just a single Python file you can import into other Python files to reuse code like functions, variables, objects, etc.

A package is a collection of modules stored in the same directory that allows you to better organize your code in a hierarchy of modules.

To create a package is really trivial. You just need to create a directory with a name of your choice, put inside this directory all the Python files you want to be considered as modules of this package, and then add a file named __init__.py. 

21) What is the difference between a local and a global variable in Python?
Answer:

The difference between a global and a local variable in Python is in their scope, which is the visibility they have from different parts of your program.

A local variable is a variable that can be accessed only inside the function it is defined into. 

A global variable is declared outside a function and so can be accessed globally, either inside or outside the function it is defined into.

22) What is the Difference Between A Shallow Copy and Deep Copy?
Answer:

Deepcopy creates a different object and populates it with the child objects of the original object. Therefore, changes in the original object are not reflected in the copy.

copy.deepcopy() creates a Deep Copy

Shallow copy creates a different object and populates it with the references of the child objects within the original object. Therefore, changes in the original object are reflected in the copy.

copy.copy creates a Shallow Copy

23) How Is Multithreading Achieved in Python?
Answer:

Multithreading usually implies that multiple threads are executed concurrently. The Python Global Interpreter Lock doesn't allow more than one thread to hold the Python interpreter at that particular point of time. So multithreading in python is achieved through context switching. It is quite different from multiprocessing which actually opens up multiple processes across multiple threads.

24) Explain Django Architecture?
Answer:

Django is a web service used to build your web pages. It contains below components

Template: The front end of the web page 

Model: The back end where the data is stored 

View: It interacts with the model and template and maps it to the URL

Django: Serves the page to the user 

25) Can Python be used for web client and web server side programming? Which one is best suited to Python?
Answer:

Python is best suited for web server-side application development due to its vast set of features for creating business logic, database interactions, web server hosting, etc.

However, Python can be used as a web client-side application that needs some conversions for a browser to interpret the client-side logic.

Note: Python can be used to create desktop applications that can run as a standalone application such as utilities for test automation.

26) What is PIP software in the Python world?
Answer:

PIP stands for Python Installer Package, which provides a seamless interface to install the various Python modules. It is a command-line tool that searches for packages over the Internet and installs them without any user interaction.

27) What should be the typical build environment for Python-based application development?
Answer:

We just need to install Python software and use PIP and then, you can install the various Python modules from the open-source community as per the requirement.

For IDE, Pycharm is highly recommended for any kind of application development with vast support for plugins. Another basic IDE is called a RIDE which is a part of the Python open-source community.

28) Which sorting technique is used by sort() and sorted() functions of python?
Answer:

Python uses Tim Sort algorithm for sorting. It’s a stable sorting whose worst case is O(N log N). It’s a hybrid sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data.

29) Differentiate between List and Tuple?
Answer:

List

a) Lists are Mutable datatype.

b) Lists consume more memory

c) The list is better for performing operations, such as insertion and deletion.

d) Implication of iterations is Time-consuming

Tuple

a) Tuples are Immutable datatype.

b) Tuple consume less memory as compared to the list

c) Tuple data type is appropriate for accessing the elements

d) Implication of iterations is comparatively Faster

30) What are Decorators?
Answer:

Decorators are one of the most helpful and powerful tools of Python. These are used to modify the behavior of the function. Decorators provide the flexibility to wrap another function to expand the working of wrapped function, without permanently modifying it.

It is also called meta programming where a part of the program attempts to change another part of program at compile time.

31) How are arguments passed by value or by reference in Python?
Answer:

Everything in Python is an object and all variables hold references to the objects. The reference values are according to the functions; as a result, you cannot change the value of the references. However, you can change the objects if it is mutable.

32) How are arguments passed by value or by reference in Python?
Answer:

Everything in Python is an object and all variables hold references to the objects. The reference values are according to the functions; as a result, you cannot change the value of the references. However, you can change the objects if it is mutable.

33) What are Iterators in Python?
Answer:

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 the next() method to iterate the stored elements. In Python, we generally use loops to iterate over the collections (list, tuple).

34) What are Generators in Python?
Answer:

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 reduces 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 resumes from the same when required.

35) What is NumPy array?
Answer:

NumPy arrays are more flexible than lists in Python. By using NumPy arrays reading and writing items is faster and more efficient.

36) What is a negative index in Python?
Answer:

A Pass statement in Python is used when we cannot decide what to do in our code, but we must type something for making syntactically correct.

37) What are the limitations of Python?
Answer:

There are certain limitations of Python, which include the following:

a) It has design restrictions

b) Performance and Speed when compared with C and C++ or Java

c) Weak in Mobile Computing

d) Does not Provide Prebuilt Statistical Models and Tests

d) It consists of an underdeveloped database access layer

38) How are identity operators different than the membership operators?
Answer:

Unlike membership operators, the identity operators compare the values to find out if they have the same value or not.

39) What are lists in Python?
Answer:

Lists are fundamentally sequenced data types in Python used to store a collection of objects. Lists in Python are represented using square brackets.

40) What is Object in Python
Answer:

Object in Python is a user-defined data type or instance of a class. It is an entity that exhibits behavior and state defined by the Class.

41) Explain most widely-used built-in data types in Python?
Answer:

The standard built-in data types in Python include

None Type

Numeric Types

Mapping Types

Sequence Types

Callable Types

Modules

Set Types

42) How to convert a number into a string?
Answer:

We can use the inbuilt str() function. For an octal or hexadecimal representation, we can use the other inbuilt functions like oct() or hex().

43) Does Python have a Switch or Case statement like in C?
Answer:

 No, it does not. However, we can make our own Switch function and use it. 

44) What is PYTHONPATH?
Answer:

PYTHONPATH is an environment variable that is used to incorporate additional directories when a module/package is imported. Whenever a module/package is imported, PYTHONPATH is used to check if the imported modules are present in the existing directories. Usually, the interpreter uses PYTHONPATH to determine which module to load.

45) Why do we need break and continue in Python?
Answer:

Both break and continue are statements that control flow in Python loops. break stops the current loop from executing further and transfers the control to the next block. continue jumps to the next iteration of the loop without exhausting it.

46) Can we use a break and continue together in Python?
Answer:

Break and continue can be used together in Python. The break will stop the current loop from execution, while jump will take to another loop.

47) Explain Inheritance and its various types in Python?
Answer:

Inheritance enables a class to acquire all the members of another class. These members can be attributes, methods, or both. By providing reusability, inheritance makes it easier to create as well as maintain an application.

The class which acquires is known as the child class or the derived class. The one that it acquires from is known as the superclass or base class or the parent class. There are 4 forms of inheritance supported by Python:

Single Inheritance – A single derived class acquires from on single superclass

Multi-Level Inheritance – At least 2 different derived classes acquire from two distinct base classes

Hierarchical Inheritance – A number of child classes acquire from one superclass

Multiple Inheritance – A derived class acquires from several superclasses

48) How will you distinguish between NumPy and SciPy?
Answer:

Typically, NumPy contains nothing but the array data type and the most basic operations, such as basic element-wise functions, indexing, reshaping, and sorting. All the numerical code resides in SciPy.

As one of NumPy’s most important goals is compatibility, the library tries to retain all features supported by either of its predecessors. Hence, NumPy contains a few linear algebra functions despite the fact that these more appropriately belong to the SciPy library.

SciPy contains fully-featured versions of the linear algebra modules available to NumPy in addition to several other numerical algorithms.

49) What is Flask and what are the benefits of using it?
Answer:

Flask is a web microframework for Python with Jinja2 and Werkzeug as its dependencies. As such, it has some notable advantages:

a) Flask has little to no dependencies on external libraries

b) Because there is a little external dependency to update and fewer security bugs, the web microframework is lightweight to use.

c) Features an inbuilt development server and a fast debugger.

50) Why do we use Pythonstartup environment variable?
Answer:

We use the Pythonstartup environment variable because it consists of the path in which the initialization file carrying Python source code can be executed to start the interpreter.