SlideShare a Scribd company logo
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Python Interview Questions
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Python Job Trends
Source: https://www.indeed.com/jobtrends/q-python.html
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Salary Trends Based on Language
Source: https://yourstory.com/2016/02/developers-salary/
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Agenda
Basic Python
Questions
1
Django Questions
2
Web Scraping
Questions
3
Data Analysis Using
Python Questions
4
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Basic Python Questions
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
Shallow copy is used when a
new instance type gets created
and it keeps the values that are
copied in the new instance.
Deep copy is used to store the
values that are already copied.
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.
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.
Shallow copy allows faster
execution of the program and it
depends on the size of the data
that is used.
Deep copy makes execution of
the program slower due to
making certain copies for each
object that is been called.
Q1. What is the difference between deep and shallow copy?
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Basic Python Questions
Q2. What is the difference between list and tuples?
Lists Tuples
Lists are mutable i.e it can be edited Tuples are immutable (tuples are lists
which can't be edited)
Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)
Consider the program shown below:
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Basic Python Questions
Q3. How Multithreading is achieved in Python?
❑ Python has a multi-threading package but if you want to multi-thread to speed your code up.
❑ Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your
'threads' can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto
the next thread.
❑ This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but
they are really just taking turns using the same CPU core.
❑ All this GIL passing adds overhead to execution. This means that if you want to make your code run faster
then using the threading package often isn't a good idea.
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Basic Python Questions
Q4. How can the ternary operators be used in python?
The Ternary operator is the
operator that is used to
show the conditional
statements. This consists
of the true or false values
with a statement that has
to be evaluated for it.
The Ternary operator will be given as:
[on_true] if [expression] else [on_false]
x, y = 25, 50
big = x if x < y else y
Syntax and example
The expression gets evaluated like if
x<y else y, in this case if x<y is true
then the value is returned as big=x and
if it is incorrect then big=y will be sent
as a result.
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Basic Python Questions
Q5. What is monkey patching in Python?
In Python, the term monkey patch only refers to dynamic modifications of a class or module at runtime. Consider
the below example:
Then, if we run the monkey-
patch testing like this:
As we can see, we did make some changes in the behavior
of f() in MyClass using the function we
defined, monkey_f(), outside of the module m.
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Basic Python Questions
Q6. How can you randomize the items of a list in place in Python?
from random import shuffle
x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
shuffle(x)
print(x)
Consider the example shown below:
['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']
Output:
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Basic Python Questions
Q7. Write a sorting algorithm for a numerical dataset in Python.
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Basic Python Questions
Q8. Looking at the below code, write down the final values of A0, A1, ...An.
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)
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]]
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Basic Python Questions
Q9. Explain split(), sub(), subn() methods of “re” module in Python.
To modify the strings, Python’s “re” module is providing 3 methods. They are:
❑ split() – uses a regex pattern to “split” a given string into a list.
❑ sub() – finds all substrings where the regex pattern matches and then replace them with a different string
❑ subn() – it is similar to sub() and also returns the new string along with the no. of replacements.
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Basic Python Questions
Q11. Explain Inheritance in Python with example?
Inheritance allows One class to gain all the members(say attributes and methods) of
another class. Inheritance provides code reusability, makes it easier to create and
maintain an application. The class from which we are inheriting is called super-class
and the class that is inherited is called a derived / child class. They are different
types of inheritance supported by Python:
❑ Single Inheritance – where a derived class acquires the members of a single
super class.
❑ Multi-level inheritance – a derived class d1 in inherited from base class base1,
and d2 is inherited from base2.
❑ Hierarchical inheritance – from one base class you can inherit any number of
child classes
❑ Multiple inheritance – a derived class is inherited from more than one base class.
class ParentClass:
v1 = "from ParentClass - v1"
v2 = "from ParentClass - v2"
class ChildClass(ParentClass):
pass
print(ChildClass.v1)
print(ChildClass.v2)
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Django Questions
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Django Questions
Q12. Mention the Django architecture?
Django MVT Pattern:
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.
ViewURL
Model
TemplateDjangoUser
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Django Questions
Q13. Explain how you can set up the Database in Django?
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 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 file name of that file.
❑ If you are not choosing SQLite as your database then setting like Password, Host, User, etc. must be added.
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Django Questions
Q13. Explain how you can set up the Database in Django?
Django uses SQLite as 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.
setting.py
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Django Questions
Q14. Give an example how you can write a VIEW in Django?
from django.http import HttpResponse
import datetime
def Current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
Returns the current date and time, as an HTML document
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Django Questions
Q15. Mention what does the Django templates consists of?
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
controls the logic of the template.
DataBase ViewsModels
Templates
URL
Browser
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Django Questions
Q16. Explain the use of session in Django framework?
Django provides 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. So the data itself is not stored client side. This is nice from a security perspective.
Client-Side
# Session
ID Cookie
Website
Server-Side
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Django Questions
Q17. List out the inheritance styles in Django?
Abstract base classes:
This style is used when
you only wants 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
In Django, there is three possible inheritance styles:
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Django Questions
Q18. Mention what does the Django field class types?
Field
Class
The database column type
The default HTML widget to avail while rendering a
form field
The minimal validation requirements used in Django
admin and in automatically generated forms
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Web Scraping Using Python Questions
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Web Scraping Using Python Questions
Q19. How To Save An Image Locally Using Python Whose URL Address I Already Know?
import urllib.request
urllib.request.urlretrieve("URL", "local-filename.jpg")
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Web Scraping Using Python Questions
Q20. How Can I Get The Google Cache Age Of Any URL Or Web Page?
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 edureka.co you’d use the following URL:
http://webcache.googleusercontent.com/search?q=cache:edureka.co
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Web Scraping Using Python Questions
Q21. You are required to scrap data from IMDB top 250 movies page. It should only have fields movie name,
year, and rating.
from bs4 import BeautifulSoup
import requests
import sys
url = 'http://www.imdb.com/chart/top'
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)
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
Q22. How To Get Indices Of N Maximum Values In A Numpy Array?
import numpy as np
arr = np.array([1, 3, 2, 4, 5])
print(arr.argsort()[-3:][::-1])
Output:
[ 4 3 1 ]
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
Q23. How Do I Calculate Percentiles With Python/Numpy?
import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50) # return 50th percentile, e.g median.
print(p)
Output:
3
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Python Questions
Q24. What advantages does NumPy arrays offers over (nested) Python lists?
❑ Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion,
appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate.
❑ They have certain limitations: they don’t support “vectorized” operations like elementwise addition and
multiplication, and the fact that they can contain objects of differing types mean that Python must store type
information for every element, and must execute type dispatching code when operating on each element.
❑ NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for
free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.
❑ NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics,
linear algebra, histograms, etc.
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
Q25. What is the difference between NumPy and SciPy?
❑ In an ideal world, NumPy would contain nothing but the array data type and the most basic operations:
indexing, sorting, reshaping, basic elementwise functions, et cetera.
❑ All numerical code would reside in SciPy. However, one of NumPy’s important goals is compatibility, so
NumPy tries to retain all features supported by either of its predecessors.
❑ Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In
any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other
numerical algorithms.
❑ If you are doing scientific computing with python, you should probably install both NumPy and SciPy.
Most new features belong in SciPy rather than NumPy.
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
Q26. How Do I make 3D plots/visualizations using NumPy/SciPy?
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.
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
Q27. How do I find the indices of an array where some condition is true?
import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a > 3 )
print(np.nonzero(a > 3))
Output:
[[False False False]
[ True True True]
[ True True True]]
(array([1, 1, 1, 2, 2, 2], dtype=int32), array([0, 1, 2, 0, 1, 2], dtype=int32))
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
Q28. How to rename column headers in Pandas DataFrame
import pandas as pd
data = {'Commander': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'Date': ['2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08'],
'Score': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
df.columns = ['Leader', 'Time', 'Score']
print(df)
Original DataFrame Updated DataFrame
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
Q29. What is the function to iterate through the values in a manner that one
also retrieves the index ? df.iteritems unfortunately only iterates column by
column.
The newest versions of pandas now include a built-in function for iterating over rows.
for index, row in df.iterrows(): # do some logic here
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
Q30. How to convert a list of Dictionaries into a Pandas DataFrame
Supposing d is your list of dicts, simply:
pd.DataFrame(d)
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
Q31. Lets say that I have the following Pandas DataFrame:
df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]})
how can I subset based on a list of values? - something like this:
list_of_values = [3,6] y = df[df['A'] in list_of_values]
This is indeed a duplicate of how to filter the dataframe rows of pandas by "within"/"in"?.
translating the response to the example shown above:
df[df['A'].isin([3, 6])]
A B
1 6 2
2 3 3
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
Q32. I have a DataFrame:
STK_ID EPS cash
STK_ID RPT_Date
601166 20111231 601166 NaN NaN
600036 20111231 600036 NaN 12
600016 20111231 600016 4.3 NaN
601009 20111231 601009 NaN NaN
601939 20111231 601939 2.5 NaN
000001 20111231 000001 NaN NaN
I just want the records whose EPS is not NaN
Just take rows where EPS is finite:
df = df[np.isfinite(df['EPS'])]
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Data Analysis Using Python Questions
Q33. Write a program to read and write the binary data using python?
The module that is used to write and read the binary data is known as struct. The program can read or write the
binary data is:
import struct
f = open(file-name, "rb")
# This Open() method allows the file to get opened in binary mode to make it portable for # use.
s = f.read(8)
f.write("Hello, World!n")
www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING
Thank You

