Python is a general-purpose, dynamic, high-level, and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures.

“Mastering Python Interviews” is your comprehensive companion, providing the knowledge and confidence needed to showcase your Python prowess and stand out in today’s competitive job market. Whether you’re gearing up for your first Python interview or aiming for a career advancement, this guide is tailored to elevate your interview performance and set you on the path to success.

Python is an easy-to-learn yet powerful and versatile scripting language, which makes it attractive for Application Development.

With its interpreted nature, Python’s syntax and dynamic typing make it an ideal language for scripting and rapid application development.

Python supports multiple programming patterns, including object-oriented, imperative, and functional or procedural programming styles.

Python is not intended to work in a particular area, such as web programming. It is a multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc.

We don’t need to use data types to declare variable because it is dynamically typed, so we can write a=10 to assign an integer value in an integer variable.

Experience Python Interview Questions

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.

Encapsulation means binding the code and the data together. A Python class in an example of encapsulation.

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.

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.  

 

An empty class is a class that does not have any code defined within its block. It can be created using the pass keyword. However, you can create objects of this class outside the class itself. IN PYTHON THE PASS command does nothing when its executed. it’s a null statement. 

 

For example-

1
2
3
4
5 class a:
pass
obj=a()
obj.name="xyz"
print("Name = ",obj.name)

Output: 

Name =  xyz

It returns a featureless object that is a base for all classes. Also, it does not take any parameters.

Next, let us have a look at some Basic Python Programs in these Python Interview Questions.

 

1
2
3
4
5
6
7
8
9
10 def bs(a):
# a = name of list
b=len(a)-1nbsp;
# minus 1 because we always compare 2 adjacent values
for x in range(b):
for y in range(b-x):
a[y]=a[y+1]

a=[32,5,3,6,7,54,87]
bs(a)

Output:  [3, 5, 6, 7, 32, 54, 87]

 

1
2
3
4 def pyfunc(r):
for x in range(r):
print(' '*(r-x-1)+'*'*(2*x+1))
pyfunc(9)

Output:

        *

       ***

      *****

     *******

    *********

   ***********

  *************

 ***************

*****************

 

1
2
3
4
5
6
7
8
9
10
11
12 # Enter number of terms needednbsp;#0,1,1,2,3,5....
a=int(input("Enter the terms"))
f=0;#first element of series
s=1#second element of series
if a=0:
print("The requested series is",f)
else:
print(f,s,end=" ")
for x in range(2,a):
print(next,end=" ")
f=s
s=next

Output: Enter the terms 5 0 1 1 2 3

1
2
3
4
5
6
7
8
9
10 a=int(input("enter number"))
if a=1:
for x in range(2,a):
if(a%x)==0:
print("not prime")
break
else:
print("Prime")
else:
print("not prime")

Output:

enter number 3

Prime

1
2
3
4
5
6 a=input("enter sequence")
b=a[::-1]
if a==b:
print("palindrome")
else:
print("Not a Palindrome")

Output:

enter sequence 323 palindrome

Let us first write a multiple line solution and then convert it to one-liner code.

1
2
3
4
5
6 with open(SOME_LARGE_FILE) as fh:
count = 0
text = fh.read()
for character in text:
if character.isupper():
count += 1

We will now try to transform this into a single line.

1	count sum(1 for line in fh for character in line if character.isupper())

 

1
2
3
4 list = ["1", "4", "0", "6", "9"]
list = [int(i) for i in list]
list.sort()
print (list)

 

1
2
3
4
5
6
7 A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]
print(A0,A1,A2,A3,A4,A5,A6)

The following will be the final outputs of A0, A1, … A6

A0 = {‘a’: 1, ‘c’: 3, ‘b’: 2, ‘e’: 5, ‘d’: 4} # the order may vary

A1 = range(0, 10)

A2 = []

A3 = [1, 2, 3, 4, 5]

A4 = [1, 2, 3, 4, 5]

A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

 

Next, in this Python Interview Questions let’s have a look at some Python Libraries

 

Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of their 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 them. The user can modify the session if only it has the secret key Flask.secret_key.

Django and Flask map the URL’s or addresses typed in the web browsers to functions in Python. 

Flask is much simpler compared to Django but, Flask does not do a lot for you meaning you will need to specify the details, whereas Django does a lot for you wherein you would not need to do much work. Django consists of prewritten code, which the user will need to analyze whereas Flask gives the users to create their own code, therefore, making it simpler to understand the code. Technically both are equally good and both contain their own pros and cons.

 

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

