Basic Python Interview Questions
Basic Python Interview Questions
Basic Python Interview Questions
LIST vs TUPLES
LIST TUPLES
Lists are mutable i.e they can Tuples are immutable (tuples are lists
be edited. which can’t be edited).
Lists are slower than tuples. Tuples are faster than list.
Syntax: list_1 = [10, ‘Chelsea’,
Syntax: tup_1 = (10, ‘Chelsea’ , 20)
20]
Q2. What are the key features of Python?
Q5.What is pep 8?
Ans: A namespace is a naming system used to make sure that names are
unique to avoid naming conflicts.
Q9. What are python modules? Name some commonly used built-in
modules in Python?
Ans: Python modules are files containing Python code. This code can
either be functions classes or variables. A Python module is a .py file
containing executable code.
• os
• sys
• math
• random
• data time
• JSON
Global Variables:
Local Variables:
Example:
1 a=2
2 def add():
3 b=3
4 c=a+b
5 print(c)
6 add()
Output: 5
When you try to access the local variable outside the function add(), it will
throw an error.
Ans: Type conversion refers to the conversion of one data type iinto
another.
list() – This function is used to convert any data type to a list type.
Ans: Arrays and lists, in Python, have the same way of storing data. But,
arrays can hold only a single data type elements whereas lists can hold any
data type elements.
Example:
Example:
1 def Newfunc():
2 print("Hi, Welcome to Edureka")
3 Newfunc(); #calling the function
Output: Hi, Welcome to Edureka
Q17.What is __init__?
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)
Output:
XYZ
23
20000
Example:
The self variable in the init method refers to the newly created object while
in other methods, it refers to the object whose method was called.
Q22. How can you randomize the items of a list in place in Python?
Ans: Iterators are objects which can be traversed though or iterated upon.
1 import random
2 random.random
The statement random.random() method return the floating point number
that is in the range of [0, 1). The function generates random float numbers.
The methods that are used with the random class are the bound methods
of the hidden instances. The instances of the Random can be done to show
the multi-threading programs that creates a different instance of individual
threads. The other random generators that are used in this are:
This means that xrange doesn’t actually generate a static list at run-time
like range does. It creates the values as you need them with a special
technique called yielding. This technique is used with a type of object
known as generators. That means that if you have a really gigantic range
you’d like to generate a list for, say one billion, xrange is the function to
use.
This is especially true if you have a really memory sensitive system such as
a cell phone that you are working with, as range will use as much memory
as it can to create your array of integers, which can result in a Memory
Error and crash your program. It’s a memory hungry beast.
Example:
Ans: Pickle module accepts any Python object and converts it into a string
representation and dumps it into a file by using dump function, this process
is called pickling. While the process of retrieving original Python objects
from the stored string representation is called unpickling.
Ans: Functions that return an iterable set of items are called generators.
Python Certification Training for Data Science
Explore Curriculum
Ans: In Python, the capitalize() method capitalizes the first letter of a string.
If the string already consists of a capital letter at the beginning, then, it
returns the original string.
Example:
1 stg='ABCD'
2 print(stg.lower())
Output: abcd
Ans: Multi-line comments appear in more than one line. All the lines to be
commented are to be prefixed by a #. You can also a very good shortcut
method to comment multiple lines. All you need to do is hold the ctrl key
and left click in every place wherever you want to include a # character
and type a # just once. This will comment all the lines where you introduced
your cursor.
Ans: Docstrings are not actually comments, but, they are documentation
strings. These docstrings are within triple quotes. They are not assigned to
any variable and therefore, at times, serve the purpose of comments as
well.
Example:
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)
Output: 2.0
Ans: Operators are special functions. They take one or more values and
produce a corresponding result.
is: returns true when 2 operands are true (Example: “a” is ‘a’)
Ans: Help() and dir() both functions are accessible from the Python
interpreter and used for viewing a consolidated dump of built-in functions.
Q35. Whenever Python exits, why isn’t all the memory de-allocated?
Ans:
1. Whenever Python exits, especially those Python modules which are
having circular references to other objects or the objects that are
referenced from the global namespaces are not always de-allocated
or freed.
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 efficient clean up mechanism,
Python would try to de-allocate/destroy every other object.
The following example contains some keys. Country, Capital & PM. Their
corresponding values are India, Delhi and Modi respectively.
1dict={'Country':'India','Capital':'Delhi','PM':'Modi'}
1print dict[Country]
India
1 print dict[Capital]
Delhi
1 print dict[PM]
Modi
Q37. How can the ternary operators be used in python?
Ans: 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.
Syntax:
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.
Q38. What does this mean: *args, **kwargs? And why would we use
it?
Ans: We use *args when we aren’t sure how many arguments are going to
be passed to a function, or if we want to pass a stored list or tuple of
arguments to a function. **kwargs is used when we don’t know how many
keyword arguments will be passed to a function, or it can be used to pass
the values of a dictionary as keyword arguments. The identifiers args and
kwargs are a convention, you could also use *bob and **billy but that would
not be wise.
Example:
1 stg='ABCD'
2 len(stg)
Q41. What are negative indexes and why are they used?
Ans: The sequences in Python are indexed and it consists of the positive
as well as negative numbers. The numbers that are positive uses ‘0’ that is
uses as first index and ‘1’ as the second index and the process goes on like
that.
The index for the negative number starts from ‘-1’ that represents the last
index in the sequence and ‘-2’ as the penultimate index 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 except the last character that is given as S[:-1]. The
negative index is also used to show the index to represent the string in
correct order.
Ans: To delete a file in Python, you need to import the OS Module. After
that, you need to use the os.remove() function.
Example:
1 import os
2 os.remove("xyz.txt")
Q44. What are the built-in types of python?
• Integers
• Floating-point
• Complex numbers
• Strings
• Boolean
• Built-in functions
Ans: Elements can be added to an array using the append(), extend() and
the insert (i,x) functions.
Example:
Example:
4.6
3.1
Ans: Shallow copy is used when a new instance type gets created and it
keeps the values that are copied in the new instance. 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. Shallow copy
allows faster execution of 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 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. Deep copy makes execution of the program slower
due to making certain copies for each object that is been called.
Ans:
Ans: The compiling and linking allows the new extensions to be compiled
properly without any error and the linking can be done only when it passes
the compiled procedure. If the dynamic loading is used then it depends on
the style that is being provided with the system. The python interpreter can
be used to provide the dynamic loading of the configuration setup files and
will rebuild the interpreter.
1. Create a file with any name and in any language that is supported by
the compiler of your system. For example file.c or file.cpp
2. Place this file in the Modules/ directory of the distribution which is
getting used.
3. Add a line in the file Setup.local that is present in the Modules/
directory.
4. Run the file using spam file.o
5. After a successful run of this rebuild the interpreter by using the make
command on the top-level directory.
6. If the file is changed then run rebuildMakefile by using the command
as ‘make Makefile’.
Example:
1 a="edureka python"
2 print(a.split())
Output: [‘edureka’, ‘python’]
Modules can be imported using the import keyword. You can import
modules in three ways-
Example:
Ans: 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:
Example:
1 class Employee:
2 def __init__(self, name):
3 self.name = name
4 E1=Employee("abc")
5 print(E1.name)
Output: abc
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 we defined, monkey_f(), outside of the
module m.
Ans: Multiple inheritance means that a class can be derived from more
than one parent classes. Python does support multiple inheritance, unlike
Java.
Ans: 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.
Ans: Encapsulation means binding the code and the data together. A
Python class in an example of encapsulation.
Ans: 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.
Ans: 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 class a:
2 &amp;amp;nbsp; pass
3 obj=a()
4 obj.name="xyz"
5 print("Name = ",obj.name)
Output:
Name = xyz
Q64. What does an object() do?
Ans: It returns a featureless object that is a base for all classes. Also, it
does not take any parameters.
Basic Python Programs – Python Interview Questions
1 def pyfunc(r):
2 for x in range(r):
3 print(' '*(r-x-1)+'*'*(2*x+1))
4 pyfunc(9)
Output:
*
***
*****
*******
*********
***********
*************
***************
*****************
Prime
1 a=input("enter sequence")
2 b=a[::-1]
3 if a==b:
4 &amp;amp;nbsp; print("palindrome")
5 else:
6 &amp;amp;nbsp; print("Not a Palindrome")
Output:
Q70. Write a one-liner that will count the number of capital letters in a
file. Your code should work even if the file is too big to fit in memory.
Ans: Let us first write a multiple line solution and then convert it to one-
liner code.
1 A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
2 A1 = range(10)A2 = sorted([i for i in A1 if i in A0])
3 A3 = sorted([A0[s] for s in A0])
4 A4 = [i for i in A1 if i in A3]
5 A5 = {i:i*i for i in A1}
6 A6 = [[i,i*i] for i in A1]
7 print(A0,A1,A2,A3,A4,A5,A6)
Ans: The following will be the final outputs of A0, A1, … A6
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.
Ans:
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.
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.
DATABASES = {
1
'default': {
2 'ENGINE' : 'django.db.backends.sqlite3',
3 'NAME' : os.path.join(BASE_DIR,
4 'db.sqlite3'),
5 }
6 }
Q78. Give an example how you can write a VIEW in Django?
Ans: 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
Ans: 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.
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.
import urllib.request
1 urllib.request.urlretrieve("URL", "local-
2 filename.jpg")
Q83. How can you Get the Google cache age of any URL or web
page?
Q84. You are required to scrap data from IMDb top 250 movies page. It
should only have fields movie name, year, and rating.
print(row)
The above code will help scrap data from IMDb’s top 250 list
Ans: 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.
Ans: 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 –
Ans: 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 ]
Q88. How do you calculate percentiles with Python/ NumPy?
1 import numpy as np
2 a = np.array([1,2,3,4,5])
3 p = np.percentile(a, 50) #Returns 50th percentile,
4 e.g. median
print(p)
Output
3
Q89. What is the difference between NumPy and SciPy?
Ans:
1. 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.
2. 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.
3. 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.
4. 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.
a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) d = (40:”john”, 45:”50”)
Answer: b, c & d.
a) /
b) //
c) %
d) None of the mentioned
Answer: b) //
When both of the operands are integer then python chops out the fraction
part and gives you the round off value, to get the accurate answer use floor
division. For ex, 5/2 = 2.5 but both of the operands are integer so answer of
this expression in python is 2. To get the 2.5 as the answer, use floor
division using //. So, 5//2 = 2.5
a) 31 characters
b) 63 characters
c) 79 characters
d) None of the above
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
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
Q97. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?
a) Error
b) None
c) 25
d) 2
Answer: c) 25
1 f = None
2
3 for i in range (5):
4 with open("data.txt", "w") as f:
5 if i &amp;gt; 2:
6 break
7
8 print f.closed
a) True
b) False
c) None
d) Error
Answer: a) True
The WITH statement when used with open file guarantees that the file
object is closed when the with block exits.
a) always
b) when an exception occurs
c) when no exception occurs
d) when an exception occurs into except block
2) What is PEP 8?
Pickle module accepts any Python object and converts it into a string
representation and dumps it into a file by using dump function, this process
is called pickling. While the process of retrieving original Python objects
from the stored string representation is called unpickling.
4) How Python is interpreted?
6) What are the tools that help to find bugs or perform static analysis?
PyChecker is a static analysis tool that detects the bugs in Python source
code and warns about the style and complexity of the bug. Pylint is another
tool that verifies whether the module meets the coding standard.
The difference between list and tuple is that list is mutable while tuple is
not. Tuple can be hashed for e.g as a key for dictionaries.
There are mutable and Immutable types of Pythons built in types Mutable
built-in types
• List
• Sets
• Dictionaries
• Strings
• Tuples
• Numbers
In Python, every name introduced has a place where it lives and can be
hooked for. This is known as namespace. It is like a box where a variable
name is mapped to the object placed. Whenever the variable is searched
out, this box will be searched, to get corresponding object.
A mechanism to select a range of items from sequence types like list, tuple,
strings etc. is known as slicing.
In order to convert a number into a string, use the inbuilt function str(). If
you want a octal or hexadecimal representation, use the inbuilt function
oct() or hex().
Xrange returns the xrange object while range returns the list, and uses the
same memory and no matter what the range size is.
26) Mention what are the rules for local and global variables in
Python?
28) Explain how can you make a Python Script executable on Unix?
import random
random.random()
31) Explain how can you access a module written in Python from C?
Module = =PyImport_ImportModule("<modulename>");
The use of the split function in Python is that it breaks a string into shorter
strings using the defined separator. It gives a list of all words present in the
string.
35) Explain what is Flask & its benefits?
Pyramid are build 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.
Like Pyramid, Django can also used for larger applications. It includes an
ORM.
38) Explain what is the common way for the Flask script to work?
40) Is Flask an MVC model and if yes give an example showing MVC
pattern for your application?
Def hello():
app.run(debug = True)
The data in the failed server won't get removed, but there is a provision for
auto-failure, which you can configure for multiple nodes. Fail-over can be
triggered during any kind of socket or Memcached server level errors and
not during normal client errors like adding an existing key, etc.
43) Explain how you can minimize the Memcached server outages in
your Python Development?
• When one instance fails, several of them goes down, this will put
larger load on the database server when lost data is reloaded as
client make a request. To avoid this, if your code has been written to
minimize cache stampedes then it will leave a minimal impact
• Another way is to bring up an instance of Memcached on a new
machine using the lost machines IP address
• Code is another option to minimize server outages as it gives you the
liberty to change the Memcached server list with minimal work
• Setting timeout value is another option that some Memcached clients
implement for Memcached server outage. When your Memcached
server goes down, the client will keep trying to send a request till the
time-out limit is reached
44) Explain what is Dogpile effect? How can you prevent this effect?
Dogpile effect is referred to the event when cache expires, and websites
are hit by the multiple requests made by the client at the same time. This
effect can be prevented by using semaphore lock. In this system when
value expires, first process acquires the lock and starts generating new
value.