More Related Content

PPTX
PDF
Parquet performance tuning: the missing guide
PDF
Mvcc in postgreSQL 권건우
PDF
Python Programming Language | Python Classes | Python Tutorial | Python Train...
PDF
Spark SQL
PDF
Redo log improvements MYSQL 8.0
PDF
Spark shuffle introduction
PDF
The Apache Spark File Format Ecosystem
Parquet performance tuning: the missing guide
Mvcc in postgreSQL 권건우
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Spark SQL
Redo log improvements MYSQL 8.0
Spark shuffle introduction
The Apache Spark File Format Ecosystem

What's hot (20)

PDF
Analytical Queries with Hive: SQL Windowing and Table Functions
ODP
PostgreSQL Administration for System Administrators
PPTX
Presto overview
PDF
Designing ETL Pipelines with Structured Streaming and Delta Lake—How to Archi...
PPTX
PostGreSQL Performance Tuning
PDF
Introduction to Vacuum Freezing and XID
PDF
Building a fully managed stream processing platform on Flink at scale for Lin...
PDF
Using Optimizer Hints to Improve MySQL Query Performance
PDF
ElasticSearch in action
PDF
Understanding Data Partitioning and Replication in Apache Cassandra
PDF
Deep dive into PostgreSQL statistics.
PDF
Parquet Strata/Hadoop World, New York 2013
PPTX
The columnar roadmap: Apache Parquet and Apache Arrow
PPTX
Unit 3 MongDB
PDF
PostgreSQL Deep Internal
PDF
What is new in PostgreSQL 14?
PDF
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PDF
The InnoDB Storage Engine for MySQL
PDF
Optimizing Delta/Parquet Data Lakes for Apache Spark
PDF
Airflow presentation
Analytical Queries with Hive: SQL Windowing and Table Functions
PostgreSQL Administration for System Administrators
Presto overview
Designing ETL Pipelines with Structured Streaming and Delta Lake—How to Archi...
PostGreSQL Performance Tuning
Introduction to Vacuum Freezing and XID
Building a fully managed stream processing platform on Flink at scale for Lin...
Using Optimizer Hints to Improve MySQL Query Performance
ElasticSearch in action
Understanding Data Partitioning and Replication in Apache Cassandra
Deep dive into PostgreSQL statistics.
Parquet Strata/Hadoop World, New York 2013
The columnar roadmap: Apache Parquet and Apache Arrow
Unit 3 MongDB
PostgreSQL Deep Internal
What is new in PostgreSQL 14?
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
The InnoDB Storage Engine for MySQL
Optimizing Delta/Parquet Data Lakes for Apache Spark
Airflow presentation
Ad

