Python Programming Interview Questions – Get Hired as Python Developer

Python Programming Interview Questions for Experts

By now we all know that Python is the most used programming language as compared to other languages and everyone wants to learn Python and build their career in it. This is why we are here to help you with Python programming interview questions. TechVidvan is providing you a series of 75+ Python Interview Questions and Answers in three parts:

To start with, in this Python programming interview questions, we are mainly focusing on experts or those who are familiar with Python and have some experience. In this article, TechVidvan is providing some project related interview questions, technical questions, advanced questions, and some frequently asked Python programming interview questions to whet your programming skills so that you can crack your next interview.

Python Programming interview questions

Advanced Python Programming Interview Questions

Q.1. How will you send mail with Python?

We can use the smtplib module for sending mail with Python. We’ll use the host smtp.gmail.com on port 587.

Code:

import smtplib
s=smtplib.SMTP(‘smtp.gmail.com’,587)
s.starttls()
s.login(‘youremailid’,’yourpassword’)
message=’This is a test’
s.sendmail(‘receiverid’,’senderid’,message)

Q.2. What is Pylint?

Pylint is a static code analysis tool that checks your code for errors, and also enforces coding standards. It also offers refactoring suggestions, like asking you to turn your variable name to snake_case. Pylint is configurable from within code and also from an external configuration file. It can give you suggestions on conventions (C), refactoring (R), warnings (W), errors (E), and fatal errors (F). For convention messages, refactor messages, warning messages, error messages, fatal error messages, and perfect code, it will give you the status codes 16, 8, 4, 2, 1, and 0 respectively.

To run it, you can type in the command prompt:

pylint palindrome.py

Q.3. Explain pickling and unpickling.

Pickling is the process of converting an object hierarchy into a byte stream. And unpickling is the inverse of that – converting the byte stream back into an object hierarchy. These are also called serialization and deserialization and can be implemented with the pickle module in Python. Serialization is also called marshalling or flattening. To pickle, you can use the pickle.dump() function, and the pickle.load() function to unpickle it.

Q.4. Is Python for web client or web server side programming?

Python can do both but is better suited for web server-side programming as it can be used for implementing web server hosting, database interactions, and business logic. It can be used on the client-side, but that needs to implement conversions so the browser can interpret the client-side logic. Python can also be used for creating standalone desktop applications, for scripting, and also for test automation. It is a general-purpose language that is good at a lot of things.

Q.5. Where would you use a list, a tuple, or a dictionary?

Since lists are mutable, you can use them for collections of items that can be altered at runtime. Tuples are immutable, so they can be used when you want to protect your data from modification. And dictionaries are useful when you want to store information as key-value pairs where the keys cannot be altered.

Learn more about:

Q.6. How does Python act as a scripting language compared to others like JavaScript?

We know that being a general-purpose language, Python is also a scripting language. It offers the following benefits over JavaScript:

  • Python is faster and easier to learn/read/write.
  • It lets you use a large number of libraries and packages for data science and machine learning- like scikit-learn, Keras, and pandas. It also has great visualization libraries.
  • Python has a large community that will answer your questions if you get stuck.

Frequently Asked Python Programming Interview Questions

Q.7. How is Django different from Flask?

Let’s compare them side by side.

1. Django is a full-stack web framework, Flask is a lightweight microframework. Django has built-in support for common tasks like user authentication and URL routing. It also has a built-in template engine, an ORM system, and a bootstrapping tool. Flask doesn’t have all those features, but it lets you use third-party libraries.

2. Django has a functional admin interface through which you can handle common project administration tasks. Flask lacks this.

3. Django has a built-in template engine, but you can also write your own templates in Django Template Language (DTL). And Flask is based on the Jinja2 template engine, which is inspired by Django’s template system.

4. Django has a built-in bootstrapping tool, Django-admin that lets you get started with building web applications. You can also split a project into multiple applications. Flask does not have a bootstrapping tool.

5. Like said before, in Django, we can divide a project into multiple applications. But with Flask, each project must be a single application.

