Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
77 views

Python Interview Questions and Answers For 2024

This document discusses top Python interview questions and answers. It covers basic Python questions, OOP questions, Python programs, libraries, web scraping, data analysis and multiple choice questions across 7 sections to help prepare for Python interviews.

Uploaded by

Shivam mishra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

Python Interview Questions and Answers For 2024

This document discusses top Python interview questions and answers. It covers basic Python questions, OOP questions, Python programs, libraries, web scraping, data analysis and multiple choice questions across 7 sections to help prepare for Python interviews.

Uploaded by

Shivam mishra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.

edurek

Q2. What are the key features of Python?


Q3. What type of language is python? 
Q4. How is Python an interpreted language?
Q5. What is pep 8?
Q6. How is memory managed in Python?
Q7. What is name space in Python?
Q8. What is PYTHON PATH?
Q9. What are python modules?
Q10. What are local variables and global variables in Python?

We have compiled a list of top Python interview questions which are classi�ed into 7 sections, na
• Basic Interview Questions
• OOPS Interview Questions
• Basic Python Programs
• Python Libraries Interview Questions
• Web Scraping Interview Questions
• Data Analysis Interview Questions
• Multiple Choice Questions (MCQ)

Let us �rst begin with some Basic Python Interview Questions.

Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can’t

Lists are slower than tuples. Tuples are faster than list.

Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)

• Python is an language. That means that, unlike languages like C and its varia
compiled before it is run. Other interpreted languages include PHP and Ruby.
• Python is , this means that you don’t need to state the types of varia
anything like that. You can do things like x=111 and then x="I'm a string" without error
• Python is well suited to in that it allows the de�nition o
and inheritance. Python does not have access speci�ers (like C++’s public, private).
• In Python, are . This means that they can be assigned to
functions and passed into functions. Classes are also �rst class objects
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

readability.

The bene�ts of using python are-

1. – Python is a high-level programming language that is easy to use, read, w


2. – Since python is interpreted language, it executes the code line
occurs in any line.
3. – the developer does not assign data types to variables at the time
assigned during execution.
4. – Python is free to use and distribute. It is open source.
5. – Python has vast libraries that contain almost any fu
provides the facility to import other packages using Python Package Manager(pip).
6. – Python programs can run on any platform without requiring any change.
7. The data structures used in python are user friendly.
8. It provides more functionality with less coding.

Bangalore New York UK


Hyderabad Chicago London
Delhi Atlanta Canada
Chennai Houston Toronto
Mumbai Los Angeles Australia
Pune Boston UAE
Kolkata Miami Dubai
Ahmedabad San Francisco Philippines

A namespace in python refers to the name which is assigned to each object in python. The o
functions. As each object is created, its name along with space(the address of the outer function
created. The namespaces are maintained in python like a dictionary where the key is the namesp
the object. There 4 types of namespace in python-

1. – These namespaces contain all the built-in objects in python and are a
running.
2. – These are namespaces for all the objects created at the level of the ma
3. – These namespaces are at the higher level or outer function.
4. – These namespaces are at the local or inner function.
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

This ������� �������� is intended as a Crash Course on ������� for Beginners. ������� has be
exponentially. But, ������� is still not known to many people. In this video, I aim to show you th
use ������� for yourself. ������� has been the buzzword for a while now. This yap lab was put
release and has been changing the game ever since.

Dictionary and list comprehensions are just another concise way to de�ne dictionaries and

Example of list comprehension is-

1 x=[i for i in range(5)]

The above code creates a list as below-

1 4
2 [0,1,2,3,4]

Example of dictionary comprehension is-

1 x=[i : i+2 for i in range(5)]

The above code creates a list as below-


Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

items is not important. Eg. {1:’apple’,2:’mango}



– There are 2 boolean values- and .

The .py �les are the python source code �les. While the .pyc �les contain the bytecode of th
created when the code is imported from some other source. The interpreter converts the source
by saving time. You can get a better understanding with the Data Engineering Course in Washing

Slicing is used to access parts of sequences like lists, tuples, and strings. The syntax of slicin
can be omitted as well. When we write [start:end] this returns all the elements of the sequence
end-1 element. If the start or end element is negative i, it means the ith element from the end. Th
how many elements have to be skipped. Eg. if there is a list- [1,2,3,4,5,6,7,8]. Then [-1:2:2] wil
the last element till the third element by printing every second element.i.e. [8,6,4].

Keywords in python are reserved words that have special meaning.They are generally used
Keywords cannot be used for variable or function names. There are following 33 keywords in pyt

• And
• Or
• Not
• If
• Elif
• Else
• For
• While
• Break
• As
• Def
• Lambda
• Pass
• Return
• True
• False
• Try
• With
• Assert
• Class
• Continue
• Del
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

2. – It is created by assigning a single character enclosed in double quotes


3. include numeric values that can be either integer, �oatingpoint value, or
4. – These can be 2 values- either True or False.
5. – These are of 4 types-

a) List collections-Eg. a=[1,2,3,’Amit’]