Similar to Python Interview Questions And Answers 2019 | Edureka (20)

PDF
Best data analyst course syllabus 2025.pdf
PDF
Best data science course syllabus 2025.pdf
PDF
DIY in 5 Minutes: Testing Django App with Pytest
PDF
Scientist meets web dev: how Python became the language of data
PDF
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
PDF
Pytorch A Detailed Overview Agladze Mikhail
PPTX
PPTX
templates in Django material : Training available at Baabtra
PPTX
Django Girls Tutorial
PDF
PyCaret_PedramJahangiryTUTORIALPYTHON.pdf
PPTX
Django framework
PPTX
Django Architecture Introduction
ODP
Web Development in Django
PDF
PHYTON-REPORT.pdf
PPTX
Django - Python MVC Framework
PDF
Django - basics
PDF
Best Data Science Deep Learning In Python in Bangalore
PDF
PyTorch Python Tutorial | Deep Learning Using PyTorch | Image Classifier Usin...
ODP
20120314 changa-python-workshop
Best data analyst course syllabus 2025.pdf
Best data science course syllabus 2025.pdf
DIY in 5 Minutes: Testing Django App with Pytest
Scientist meets web dev: how Python became the language of data
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Pytorch A Detailed Overview Agladze Mikhail
templates in Django material : Training available at Baabtra
Django Girls Tutorial
PyCaret_PedramJahangiryTUTORIALPYTHON.pdf
Django framework
Django Architecture Introduction
Web Development in Django
PHYTON-REPORT.pdf
Django - Python MVC Framework
Django - basics
Best Data Science Deep Learning In Python in Bangalore
PyTorch Python Tutorial | Deep Learning Using PyTorch | Image Classifier Usin...
20120314 changa-python-workshop
Ad

