Loading…

Python Interview Questions

By Umesh Singh
Last update: 02 Jun 2020, 45 Questions
Introduction to Python
Python Interview Questions

A high-level, interactive and object-oriented scripting language, Python is a highly readable language that makes it ideal for beginner-level programmers.  Here we can help you to prepare for the best Python interview questions. It uses English keywords and has fewer syntactical constructions as compared to other languages. Similar to PERL and PHP, Python is processed by the interpreter at runtime. Python supports the Object-Oriented style of programming, which encapsulates code within objects.

Key Points of Python
  • Similar to PERL and PHP, Python is processed by the interpreter at runtime. Python supports Object-Oriented style of programming, which encapsulates code within objects.
  • Derived from other languages, such as ABC, C, C++, Modula-3, SmallTalk, Algol-68, Unix shell, and other scripting languages.
  • Python is copyrighted, and its source code is available under the GNU General Public License (GPL).
  • Supports the development of many applications, from text processing to games.
  • Works for scripting, embedded code and compiled the code.
  • Detailed

If you are looking for a job as a Python developer, we have a vast collection of python coding interview questions .

Quick Questions about Python
What is Python? Python is a high-level, interactive and object-oriented scripting language.
What is the latest version of Python? 3.8.2 and released on February 26, 2020
Created By Guido van Rossum in 1990.
What language does Python use? C languages
License Python releases have also been GPL-compatible.
Official Website https://www.python.org

Most Frequently Asked Python Interview Questions And Answers

1. What are the main features of Python?
Here are some important features of Python:
  • Being easy to learn, it is considered as the best language for beginner developers.
  • It is an interpreted language.
  • It is cross-platform in nature.
  • Free and Open source
  • It is based on an Object-Oriented Programming Language (OOPS)
  • It has extensive in-built libraries
2. What is self variable in Python?

In Python, a self variable is used for binding the instance within the class to the instance inside the method. In this, to access the instance variables and methods, we have to explicitly declare it as the first method argument.

Example

                                                    

class Dog:
    def __init__(self, breed):
        self.breed = breed
    def bark(self):
        print(f'{self.breed} is continuously barking.')
d = Dog('German Shepherd')
d.bark()

Output
German Shepherd is continuously barking.

3. What is PEP 8?

PEP in Python stands for Python Enhancement Proposal. The PEP 8 is basically Python’s style guide. It helps in writing code to specific rules making it helpful for large codebases having multiple writers by bringing a uniform and predictive writing style.

4. How is it possible to share global variables across various modules?

In order to share global variables across different modules within a single program, you need to create a special module. After that, just import the config module in all of the modules of your application. This will make the module available as a global variable across all the modules.

5. Why is flask used in Python?

A Flask is a micro web framework for Python based on the "Werkzeug, Jinja 2 and good intentions". Werkzeug and jingja are its dependencies. Because a Flask is part of the micro-framework, it has little or no dependencies on the external libraries. A Flask also makes the framework light while taking little dependency and gives fewer security bugs.

Note: These python programming interview questions have been designed specially to get you familiar with the nature of questions.

6. What is the difference between list and tuples?
Tuples Lists
Items in a tuple are surrounded by a parenthesis () Items are surrounded in square brackets [ ]
They are immutable in nature Lists are by nature immutable
There are 33 available methods in it. There are 46 methods here.
Keys can be created using Tuples. No, keys can’t be created using these
7. How is Python interpreted?

Python is an interpreted language. It runs directly from the source code and converts the source code into an intermediate language. This intermediate language is translated into machine language and has to be executed.

8. What is pickling and unpickling?

The process of picking can be defined as: Pickle, which is a module, accepts an object, converts it into a string, and dumps into a file using dump function.

The process of retrieving Python objects from the stored string is called unpickling.

9. How we can copy an object in Python? In Python, we can use try copy.copy () or copy.deepcopy() for copy an object.
10. How are arguments passed - by reference or by value?

Everything in Python is like an object. All variables hold different references to the objects. The values of references are as per their functions. As a result, the programmer cannot change the value of the references. However, he can change the objects if they are mutable.

11. How can you access a session in Flask?

A session allows the programmer to remember information from one request to another. In a flask, a session uses a signed cookie so that the user can look at the contents and modify. The programmer will be able to modify the session only if it has the secret key Flask.secret_key.

12. What is lambda? Why do lambda forms not have statements?

Lambda is an anonymous expression function that is often used as an inline function. Its form does not have a statement as it is only used to make new functional objects and then return them at the runtime.

13. What is the module and package in Python?

The module is a way to structure a program. Each Python program is a module, which imports other modules such as objects and attributes. The entire folder of the Python program is a package of modules. A package can have both modules or subfolders.

14. How to create an empty class in Python?

In Python, an empty class can be created by using the “pass” command. This can be done only after the defining of the class object because at least one line of code is mandatory for creating a class. Here’s an example of how to create an empty class:

Example

                                                    

class customer:
    pass

customer1 = customer()

customer1.first_name = 'Jason'
customer1.last_name = 'Doe'

15. What is the use of Xrange in Python?

In Python, the use of the xrange() function is to generate a sequence of numbers that are similar to the range() function. But, the xrange() function is used only in Python 2. xx whereas the range() is used in Python 3.

16. How is memory managed in Python?

Memory is managed by the private heap space. All objects and data structures are located in a private heap, and the programmer has no access to it. Only the interpreter has access. Python memory manager allocates heap space for objects. The programmer is given access to some tools for coding by the core API. The inbuilt garbage collector recycles the unused memory and frees up the memory to make it available for the heap space.

Note: This is a type of most frequently asked python developer interview questions.

17. What is a negative index in Python?