b) Tuple literals- Eg. a=(5,6,7,8)

c) Dictionary literals- Eg. dict={1: ’apple’, 2: ’mango, 3: ’banana`’}

d) Set literals- Eg. {“Tanya”, “Rohit”, “Mohan”}

6. Special literal- Python has 1 special literal None which is used to return a null variable.

The dataframes in python can be combined in the following ways-

1. Concatenating them by stacking the 2 dataframes vertically.


2. Concatenating them by stacking the 2 dataframes horizontally.
3. Combining them on a common column. This is referred to as joining.

The concat() function is used to concatenate two dataframes. Its syntax is- pd.concat([dataframe1

Dataframes are joined together on a common column called a key. When we combine all the row
the join used is outer join. While, when we combine the common rows or intersection, the join us
pd.concat([dataframe1, dataframe2], axis=’axis’, join=’type_of_join)

The new features in Python 3.9.0.0 version are-

• New Dictionary functions Merge(|) and Update(|=)


• New String Methods to Remove Pre�xes and Su�xes

• New Parser based on PEG rather than LL1
• New modules like zoneinfo and graphlib

• Deprecated functions and commands such as deprecated parser and symbol modules, dep
• Removal of erroneous methods, functions, etc.

Memory is managed in Python in the following ways:


Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

It is an environment variable which is used when a module is imported. Whenever a mod


also looked up to check for the presence of the imported modules in various directories. The
which module to load.

Python modules are �les containing Python code. This code can either be functions classes
a .py �le containing executable code.

Some of the commonly used built-in modules are:

• os
• sys
• math
• random
• data time
• JSON

Variables declared outside a function or in global space are called global variables. These va
function in the program.

Any variable declared inside a function is known as a local variable. This variable is present i
global space.

1 a=2
2 def add():
3 b=3
4 c=a+b
5 print(c)
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

– converts integer to octal



This function is used to convert to a tuple.

This function returns the type after converting to set.

This function is used to convert any data type to a list type.

This function is used to convert a tuple of order (key, value) into a dictionary.

Used to convert integer into a string.

This function converts real numbers to complex(real,imag) number.

To install Python on Windows, follow the below steps:

• Install python from this link: https://www.python.org/downloads/


• After this, install it on your PC. Look for the location where PYTHON has been installed on y
command on your command prompt: cmd python.
• Then go to advanced system settings and add a new variable and name it as PYTHON_NAM
• Look for the path variable, select its value and select ‘edit’.
• Add a semicolon towards the end of the value if it’s not present and then type %PYTHON_H

Indentation is necessary for Python. It speci�es a block of code. All code within loops, cl
within an indented block. It is usually done using four space characters. If your code is not
execute accurately and will throw errors as well.

Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a si
lists can hold any data type elements.

1 import array as arr


2 My_Array=arr.array('i',[1,2,3,4])
3 My_list=[1,'abc',1.20]
4 print(My_Array)
5 print(My_list)

array(‘i’, [1, 2, 3, 4]) [1, ‘abc’, 1.2]

A function is a block of code which is executed only when it is called. To de�ne a Python fun
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

1 class Employee:
2 def __init__(self, name, age,salary):
3 self.name = name 
4 self.age = age
5 self.salary = 20000
6 E1 = Employee("XYZ", 23, 20000)
7 # E1 is the instance of class Employee.
8 #__init__ allocates memory for E1.
9 print(E1.name)
10 print(E1.age)
11 print(E1.salary)

XYZ

23

20000

An anonymous function is known as a lambda function. This function can have any number
one statement.

1 a = lambda x,y : x+y


2 print(a(5, 6))

11

Self is an instance or an object of a class. In Python, this is explicitly included as the �rst pa
case in Java where it’s optional. It helps to di�erentiate between the methods and attributes of a

The self variable in the init method refers to the newly created object while in other method
method was called.

Allows loop termination when some condition is met and the control is t
Break
to the next statement.

Allows skipping some part of a loop when some speci�c condition is m


Continue
control is transferred to the beginning of the loop

Used when you need some block of code syntactically, but you want
Pass
execution. This is basically a null operation. Nothing happens when this is

[::-1] is used to reverse the order of an array or a sequence.


Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']


Iterators are objects which can be traversed though or iterated upon.

Random module is the standard module that is used to generate a random number. The m

1 import random
2 random.random

The statement random.random() method return the �oating-point number that is in the range
random �oat numbers. The methods that are used with the random class are the bound meth
instances of the Random can be done to show the multi-threading programs that creates a
threads. The other random generators that are used in this are:

1. : it chooses an integer and de�ne the range in-between [a, b). It retur
randomly from the range that is speci�ed. It doesn’t build a range object.
2. : it chooses a �oating point number that is de�ned in the range of [a,b).Iyt ret
3. : it is used for the normal distribution where the mu is a mea
used for standard deviation.
4. that is used and instantiated creates independent multiple random num

For the most part, xrange and range are the exact same in terms of functionality. They both
of integers for you to use, however you please. The only di�erence is that range returns a Pytho
an xrange object.

This means that xrange doesn’t actually generate a static list at run-time like range does. It crea
with a special technique called yielding. This technique is used with a type of object known as ge
have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function

� � �

Reviews Reviews Reviews

     (21125)      (53217)      (119955)


Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

Pickle module accepts any Python object and converts it into a string representation and d
function, this process is called pickling. While the process of retrieving original
 Python
representation is called unpickling.

Functions that return an iterable set of items are called generators.

In Python, the capitalize() method capitalizes the �rst letter of a string. If the string already
beginning, then, it returns the original string.

To convert a string to lowercase, lower() function can be used.

1 stg='ABCD'
2 print(stg.lower())

abcd

Multi-line comments appear in more than one line. All the lines to be commented are to b
very good . All you need to do is hold the ctrl
wherever you want to include a # character and type a # just once. This will comment all the
cursor.

Docstrings are not actually comments, but, they are . These doc
They are not assigned to any variable and therefore, at times, serve the purpose of comments as

1 """
2 Using docstring as a comment.
3 This code divides 2 numbers
4 """
5 x=8
6 y=4
7 z=x/y
8 print(z)

2.0

Q44. What is the purpose of ‘is’, ‘not’ and ‘in’ operators?


Operators are special functions. They take one or more values and produce a correspondin

: returns true when 2 operands are true (Example: “a” is ‘a’)


Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

2. It is impossible to de-allocate those portions of memory that are reserved by the C library.
3. On exit, because of having its own e�cient clean up mechanism, Python would  try to de-all

The built-in datatypes in Python is called dictionary. It de�nes one-to-one relationship betw
contain pair of keys and their corresponding values. Dictionaries are indexed by keys.

Let’s take an example:

The following example contains some keys. Country, Capital & PM. Their corresponding va
respectively.

1 dict={'Country':'India','Capital':'Delhi','PM':'Modi'}

1 print dict[Country]

Output:India

1 print dict[Capital]

Output:Delhi

1 print dict[PM]

Output:Modi

The Ternary operator is the operator that is used to show the conditional statements. T
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, 50big = x if x < y else y

The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is retur
then big=y will be sent as a result.

We use *args when we aren’t sure how many arguments are going to be passed to a functio
list or tuple of arguments to a function. **kwargs is used when we don’t know how many keywo
function, or it can be used to pass the values of a dictionary as keyword arguments. The id
convention, you could also use *bob and **billy but that would not be wise.

It is used to determine the length of a string, a list, an array, etc.


Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

The index for the negative number starts from ‘-1’ that represents the last index in the sequence
and the sequence carries forward like the positive number. 

The negative index is used to remove any new-line spaces from the string and allow the string to
given as S[:-1]. The negative index is also used to show the index to represent the string in correc

Python packages are namespaces containing multiple modules.

To delete a �le in Python, you need to import the OS Module. After that, you need to use th

1 import os
2 os.remove("xyz.txt")

Built-in types in Python are as follows –

• Integers
• Floating-point
• Complex numbers
• Strings
• Boolean
• Built-in functions

1. Python’s lists are e�cient general-purpose containers. They support (fairly) e�cient ins
concatenation, and Python’s list comprehensions make them easy to construct and manipu
2. They have certain limitations: they don’t support “vectorized” operations like elementwise
the fact that they can contain objects of di�ering types mean that Python must store typ
and must execute type dispatching code when operating on each element.
3. NumPy is not just more e�cient; it is also more convenient. You get a lot of vector and m
sometimes allow one to avoid unnecessary work. And they are also e�ciently implemented
4. NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast
algebra, histograms, etc.

Elements can be added to an array using the , and the functio

1 a=arr.array('d', [1.1 , 2.1 ,3.1] )


2 a.append(3.4)
3 print(a)
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

1 a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])


2 print(a.pop())
3 print(a.pop(3)) 
4 a.remove(1.1)
5 print(a)

4.6

Weekday / Weekend Batches

3.1

array(‘d’, [2.2, 3.8, 3.7, 1.2])

Python is an object-oriented programming language. This means that any program can be s
object model. However, Python can be treated as a procedural as well as structural language.

Check out these AI and ML courses by E & ICT Academy NIT Warangal to learn Python usage in AI
career.

Shallow copy is used when a new instance type gets created and it keeps the values that
Shallow copy is used to copy the reference pointers just like it copies the values. These referen
and the changes made in any member of the class will also a�ect the original copy of it. Shallow
the program and it depends on the size of the data that is used.

Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the refe
makes the reference to an object and the new object that is pointed by some other object gets
original copy won’t a�ect any other copy that uses the object. Deep copy makes execution of th
certain copies for each object that is been called.
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

1. Create a �le with any name and in any language that is supported by the compiler of yo
�le.cpp 
2. Place this �le in the Modules/ directory of the distribution which is getting used.
3. Add a line in the �le Setup.local that is present in the Modules/ directory.
4. Run the �le using spam �le.o
5. After a successful run of this rebuild the interpreter by using the make command on the top
6. If the �le is changed then run rebuildMake�le by using the command as ‘make Make�le’.

Python libraries are a collection of Python packages. Some of the majorly used python libraries a
Scikit-learn and many more.

The split() method is used to separate a given String in Python.

1 a="edureka python"
2 print(a.split())

[‘edureka’, ‘python’]

Modules can be imported using the keyword. You can import modules in three ways-

1 import array #importing using the original module name


2 import array as arr # importing using an alias name
3 from array import * #imports everything present in the array module

Next, in this Python Interview Questions blog, let’s have a look at Object Oriented Concepts in Py

Here is the list of Top 10 Trending Technologies in 2023 that will be in demand!
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

class and the class that is inherited is called a derived / child class.

They are di�erent types of inheritance supported by Python:

1. – where a derived class acquires the members of a single super class.


2. – a derived class d1 in inherited from base class base1, and d2 are
3. – from one base class you can inherit any number of child classe
4. – a derived class is inherited from more than one base class.

Class in Python is created using the keyword.

1 class Employee:
2 def __init__(self, name):
3 self.name = name
4 E1=Employee("abc")
5 print(E1.name)

abc

In Python, the term monkey patch only refers to dynamic modi�cations of a class or module

Consider the below example:

1 # m.py
2 class MyClass:
3 def f(self):
4 print "f()"

We can then run the monkey-patch testing like this:

1 import m
2 def monkey_f(self):
3 print "monkey_f()"
4
5 m.MyClass.f = monkey_f
6 obj = m.MyClass()
7 obj.f()

The output will be as below:

monkey_f()

As we can see, we did make some changes in the behavior of f() in MyClass using the function w
the module m.

Multiple inheritance means that a class can be derived from more than one parent classe
inheritance, unlike Java.
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

An empty class is a class that does not have any code de�ned within its block.
 It can be
However, you can create objects of this class outside the class itself. IN PYTHON THE PASS c
executed. it’s a null statement.

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

Name = xyz

It returns a featureless object that is a base for all classes. Also, it does not take any parame
Next, let us have a look at some Basic Python Programs in these Python Interview Questions.

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

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

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

*
***
*****
*******
*********
***********
*************
***************
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

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

enter number 3

Prime

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

enter sequence 323 palindrome

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

1 with open(SOME_LARGE_FILE) as fh:


2 count = 0
3 text = fh.read()
4 for character in text:
5 if character.isupper():
6 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())

The following code can be used to sort a list in Python:

1 list = ["1", "4", "0", "6", "9"]


2 list = [int(i) for i in list]
3 list.sort()
4 print (list)
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

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],

Next, in this Python Interview Questions let's have a look at some Python Librarie

Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intenti
Jinja2 are two of their dependencies. This means it will have little to no dependencies on
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 �ask,
the user can look at the session contents and modify them. The user can modify the sessi
Flask.secret_key.

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

Flask is much simpler compared to Django but, Flask does not do a lot for you meaning you will n
whereas Django does a lot for you wherein you would not need to do much work. Django consist
user will need to analyze whereas Flask gives the users to create their own code, therefore, maki
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 requirem
external libraries. Flask is ready to use.
• Pyramid is built for larger applications. It provides �exibility and lets the developer use the
developer can choose the database, URL structure, templating style and more. Pyramid is h
• Django can also be used for larger applications just like Pyramid. It includes an ORM.

Django MVT Pattern:


Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on


• : The name of your database. In the case if you are using SQLite as your
 database, in
on your computer, Name should be a full absolute path, including the �le name of that �le.
• If you are not choosing SQLite as your database then settings like Password, Host, User, etc

Django uses SQLite as a default database, it stores data as a single �le in the �lesystem. If
—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your d
create a new database for your Django project. Either way, with your (empty) database in place,
how to use it. This is where your project’s settings.py �le comes in.

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

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

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

1 from django.http import HttpResponse


2 import datetime
3
4 def Current_datetime(request):
5 now = datetime.datetime.now()
6 html = "It is now %s/body/html % now
7 return HttpResponse(html)

Returns the current date and time, as an HTML document

The template is a simple text �le. It can create any text-based format like XML, CSV, H
variables that get replaced with values when the template is evaluated and tags (% tag %) that co
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

Python Interview Questions – Django Template

Django provides a session that lets you store and retrieve data on a per-site-visitor basis.
sending and receiving cookies, by placing a session ID cookie on the client side, and storing all th
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

1. Abstract Base Classes: This style is used when you only want parent’s class to hold inform
out for each child model. 
2. Multi-table Inheritance: This style is used If you are sub-classing an existing model and need
database table.
3. Proxy models: You can use this model, If you only want to modify the Python level behavio
the model’s �elds.

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

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

1 import urllib.request
2 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 cac
the time for. For example, to check the Google Webcache age of edureka.co you’d use the follow

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

We will use the following lines of code:

1 from bs4 import BeautifulSoup


2
3 import requests
4 import sys
5
6 url = '<a href="http://www.imdb.com/chart/top">http://www.imdb.com/chart/to
7 response = requests.get(url)
8 soup = BeautifulSoup(response.text)
9 tr = soup.findChildren("tr")
10 tr = iter(tr)
11 next(tr)
12
13 for movie in tr:
14 title = movie.find('td', {'class': 'titleColumn'} ).find('a').contents[0]
15 year = movie.find('td', {'class': 'titleColumn'} ).find('span', {'class': '
16 rating = movie.find('td', {'class': 'ratingColumn imdbRating'} ).find('stro
17 row = title + ' - ' + year + ' ' + ' ' + rating
18
19 print(row)

The above code will help scrap data from IMDb’s top 250 list
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

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

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

Output

[ 4 3 1 ]

We can calculate percentiles with the following code

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

:3

It refers to Numerical python. It refers to Scienti�c python.


It has fewer new scienti�c computing features. Most new scienti�c computing
It has more fully-featured versi
It contains less linear algebra functions.
modules, as well as many other
NumPy has a faster processing speed. SciPy on the other hand has slo

Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in t
integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, where
of high-quality 3D visualization features, utilizing the powerful VTK engine.

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

a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) d = (40:”john”, 45:”50”)
b, c & d.

Dictionaries are created by specifying keys and values.


Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

Identi�ers can be of any length.


a) they are used to indicate a private variables of a class


b) they confuse the interpreter
c) they are used to indicate global variables
d) they slow down execution
a) they are used to indicate a private variable of a class

As Python has no concept of private variables, leading underscores are used to indicate variables
outside the class.

a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000
b) a b c = 1000 2000 3000

Spaces are not allowed in variable names.

1 try:
2 if '1' != 1:
3 raise "someError"
4 else:
5 print("someError has not occured")
6 except "someError":
7 print ("someError has occured")

a) someError has occured


b) someError has not occured
c) invalid code
d) none of the above
c) invalid code

A new exception class must inherit from a BaseException. There is no such inheritance here.

a) Error
b) None
c) 25
d) 2
c) 25

The index -1 corresponds to the last index in the list.

a) out�le = open(“c:scores.txt”, “r”)


b) out�le = open(“c:scores.txt”, “w”)
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek

The WITH statement when used with open �le guarantees that the �le object is closed when the

a) always
b) when an exception occurs
c) when no exception occurs
d) when an exception occurs into except block
c) when no exception occurs

The else part is executed when no exception occurs.

I hope this set of Python Interview Questions will help you in preparing for your interviews. All th

Got a question for us? Please mention it in the comments section and we will get back to you at t

Edureka o�ers a Data Science with Python Course that will help you master the art of analyt
employing Python. You will use libraries like Pandas, Numpy, Matplotlib, Scipy, Scikit, and Pyspa
Python machine learning, scripts, sequence, web scraping, and big data analytics leveraging Apac

SAT&SUN (Weekend Batch)

  

Watch Now Watch Now Watch Now

You might also like