6. Django has a built-in ORM (Object Relational Mapping) system that works with databases like MySQL, Oracle, SQLite, and PostgreSQL. This lets you perform common database operations without having to write complex SQL queries. Flask does not have an ORM, and you must perform database operations through SQLAlchemy.

7. Since Django has support for everything, it does not let you modify the functionality. Flask is rather extensible and lets you use tools and libraries flexibly.

8. Django is more popular than Flask, but both Django and Flask are open-source web frameworks that are commonly used and also by big names. Different projects are better suited to Django or Flask.

Q.8. Which databases does Python support?

Most commonly, the databases used for Python are PostgreSQL, MySQL, and SQLite. SQLite is built into Python and can be accessed with the sqlite3 module. It can only handle a single connection at once. You can also use other database interfaces including, but not limited to:

  • MongoDB
  • Oracle
  • Sybase
  • Microsoft SQL Server
  • Informix
  • Ingres
  • Inter-base
  • Microsoft Access
  • SAP DB
  • Firebird
  • IBM DB2

Q.9. Explain locals() and globals().

locals() and globals() are built-in functions in Python. locals() gives us a dictionary holding the local variables in the current scope. And globals() gives us a dictionary with the global variables in the current scope.

We also use them with eval() and exec(). They let us evaluate and execute user code. This can be risky as users can misuse it to obtain confidential information or carry out malicious actions. Specifying the locals and globals parameters, we can restrict what the user can access:

Code:

exec('print(a)',{'a':7})

Technical Python Programming Interview Questions

Q.10. How will you round a floating-point number using string interpolation?

Using the format method with the following code:

Code:

>>> "{:.2f}".format(77.321)

Output:

‘77.32’

This rounds the value 77.321 to 2 digits after the decimal. This is new style string formatting.

Code:

>>> from math import pi
>>> "{:.2f}".format(pi)

Output:

‘3.14’

Q.11. How will you measure the performance of your code?

To measure the performance of our code, we can use the time module. Using time.time(), we can get the time at different stages of the execution to find out how much time a certain part of code takes. We can also use the logging module to log data with timestamps.

Code:

import time

count=0

print(time.time())

for i in range(100):
    count+=1

print(time.time())

Q.12. Should you use Memcached in your project?

No. Memcached should not be used in a Python project. It is a cache, not a data store. Memcached cannot query data or iterate over content to extract information. It also does not offer security in the form of encryption or authentication. And if you choose to use it, you should always have a second source of information for the application.

Q.13. How will you share global variables over modules?

We can create a separate module to hold all the global variables, then import it in the modules where we need them. We can call this config.py or anything else we want. This lets us share the variables across modules in a single program.

Q.14. How will you get the indices of the 3 highest values in a NumPy array?

Let’s first create a NumPy array. Now, the argsort() function gets us the indices that would sort this array. If we slice it with [-3:], we’ll get the last three values in this list – the last 3 indices. [::-1] will reverse this and get us the indices of the 3 highest values in decreasing order – 8, then 5, then 4.

Code:

>>> import numpy as np
>>> arr=np.array([1,2,3,4,5,8,3,4])
>>> print(arr.argsort()[-3:][::-1])

Output:

[5 4 7]

Q.15. How will you download DataFlair’s logo using Python?

We can use the urllib module for this.

Code:

>>> import urllib.request
>>> urllib.request.urlretrieve('https://data-flair.training/blogs/wp-content/uploads/sites/2/2019/01/DataFlair_Logo_Final-01.png','df logo.png')
('df logo.png', <http.client.HTTPMessage object at 0x00000196A3FE7648>)

The urlretrieve() function retrieves a URL into a temporary location on disk. We give it the URL of the image, and also what to call it. This saves the logo as df logo.png where Python resides.

Q.16. Explain the different inheritance styles in Django.

Django has 3 inheritance styles you can implement:

  • Abstract Base Class – ABCs are classes with one or more abstract methods. Such a method has a declaration, but no implementation. We can have subclasses implement the abstract methods, but it’s not mandatory.
  • Multi-table Inheritance – If you are subclassing an existing model, and each model must have its own database table, you can use this style.
  • Proxy models – If you want to modify a model’s Python-level behavior, but not its fields, you can use this style.