Indexing Python sequences in both positive and negative numbers are possible. For the positive index, 0 is the first index, 1 is the second index and so forth. For the negative index, (-1) is the last index and (-2) is the second last index and so forth.

18. What is pass in Python? What are the differences between pass and continue?

Pass means where there is a no-operation Python statement. It is just a placeholder in a compound statement where nothing needs can be written. The continue makes the loop to resume from the next iteration.

19. Why multithreading is not possible in python?

One of the many confusing questions in Python, yes, Python does support threading, but, due to the presence of GIL multi-threading is not supported. The GIL basically does not support the running of multiple CPU cores parallelly, hence, multithreading is not supported in Python.

20. Name the arithmetic operators supported by Python.

Python does not support the unary operators; rather, it supports augmented assignment operators.

The arithmetic operators it supports are as follows-
  • Addition- '+'
  • Subtraction- '-'
  • Multiplication- '*'
  • Division- '/:
  • Modulo division- '%'
  • Power of- '**'
  • Floor div- '//'
21. What is MRO in python?

Method resolution order or MRO refers to when one class inherits from multiple classes. The class that gets inherited is the parent class and the class that inherits is the child class. It also refers to the order where the base class is searched while executing the method.

22. What is the use of repr function in Python?

This function returns to a printable presentation for the given object. It takes a single object & its syntax is repr(obj). The function repr computes all the formal string representation for the given object in Python.

23. Narrate the difference between Python arrays and lists.

Both lists and arrays in Python can store the data in the same way.
The difference is-

Array List
An array can hold single data type elements. Lists in Python can hold any type of data element.
24. What is Python magic method?

It refers to the method which adds a certain value to the class. It can’t be initiated by the user rather only occurs when an internal action takes charge. In python, the built-in classes define a number of magic methods.

25. What is the difference between repr and str in Python?
Repr() Str()
It is unambiguous It is readable
It can be implemented for any class Implement in case of the string version
Used to compute official Used to compute informally
It displays object Displays string representations
26. What is Python?

A high-level, interactive, and object-oriented scripting language, Python is a highly readable language that makes it ideal for beginner-level programmers. It uses English keywords and has fewer syntactical constructions as compared to other languages.

27. What is typecasting in python?

The entity that changes the data types from one form to another is known as typecasting. In programming languages, it is used to make sure the variables are processed in the correct sequence by the function.

E.g., while converting an integer to string.

28. What is the type () in Python?

The built-in method which decides the types of the variable at the program runtime is known as type() in Python. When a single argument is passed through it, then it returns given object type. When 3 arguments pass through this, then it returns a new object type.

29. Do you know the number of keywords in Python? Why should you know them all?

In total, there are 33 keywords in Python. It is important to know them all in order to know about their use so we can utilize them. In additon, while we are naming a variable, the name cannot be matched with the keywords. This is another reason to know all the keywords.

30. What tools can help find bugs or perform the static analysis?

For performing Static Analysis, PyChecker is a tool that detects the bugs in source code and warns the programmer about the style and complexity. Pylint is another tool that authenticates whether the module meets the coding standard.

31. What are decorators?

Decorators are specific changes that we make in syntax to alter functions.

32. What are Dict and List comprehensions?

Dict and List are syntax constructions that ease the creation of a Dictionary or List based on iterables.

33. What are the differences between Pyramid, Django, and Flask?

A Flask is a microframework build for small applications with more straightforward requirements. Flask comes ready to use.

Pyramids are built for larger applications. They provide flexibility and allow the developer to use the right tools for their projects. The developer is free to choose the database, templating style, URL structure, and more. Pyramids is configurable.

Similar to Pyramids, Django can be used for larger applications. It includes an ORM.

34. How is multithreading achieved in Python?

A thread is a lightweight process. Multithreading allows the programmer to execute multiple threads in one go. The Global Interpreter Lock ensures that a single thread performs at a given time. A thread holds the GIL and does some work before passing it on to the next thread. This looks like parallel execution, but actually, it is just threading taking turns at the CPU.

35. Explain supported data types in Python?

Python supported 5 data types.

  • Numbers
  • String
  • Tuple
  • Dictionary
  • List
36. How do you randomize a list in Python?

from random import shuffle

x = ['My', 'Singh', 'Hello', 'India']

shuffle(x)

print(x)

The output of the following code is as below.

['Singh', 'India', 'Hello', 'My']

37. In Python, how can you generate random numbers?

In Python, an array of random integers can be generated through the function randint () NumPy. This function usually starts with three arguments; from the lower end, the upper-end range and the number of actual integer values to successfully generate the size of the array.

38. How web scraping is done in Python, explain in short?
  • Select the URL you want to scrap
  • Inspect the page
  • Select data you want to extract
  • Write the codes and run them

Once the data is extracted store the data in any required format

39. What is the OS module?

The way of using the operating system dependent functionalities is an OS module. Through this function, the interface is provided with the underlying operating system for which Python is running on.

40. What do you understand by DeQue in Python?

DeQue module is a segment of the collection library that has a feature of addition and removal of the elements from their respective ends.

41. In Python, what is Theano?

It is a Python library used to optimize, define, and execute the mathematical expressions including multidimensional arrays.

42. Name the built-in types provided by Python?

There are two categories of ‘types’ present in Python, which is mutable and immutable.

Mutable built-in types
  • List
  • Dictionary
  • Set
Immutable built-in type
  • String
  • Number
  • Tuple
43. What is %S in Python? Python easily supports the formatting for any value into a string which may contain a number of complex expressions. The utility includes pushing the values with the help of % format specifier into a string.
44. How will you do debugging in Python? Debugging in Python can be done by utilizing the inbuilt module pdb. This module actually defines the interactive source code debugger for all the Python programs.
Add Review