More from Edureka! (20)

PDF
What to learn during the 21 days Lockdown | Edureka
PDF
Top 10 Dying Programming Languages in 2020 | Edureka
PDF
Top 5 Trending Business Intelligence Tools | Edureka
PDF
Tableau Tutorial for Data Science | Edureka
PDF
Python Programming Tutorial | Edureka
PDF
Top 5 PMP Certifications | Edureka
PDF
Top Maven Interview Questions in 2020 | Edureka
PDF
Linux Mint Tutorial | Edureka
PDF
How to Deploy Java Web App in AWS| Edureka
PDF
Importance of Digital Marketing | Edureka
PDF
RPA in 2020 | Edureka
PDF
Email Notifications in Jenkins | Edureka
PDF
EA Algorithm in Machine Learning | Edureka
PDF
Cognitive AI Tutorial | Edureka
PDF
AWS Cloud Practitioner Tutorial | Edureka
PDF
Blue Prism Top Interview Questions | Edureka
PDF
Big Data on AWS Tutorial | Edureka
PDF
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
PDF
Kubernetes Installation on Ubuntu | Edureka
PDF
Introduction to DevOps | Edureka
What to learn during the 21 days Lockdown | Edureka
Top 10 Dying Programming Languages in 2020 | Edureka
Top 5 Trending Business Intelligence Tools | Edureka
Tableau Tutorial for Data Science | Edureka
Python Programming Tutorial | Edureka
Top 5 PMP Certifications | Edureka
Top Maven Interview Questions in 2020 | Edureka
Linux Mint Tutorial | Edureka
How to Deploy Java Web App in AWS| Edureka
Importance of Digital Marketing | Edureka
RPA in 2020 | Edureka
Email Notifications in Jenkins | Edureka
EA Algorithm in Machine Learning | Edureka
Cognitive AI Tutorial | Edureka
AWS Cloud Practitioner Tutorial | Edureka
Blue Prism Top Interview Questions | Edureka
Big Data on AWS Tutorial | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
Kubernetes Installation on Ubuntu | Edureka
Introduction to DevOps | Edureka

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Cloud computing and distributed systems.
PDF
Encapsulation theory and applications.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Empathic Computing: Creating Shared Understanding
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Big Data Technologies - Introduction.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Approach and Philosophy of On baking technology
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Cloud computing and distributed systems.
Encapsulation theory and applications.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
sap open course for s4hana steps from ECC to s4
Empathic Computing: Creating Shared Understanding
Agricultural_Statistics_at_a_Glance_2022_0.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Review of recent advances in non-invasive hemoglobin estimation
Big Data Technologies - Introduction.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
The AUB Centre for AI in Media Proposal.docx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
NewMind AI Weekly Chronicles - August'25 Week I
Approach and Philosophy of On baking technology
Dropbox Q2 2025 Financial Results & Investor Presentation
Reach Out and Touch Someone: Haptics and Empathic Computing
Building Integrated photovoltaic BIPV_UPV.pdf
Understanding_Digital_Forensics_Presentation.pptx