Q.17. Why do you need sessions in Django?

Sessions help us customize the user experience. Django session stores and receives data for every visitor. It implements the processes of sending/receiving cookies, placing session ID cookies on the client’s machine, and storing the retrieved data on the server.

Q.18. How will you get the number of digits in a file?

Let’s open the file statistics.txt using a with-clause, and call it ‘numbers’. Now, for each line in this file, for each character in the line, add 1 if it is a digit. Print out the final sum.

Code:

>>> with open('C:\\Users\\DataFlair\\Desktop\\statistics.txt') as numbers:
  print(sum(1 for line in numbers.read() for char in line if char.isdigit()))

Output:

14

Q.19. Implement the bubble sort algorithm in Python.

Let’s create a function for this.

Code:

def bubble_sort(list):
for i in range(len(list)-1):
for j in range(len(list)-1-i):
if list[j]>list[j+1]:
list[j],list[j+1]=list[j+1],list[j]
return list

Now, make a call to this function with a list to sort as argument.

Code:

bubble_sort([4,2,4,1,9,0,5,2])

Output:

[0, 1, 2, 2, 4, 4, 5, 9]

Q.20. How are database requests handled in Flask?

To create and initiate databases in Flask, you need the sqlite3 command. To request for a database:

  • before_request(): Registers a function to be called before a request, no arguments passed.
  • after_request(): Registers a function to be called after a request, takes an argument for the response to send to the client.
  • teardown_request(): Registers a function to be called at the end of each request regardless of whether there has been an exception.

Q.21. Can you skip using a nested function in a decorator?

This is a normal decorator:

Code:

>>> def decor(func):
  def wrap():
    print("/////////////////////")
    func()
    print("/////////////////////")
  return wrap

>>> @decor
def sayhi():
  print("Hi")


>>> sayhi()

Output:

/////////////////////
Hi
/////////////////////

If we do not use an inner function, the decorator returns None:

Code:

>>> def decor(func):
  print("/////////////////////")
  func()
  print("/////////////////////")


>>> @decor
def sayhi():
  print("Hi")

Output:

/////////////////////
Hi
/////////////////////

Code:

>>> sayhi()

Output:

Traceback (most recent call last):
  File “<pyshell#176>”, line 1, in <module>
    sayhi()
TypeError: ‘NoneType’ object is not callable

This time, it executed the decorator when we defined the function ‘sayhi’. Then, when we explicitly called ‘sayhi’, it raised a TypeError stating ‘NoneType’ object is not callable.

Project Related Python Programming Interview Questions

Q.22. When should you use a generator?

Generators return iterable objects which we can iterate on with the yield keyword. Generators let us hold execution whenever we want. When we are working with large datasets, we should use generators instead of loops. We can also use them when we don’t want all the results. We can also use them as callbacks.

Know more about generators in Python with TechVidvan.

Q.23. What is memoization?

Memoization is the optimization technique of storing the results of expensive function calls to return the cached result when the same input occurs again. This speeds up a program. We can use decorators to implement these.

Q.24. What is monkey patching?

Monkey patching is the act of modifying a class or a module at runtime. This is a way of extending the code at runtime and is also called a dynamic modification.

Syntax:

from pkg.module import MyClass
def sayhi(self):
  print("Hi")

MyClass.sayhi=sayhi

Q.25. Which is the best IDE for Python?

This is subjective, but PyCharm and Spyder are good options. Also, the Jupyter Notebook or JupyterLab is a good option for data science.

Q.26. How will you make a Python script executable on Unix?

There are two prerequisites to make a Python script executable on Unix –

  • The script file should be in an executable mode.
  • The first line should begin with a #.

Summary

This was all about Python programming interview questions and answers. I hope this article was helpful to you. If you want to add more Python interview questions for beginners, intermediates, and experts level, do let us know in the comment section.

All the best for your next interview!!