Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python’s design philosophy emphasizes code readability with its notable use of significant whitespace.
Nowadays the popularity of python is increasing day by day. Python is easy to learn and has vast libraries. In the field of Machine Learning, Deep Learning and Artificial Intelligence Python are the top priority in the implementation tool. You can find on google the trends of top programming languages.
Since the demand and popularity are on top, so the career opportunity in Python programming and related fields is high. Keeping this in mind we have created a set of some useful Python Interview Questions and Answers, so that one may find a proper guide for an Interview.
Python Interview Questions are very useful when you are going for an Interview for the designation of Python Developer or Machine Learning or any Related fields to Python. These python interview questions and answers are equally useful for freshers and experienced.
While representing this set of questions along with answers we hope that they will be useful for visitors.
What is Python?
Python is an Interpreted programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, built-in data structure and it is open-source.
What are the key features of Python?
- Python is an interpreted language. That means Python does not need to be compiled before it is run.
- Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that.
- Python is well suited to object-orientated programming in that it allows the definition of classes along with composition and inheritance.
- In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first-class objects
- Writing Python code is quick but running it is often slower than compiled languages. Fortunately，Python allows the inclusion of C based extensions so bottlenecks can be optimized away and often are.
What type of language is python? Programming or scripting?
Python is capable of scripting, but in a general sense, it is considered as a general-purpose programming language.
What is PEP 8?
PEP 8 is a coding convention, a set of recommendations about how to write your Python code more readable.
What are Python packages?
Python packages are namespaces containing multiple modules.
What is the difference between abs () and fabs ()?
abs() is a built-in function that works with integer, float and complex numbers also.
fabs() is defined in the math module which doesn’t work with complex numbers.
How Python is interpreted?
Python is an interpreted language because 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.
How memory is managed in Python?
Python has an awesome feature of memory management. The following points will explain memory management in python:
- 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 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.
What are the tools that help to find bugs or perform the static analysis?
PyChecker is a static analysis tool that detects bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.
What are Python decorators?
A Python decorator is a specific change that we make in Python syntax to alter functions easily.
What is the difference between list and tuple?
The difference between list and tuple is that the list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.
How are arguments passed by value or by reference?
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.
What is Dict and List comprehensions are?
They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.
What is the built-in type does python provides?
There are mutable and Immutable types of Pythons built-in types Mutable built-in types
Immutable built-in types
What is namespace in Python?
In Python, every name introduced has a place where it lives and can be hooked for. This is known as a namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get the corresponding object.
What is the difference between deep and shallow copy?
Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.
A deep copy is used to store the values that are already copied. The deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.
What is lambda in Python?
It is a single expression anonymous function often used as an inline function.
Why lambda forms in python does not have statements?
A lambda form in python does not have statements as it is used to make a new function object and then return them at runtime.
Does python support multiple inheritances?
Multiple inheritances mean that a class can be derived from more than one parent class. Python does support multiple inheritances, unlike Java.
What is a pass in Python?
Pass means, no-operation Python statement, or in other words, it is a place holder in a compound statement, where there should be a blank left and nothing has to be written there.
What is Polymorphism in Python?
Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.
What is encapsulation in Python?
Encapsulation means binding the code and the data together. A Python class is an example of encapsulation.
How do you do data abstraction in Python?
Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.
How to use access specifiers?
Python does not deprive access to an instance variable or function. Python lays down the concept of prefixing the name of the variable, function or method with a single or double underscore to imitate the behavior of protected and private access specifiers.
In Python what are iterators?
In Python, iterators are used to iterate a group of elements, containers like a list.
What is the unit test in Python?
A unit testing framework in Python is known as a unit test. It supports the sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections, etc.
Explain what Flask is and its benefits?
Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of its dependencies. This means it will have little to no dependencies on external libraries. It makes the framework light while there is a little dependency to update and fewer security bugs.
A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify it. The user can modify the session if only it has the secret key Flask.secret_key.
In Python what is slicing?
A mechanism to select a range of items from sequence types like list, tuple, strings, etc. is known as slicing.
What are the generators in Python?
The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.
What is PYTHONPATH?
It is an environment variable that is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.
What is type conversion in Python?
Type conversion refers to the conversion of one data type into another.
int() : converts any data type into integer type
float() : converts any data type into float type
ord() : converts characters into integer
hex() : converts integers to hexadecimal
oct() : converts integer to octal
tuple() : This function is used to convert to a tuple.
set() : This function returns the type after converting to set.
list() : This function is used to convert any data type to a list type.
dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
str() : Used to convert integer into a string.
What is docstring in Python?
A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.
How can you copy an object in Python?
To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.
What is a negative index in Python?
Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.
How you can convert a number to a string?
In order to convert a number into a string, use the inbuilt function str(). If you want an octal or hexadecimal representation, use the inbuilt function oct() or hex().
What is the difference between Xrange and range?
Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.
Mention the differences between Django, Pyramid, and Flask.
- Flask is a “microframework” primarily build for a small application with simpler requirements. In a flask, you have to use external libraries. Flask is ready to use.
- Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
- Django can also be used for larger applications just like Pyramid. It includes an ORM.
What is module and package in Python?
In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.
The folder of Python program is a package of modules. A package can have modules or subfolders.
Why indentation required in python?
Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
Mention what are the rules for local and global variables in Python?
Local variables: If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be local.
Global variables: Those variables that are only referenced inside a function are implicitly global.
List out the inheritance styles in Django.
In Django, there are three possible inheritance styles:
- Abstract Base Classes: This style is used when you only want the parent’s class to hold information that you don’t want to type out for each child model.
- Multi-table Inheritance: This style is used If you are sub-classing an existing model and need each model to have its own database table.
- Proxy models: You can use this model, If you only want to modify the Python level behavior of the model, without changing the model’s fields.
Why are local variable names beginning with an underscore discouraged?
- they are used to indicate a private variables of a class
- they confuse the interpreter
- they are used to indicate global variables
- they slow down execution
What is the purpose of the PYTHONCASEOK environment variable?
PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.
Explain how can you make a Python Script executable on Unix?
To make a Python Script executable on Unix, you need to do two things,
- Script file’s mode must be executable and
- the first line must begin with # ( #!/usr/local/bin/python)
How can you share global variables across modules?
To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.
What are the supported data types in Python?
Python has five standard data types −
Explain how to delete a file in Python?
By using a command os.remove (filename) or os.unlink(filename)
Explain how you can generate random numbers in Python?
To generate random numbers in Python, you need to import command as
This returns a random floating-point number in the range [0,1)
What is self in Python?
Self is an instance of an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it’s optional. It helps to differentiate between the methods and attributes of a class with local variables.
The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.
What are tuples in Python?
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
How will you check if all characters in a string are alphanumeric?
We will use the method isalnum().
Does Python allow you to program in a structured style?
Yes. It does allow to code is structured as well as Object-oriented style. It offers excellent flexibility to design and implement your application code depending on the requirements of your application.
Explain how can you access a module written in Python from C?
You can access a module written in Python from C by following method,
Module = =PyImport_ImportModule(“<modulename>”);
Mention the use of // operator in Python?
It is a Floor Divisionoperator, which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.
Mention five benefits of using Python?
- Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
- Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
- Provide easy readability due to use of square brackets
- Easy-to-learn for beginners
What is module and package in Python?
In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.
The folder of the Python program is a package of modules. A package can have modules or subfolders.
What is difference between pickling and unpickling?
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using a dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
- Having the built-in data types saves programming time and effort from declaring variables
What is a dictionary in Python?
Ans: The built-in data types in Python are called the dictionary. It defines one-to-one relationships between keys and values. Dictionaries contain a pair of keys and their corresponding values. Dictionaries are indexed by keys.
Mention the use of the split function in Python?
The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all the words present in the string.
What tools can be used to unit test your Python code?
The best and easiest way is to use ‘unittest’ python standard library to test units/classes. The features supported are very similar to the other unit testing tools such as JUnit, TestNG.
What is the starting point of Python code execution?
As Python is an interpreter, it starts reading the code from the source file and starts executing them.
Explain what is Flask & its benefits?
Flask is a web microframework for Python based on “Werkzeug, Jinja 2 and good intentions” BSD licensed. Werkzeug and jinja are two of its dependencies.
Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is a little dependency to update and fewer security bugs.
Mention what is the difference between Django, Pyramid, and Flask?
Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.
The pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. The pyramid is heavily configurable.
Like Pyramid, Django can also used for larger applications. It includes an ORM.
How to comment on multiple lines in python?
Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment on multiple lines. All you need to do is hold the ctrl key and left-click in every place wherever you want to include a # character and type a # just once. This will comment on all the lines where you introduced your cursor.
Which module(s) of Python can be used to measure the performance of your application code?
Time module can be used to calculate the time at different stages of your application and use the Logging module to log data to a file system in any preferred format.
Mention what is Flask-WTF and what are their features?
Flask-WTF offers simple integration with WTForms. Features include for Flask WTF are
- Integration with wtforms
- Secure form with csrf token
- Global csrf protection
- Internationalization integration
- Recaptcha supporting
- File upload that works with Flask Uploads
Does the same Python code work on multiple platforms without any changes?
As long as you have the Python environment on your target platform (Linux, Windows, Mac), you can run the same code.
How do you make use of Arrays in Python?
Python does not support Arrays. However, you can use List collection type which can store an unlimited number of elements.
Explain what is the common way for the Flask script to work?
The common way for the flask script to work is
- Either it should be the import path for your application
- Or the path to a Python file
What are the different environment variables identified by Python?
PYTHONPATH: This environment variable helps the interpreter as to where to locate the module files imported in the program.
PYTHONSTARTUP: This environment variable contains the path of the Initialization file containing the source code.
PYTHONCASEOK: This variable is used to find the first case-insensitive match in the import statement
Explain how you can access sessions in Flask?
A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify them. The user can modify the session if only it has the secret key Flask.secret_key.
What are a help () and dir() in python?
help() is a built-in function that can be used to return the Python documentation of a particular object, methods, attributes, etc.
dir() displays a list of attributes for the objects which are passed as an argument. If dir() is without the argument then it returns a list of names in current local space.
What is the difference between locals() and globals ()?
locals() is accessed within the function and it returns all names that can be accessed locally from that function.