Python Interview Questions And Answers 2019 | Edureka

  • 1. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Python Interview Questions
  • 2. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Python Job Trends Source: https://www.indeed.com/jobtrends/q-python.html
  • 3. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Salary Trends Based on Language Source: https://yourstory.com/2016/02/developers-salary/
  • 4. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Agenda Basic Python Questions 1 Django Questions 2 Web Scraping Questions 3 Data Analysis Using Python Questions 4
  • 5. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Basic Python Questions
  • 6. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Deep copy is used to store the values that are already copied. 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. 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. Shallow copy allows faster execution of the program and it depends on the size of the data that is used. Deep copy makes execution of the program slower due to making certain copies for each object that is been called. Q1. What is the difference between deep and shallow copy?
  • 7. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Basic Python Questions Q2. What is the difference between list and tuples? Lists Tuples Lists are mutable i.e it can be edited Tuples are immutable (tuples are lists which can't be edited) Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20) Consider the program shown below:
  • 8. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Basic Python Questions Q3. How Multithreading is achieved in Python? ❑ Python has a multi-threading package but if you want to multi-thread to speed your code up. ❑ Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your 'threads' can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. ❑ This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core. ❑ All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn't a good idea.
  • 9. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Basic Python Questions Q4. How can the ternary operators be used in python? The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it. The Ternary operator will be given as: [on_true] if [expression] else [on_false] x, y = 25, 50 big = x if x < y else y Syntax and example The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result.
  • 10. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Basic Python Questions Q5. What is monkey patching in Python? In Python, the term monkey patch only refers to dynamic modifications of a class or module at runtime. Consider the below example: Then, if we run the monkey- patch testing like this: As we can see, we did make some changes in the behavior of f() in MyClass using the function we defined, monkey_f(), outside of the module m.
  • 11. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Basic Python Questions Q6. How can you randomize the items of a list in place in Python? from random import shuffle x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High'] shuffle(x) print(x) Consider the example shown below: ['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag'] Output:
  • 12. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Basic Python Questions Q7. Write a sorting algorithm for a numerical dataset in Python.
  • 13. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Basic Python Questions Q8. Looking at the below code, write down the final values of A0, A1, ...An. 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) 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]]
  • 14. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Basic Python Questions Q9. Explain split(), sub(), subn() methods of “re” module in Python. To modify the strings, Python’s “re” module is providing 3 methods. They are: ❑ split() – uses a regex pattern to “split” a given string into a list. ❑ sub() – finds all substrings where the regex pattern matches and then replace them with a different string ❑ subn() – it is similar to sub() and also returns the new string along with the no. of replacements.
  • 15. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Basic Python Questions Q11. Explain Inheritance in Python with example? Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class. They are different types of inheritance supported by Python: ❑ Single Inheritance – where a derived class acquires the members of a single super class. ❑ Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 is inherited from base2. ❑ Hierarchical inheritance – from one base class you can inherit any number of child classes ❑ Multiple inheritance – a derived class is inherited from more than one base class. class ParentClass: v1 = "from ParentClass - v1" v2 = "from ParentClass - v2" class ChildClass(ParentClass): pass print(ChildClass.v1) print(ChildClass.v2)
  • 17. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Django Questions Q12. Mention the Django architecture? Django MVT Pattern: 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. ViewURL Model TemplateDjangoUser
  • 18. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Django Questions Q13. Explain how you can set up the Database in Django? 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 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 file name of that file. ❑ If you are not choosing SQLite as your database then setting like Password, Host, User, etc. must be added.
  • 19. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Django Questions Q13. Explain how you can set up the Database in Django? Django uses SQLite as 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. setting.py
  • 20. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Django Questions Q14. Give an example how you can write a VIEW in Django? from django.http import HttpResponse import datetime def Current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html) Returns the current date and time, as an HTML document
  • 21. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Django Questions Q15. Mention what does the Django templates consists of? 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 controls the logic of the template. DataBase ViewsModels Templates URL Browser
  • 22. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Django Questions Q16. Explain the use of session in Django framework? Django provides 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. So the data itself is not stored client side. This is nice from a security perspective. Client-Side # Session ID Cookie Website Server-Side
  • 23. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Django Questions Q17. List out the inheritance styles in Django? Abstract base classes: This style is used when you only wants 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 In Django, there is three possible inheritance styles:
  • 24. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Django Questions Q18. Mention what does the Django field class types? Field Class The database column type The default HTML widget to avail while rendering a form field The minimal validation requirements used in Django admin and in automatically generated forms
  • 25. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Web Scraping Using Python Questions
  • 26. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Web Scraping Using Python Questions Q19. How To Save An Image Locally Using Python Whose URL Address I Already Know? import urllib.request urllib.request.urlretrieve("URL", "local-filename.jpg")
  • 27. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Web Scraping Using Python Questions Q20. How Can I Get The Google Cache Age Of Any URL Or Web Page? 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 edureka.co you’d use the following URL: http://webcache.googleusercontent.com/search?q=cache:edureka.co
  • 28. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Web Scraping Using Python Questions Q21. You are required to scrap data from IMDB top 250 movies page. It should only have fields movie name, year, and rating. from bs4 import BeautifulSoup import requests import sys url = 'http://www.imdb.com/chart/top' 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)
  • 29. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions
  • 30. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions Q22. How To Get Indices Of N Maximum Values In A Numpy Array? import numpy as np arr = np.array([1, 3, 2, 4, 5]) print(arr.argsort()[-3:][::-1]) Output: [ 4 3 1 ]
  • 31. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions Q23. How Do I Calculate Percentiles With Python/Numpy? import numpy as np a = np.array([1,2,3,4,5]) p = np.percentile(a, 50) # return 50th percentile, e.g median. print(p) Output: 3
  • 32. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Python Questions Q24. What advantages does NumPy arrays offers over (nested) Python lists? ❑ Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate. ❑ They have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element. ❑ NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented. ❑ NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc.
  • 33. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions Q25. What is the difference between NumPy and SciPy? ❑ In an ideal world, NumPy would contain nothing but the array data type and the most basic operations: indexing, sorting, reshaping, basic elementwise functions, et cetera. ❑ All numerical code would reside in SciPy. However, one of NumPy’s important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors. ❑ Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms. ❑ If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.
  • 34. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions Q26. How Do I make 3D plots/visualizations using NumPy/SciPy? 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.
  • 35. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions Q27. How do I find the indices of an array where some condition is true? import numpy as np a = np.array([[1,2,3],[4,5,6],[7,8,9]]) print(a > 3 ) print(np.nonzero(a > 3)) Output: [[False False False] [ True True True] [ True True True]] (array([1, 1, 1, 2, 2, 2], dtype=int32), array([0, 1, 2, 0, 1, 2], dtype=int32))
  • 36. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions Q28. How to rename column headers in Pandas DataFrame import pandas as pd data = {'Commander': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'Date': ['2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08'], 'Score': [4, 24, 31, 2, 3]} df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma']) df.columns = ['Leader', 'Time', 'Score'] print(df) Original DataFrame Updated DataFrame
  • 37. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions Q29. What is the function to iterate through the values in a manner that one also retrieves the index ? df.iteritems unfortunately only iterates column by column. The newest versions of pandas now include a built-in function for iterating over rows. for index, row in df.iterrows(): # do some logic here
  • 38. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions Q30. How to convert a list of Dictionaries into a Pandas DataFrame Supposing d is your list of dicts, simply: pd.DataFrame(d)
  • 39. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions Q31. Lets say that I have the following Pandas DataFrame: df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]}) how can I subset based on a list of values? - something like this: list_of_values = [3,6] y = df[df['A'] in list_of_values] This is indeed a duplicate of how to filter the dataframe rows of pandas by "within"/"in"?. translating the response to the example shown above: df[df['A'].isin([3, 6])] A B 1 6 2 2 3 3
  • 40. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions Q32. I have a DataFrame: STK_ID EPS cash STK_ID RPT_Date 601166 20111231 601166 NaN NaN 600036 20111231 600036 NaN 12 600016 20111231 600016 4.3 NaN 601009 20111231 601009 NaN NaN 601939 20111231 601939 2.5 NaN 000001 20111231 000001 NaN NaN I just want the records whose EPS is not NaN Just take rows where EPS is finite: df = df[np.isfinite(df['EPS'])]
  • 41. www.edureka.co/pythonEDUREKA PYTHON CERTIFICATION TRAINING Data Analysis Using Python Questions Q33. Write a program to read and write the binary data using python? The module that is used to write and read the binary data is known as struct. The program can read or write the binary data is: import struct f = open(file-name, "rb") # This Open() method allows the file to get opened in binary mode to make it portable for # use. s = f.read(8) f.write("Hello, World!n")