Django MVT Pattern:

Figure:  Python Interview Questions – Django Architecture

The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.

 

You can use the command edit mysite/setting.py, it is a normal python module with module level representing Django settings.

Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings.

  • Engines: you can change the database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on
  • Name: The name of your database. In the case if you are using SQLite as your database, in that case, database will be a file on your computer, Name should be a full absolute path, including the file name of that file.
  • If you are not choosing SQLite as your database then settings like Password, Host, User, etc. must be added.

Django uses SQLite as a default database, it stores data as a single file in the filesystem. If you do have a database server—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your database’s administration tools to create a new database for your Django project. Either way, with your (empty) database in place, all that remains is to tell Django how to use it. This is where your project’s settings.py file comes in.

We will add the following lines of code to the setting.py file:

1
2
3
4
5
6 DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.sqlite3',
'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

 

This is how we can use write a view in Django:

1
2
3
4
5
6
7 from django.http import HttpResponse
import datetime

def Current_datetime(request):
now = datetime.datetime.now()
html = "It is now %s/body/html % now
return HttpResponse(html)

Returns the current date and time, as an HTML document

The template is a simple text file.  It can create any text-based format like XML, CSV, HTML, etc.  A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that control the logic of the template.

Figure: Python Interview Questions – Django Template

Django provides a session that lets you store and retrieve data on a per-site-visitor basis. Django abstracts the process of sending and receiving cookies, by placing a session ID cookie on the client side, and storing all the related data on the server side.

Figure: Python Interview Questions – Django Framework

So the data itself is not stored client side. This is nice from a security perspective.

 

In Django, there are three possible inheritance styles:

  1. Abstract Base Classes: This style is used when you only want parent’s class to hold information that you don’t want to type out for each child model.
  2. 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.
  3. 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.

Next in this Python Interview Question blog, let’s have a look at questions related to Web Scraping.

We will use the following code to save an image locally from an URL address

1
2 import urllib.request
urllib.request.urlretrieve("URL", "local-filename.jpg")

 

Use the following URL format:

http://webcache.googleusercontent.com/search ?q=cache:URLGOESHERE

Be sure to replace “URLGOESHERE” with the proper web address of the page or site whose cache you want to retrieve and see the time for. For example, to check the Google Webcache age of Kaashiv.com you’d use the following URL:

http://webcache.googleusercontent.com/search ?q=cache:Kaashiv.com

 

We will use the following lines of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 from bs4 import BeautifulSoup

import requests
import sys

url = '<a href="http://www.imdb.com/chart/top">http://www.imdb.com/chart/top</a>'
response = requests.get(url)
soup = BeautifulSoup(response.text)
tr = soup.findChildren("tr")
tr = iter(tr)
next(tr)

for movie in tr:
title = movie.find('td', {'class': 'titleColumn'} ).find('a').contents[0]
year = movie.find('td', {'class': 'titleColumn'} ).find('span', {'class': 'secondaryInfo'}).contents[0]
rating = movie.find('td', {'class': 'ratingColumn imdbRating'} ).find('strong').contents[0]
row = title + ' - ' + year + ' ' + ' ' + rating

print(row)

The above code will help scrap data from IMDb’s top 250 list

Next in this Python Interview Questions blog, let’s have a look at questions related to Data Analysis in Python.

 

map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions.

We use python numpy array instead of a list because of the below three reasons:

  1. Less Memory
  2. Fast
  3. Convenient

For more information on these parameters, you can refer to this section – Numpy Vs List.

 

We can get the indices of N maximum values in a NumPy array using the below code:

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

Output

[ 4 3 1 ]

We can calculate percentiles with the following code

1
2
3
4 import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50) #Returns 50th percentile, e.g. median
print(p)

Output:3

NumPy

SciPy

It refers to Numerical python.

It refers to Scientific python.

It has fewer new scientific computing features.

Most new scientific computing features belong in SciPy.

It contains less linear algebra functions.

It has more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms.

NumPy has a faster processing speed.

SciPy on the other hand has slower computational speed.

 

Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in the 2D case, packages exist that integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, whereas Mayavi provides a wide range of high-quality 3D visualization features, utilizing the powerful VTK engine.

Categorized in: