Interview Questions
Interview Questions
Python is a general-purpose programming language that has a simple, easy-to-learn syntax that emphasizes
readability and therefore reduces the cost of program maintenance. Moreover, the language is capable of
scripting, is completely open-source, and supports third-party packages encouraging modularity and code
reuse.
Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community
of developers for Rapid Application Development and deployment.
Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to
type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in
a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the
other hand, a weakly-typed language, such as Javascript, will simply output "12" as result.
Python is an interpreted language, executes each statement line by line and thus type-checking is done on the
fly, during execution. Hence, Python is a Dynamically Typed Language.
An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP, and
Ruby are prime examples of Interpreted languages. Programs written in an interpreted language runs directly
from the source code, with no intermediary compilation step.
PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information
to the Python community, or describing a new feature for Python or its processes. PEP 8 is especially important
since it documents the style guidelines for Python Code. Apparently contributing to the Python open-source
community requires you to follow these style guidelines sincerely and strictly.
Every object in Python functions within a scope. A scope is a block of code where an object in Python remains
relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have
a scope defined for them where you could use their objects without any prefix. A few examples of scope created
during code execution in Python are as follows:
A local scope refers to the local objects available in the current function.
A global scope refers to the objects available throughout the code execution since their inception.
A module-level scope refers to the global objects of the current module accessible in the program.
An outermost scope refers to all the built-in names callable in the program. The objects in this scope are
searched last to find the name referenced.
Note: Local scope objects can be synced with global scope objects using keywords such as global.
6. What are lists and tuples? What is the key difference between the two?
Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects
stored in both sequences can have different data types. Lists are represented with square brackets ['sara', 6,
0.19], while tuples are represented with parantheses ('ansh', 5, 0.97).
But what is the real difference between the two? The key difference between the two is that while lists are
mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or
sliced on the go but tuples remain constant and cannot be modified in any manner. You can run the following
example on Python IDLE to confirm the difference:
There are several built-in data types in Python. Although, Python doesn't require data types to be defined
explicitly during variable declarations type errors are likely to occur if the knowledge of data types and their
compatibility with each other are neglected. Python provides type() and isinstance() functions to check the
type of these variables. These data types can be grouped into the following categories-
None Type:
None keyword represents the null values in Python. Boolean equality operation can be performed using these
NoneType objects.
Numeric Types:
There are three distinct numeric types - integers, floating-point numbers, and complex numbers.
Additionally, booleans are a sub-type of integers.
Sequence Types:
According to Python Docs, there are three basic Sequence Types - lists, tuples, and range objects. Sequence
types have the in and not in operators defined for their traversing their elements. These operators share the
same priority as the comparison operations.
Note: The standard library also includes additional types for processing:
1. Binary data such as bytearray bytes memoryview , and
2. Text strings such as str.
Mapping Types:
A mapping object can map hashable values to random objects in Python. Mappings objects are mutable and
there is currently only one standard mapping type, the dictionary.
Set Types:
Currently, Python has two built-in set types - set and frozenset. set type is mutable and supports methods
like add() and remove(). frozenset type is immutable and can't be modified after creation.
Note: set is mutable and thus cannot be used as key for a dictionary. On the other hand, frozenset is immutable
and thus, hashable, and can be used as a dictionary key or as an element of another set.
Modules:
Module is an additional built-in type supported by the Python Interpreter. It supports one special operation,
i.e., attribute access: mymod.myobj, where mymod is a module and myobj references a name defined in m's
symbol table. The module's symbol table resides in a very special attribute of the module __dict__, but direct
assignment to this module is neither possible nor recommended.
Callable Types:
Callable types are the types to which function call can be applied. They can be user-defined functions,
instance methods, generator functions, and some other built-in functions, methods and classes.
Refer to the documentation at docs.python.org for a detailed view of the callable types.
def myEmptyFunc():
# do nothing
pass
myEmptyFunc() # nothing happens
## Without the pass keyword
# File "<stdin>", line 3
# IndentationError: expected an indented block
Python packages and Python modules are two mechanisms that allow for modular programming in Python.
Modularizing has several advantages -
Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand.
This makes development easier and less error-prone.
Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If
they are written in a manner that reduces interdependency, it is less likely that modifications in a module might
impact other parts of the program.
Reusability: Functions defined in a module can be easily reused by other parts of the application.
Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifiers from
other parts of the program.
Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes, or
variables defined and implemented. They can be imported and initialized once using the import statement. If
partial functionality is needed, import the requisite classes or functions using from foo import bar.
Packages allow for hierarchial structuring of the module namespace using dot notation. As, modules help
avoid clashes between global variable names, in a similar manner, packages help avoid clashes between
module names.
Creating a package is easy since it makes use of the system's inherent file structure. So just stuff the modules
into a folder and there you have it, the folder name as the package name. Importing a module or its contents
from this package requires the package name as prefix to the module name joined by a dot.
Note: You can technically import the package as well, but alas, it doesn't import the modules within the package
to the local namespace, thus, it is practically useless.
Global variables are public variables that are defined in the global scope. To use the variable in the global scope
inside a function, we use the global keyword.
Protected attributes are attributes defined with an underscore prefixed to their identifier eg. _sara. They can
still be accessed and modified from outside the class they are defined in but a responsible developer should
refrain from doing so.
Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh. They cannot be
accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.
__init__ is a contructor method in Python and is automatically called to allocate memory when a new
object/instance is created. All classes have a __init__ method associated with them. It helps in distinguishing
methods and attributes of a class from local variables.
# class definition
class Student:
def __init__(self, fname, lname, age, section):
self.firstname = fname
self.lastname = lname
self.age = age
self.section = section
# creating a new object
stu1 = Student("Sara", "Ansh", 22, "A2")
Break The break statement terminates the loop immediately and the control flows to the statement after
the body of the loop.
Continue The continue statement terminates the current iteration of the statement, skips the rest of the code
in the current iteration and the control flows to the next iteration of the loop.
Pass As explained above, the pass keyword in Python is generally used to fill up empty blocks and is
similar to an empty statement represented by a semi-colon in languages such as Java, C++,
Javascript, etc.
pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]
for p in pat:
pass
if (p == 0):
current = p
break
elif (p % 2 == 0):
continue
print(p) # output => 1 3 1 3 1
print(current) # output => 0
17. Explain how can you make a Python Script executable on Unix?
Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous.
It is a thin wrapper around C language arrays and consumes far less memory than lists.
Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has
the disadvantage of consuming large memory.
import array
a = array.array('i', [1, 2, 3])
for i in a:
print(i, end=' ') #OUTPUT: 1 2 3
a = array.array('i', [1, 2, 'string']) #OUTPUT: TypeError: an integer is required (got type str)
a = [1, 2, 'string']
for i in a:
print(i, end=' ') #OUTPUT: 1 2 string
Memory management in Python is handled by the Python Memory Manager. The memory allocated by the
manager is in form of a private heap space dedicated to Python. All Python objects are stored in this heap and
being private, it is inaccessible to the programmer. Though, python does provide some core API functions to
work upon the private heap space.
Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.
20. What are Python namespaces? Why are they used?
A namespace in Python ensures that object names in a program are unique and can be used without any conflict.
Python implements these namespaces as dictionaries with 'name as key' mapped to a corresponding 'object as
value'. This allows for multiple namespaces to use the same name and map it to a separate object. A few
examples of namespaces are as follows:
Local Namespace includes local names inside a function. the namespace is temporarily created for a function
call and gets cleared when the function returns.
Global Namespace includes names from various imported packages/ modules that are being used in the
current project. This namespace is created when the package is imported in the script and lasts until the
execution of the script.
Built-in Namespace includes built-in functions of core Python and built-in names for various types of
exceptions.
The lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object
ends, the lifecycle of that namespace comes to an end. Hence, it isn't possible to access inner namespace objects
from an outer namespace.
Sometimes objects within the same scope have the same name but function differently. In such cases, scope
resolution comes into play in Python automatically. A few examples of such behavior are:
Python modules namely 'math' and 'cmath' have a lot of functions that are common to both of them
- log10(), acos(), exp() etc. To resolve this ambiguity, it is necessary to prefix them with their respective
module, like math.exp() and cmath.exp().
Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call.
However, the function call didn't change the value of the temp globally. Here, we can observe that Python draws
a clear line between global and local variables, treating their namespaces as separate identities.
This behavior can be overridden using the global keyword inside the function, as shown in the following
example:
Decorators in Python are essentially functions that add functionality to an existing function in Python without
changing the structure of the function itself. They are represented the @decorator_name in Python and are
called in a bottom-up fashion. For example:
The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they
can even accept arguments for functions and can further modify those arguments before passing it to the
function itself. The inner nested function, i.e. 'wrapper' function, plays a significant role here. It is
implemented to enforce encapsulation and thus, keep itself hidden from the global scope.
Python comprehensions, like decorators, are syntactic sugar constructs that help build altered and filtered
lists, dictionaries, or sets from a given list, dictionary, or set. Using comprehensions saves a lot of time and code
that might be considerably more verbose (containing more lines of code). Let's check out some examples,
where comprehensions can be truly beneficial:
Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one.
a = [1, 2, 3]
b = [7, 8, 9]
[(x + y) for (x,y) in zip(a,b)] # parallel iterators
# output => [8, 10, 12]
[(x,y) for x in a for y in b] # nested iterators
# output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)]
A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work
upon its inner elements.
my_list = [[10,20,30],[40,50,60],[70,80,90]]
flattened = [x for temp in my_list for x in temp]
# output => [10, 20, 30, 40, 50, 60, 70, 80, 90]
Note: List comprehensions have the same effect as the map method in other languages. They follow the
mathematical set builder notation rather than map and filter functions in Python.
Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a
single expression. It is generally used in situations requiring an anonymous function for a short time period.
Lambda functions can be used in either of the two ways:
mul = lambda a, b : a * b
print(mul(2, 5)) # output => 10
def myWrapper(n):
return lambda a : a * n
mulFive = myWrapper(5)
print(mulFive(2)) # output => 10
In Python, the assignment statement (= operator) does not copy objects. Instead, it creates a binding between
the existing object and the target variable name. To create copies of an object in Python, we need to use
the copy module. Moreover, there are two ways of creating copies for the given object using the copy module
-
Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of the values in the
original object. If either of the values is a reference to other objects, just the reference addresses for the same
are copied.
Deep Copy copies all values recursively from source to target object, i.e. it even duplicates the objects
referenced by the source object.
So how does that make a difference? It sure does, because unlike range(), xrange() doesn't generate a static
list, it creates the value on the go. This technique is commonly used with an object-type generator and has
been termed as "yielding".
Yielding is crucial in applications where memory is a constraint. Creating a static list as in range() can lead to
a Memory Error in such conditions, while, xrange() can handle it optimally by using just enough memory for
the generator (significantly less in comparison).
Note: xrange has been deprecated as of Python 3.x. Now range does exactly the same as what xrange used to
do in Python 2.x, since it was way better to use xrange() than the original range() function in Python 2.x.
Python library offers a feature - serialization out of the box. Serializing an object refers to transforming it into
a format that can be stored, so as to be able to deserialize it, later on, to obtain the original object. Here,
the pickle module comes into play.
Pickling:
Pickling is the name of the serialization process in Python. Any object in Python can be serialized into a byte
stream and dumped as a file in the memory. The process of pickling is compact but pickle objects can be
compressed further. Moreover, pickle keeps track of the objects it has serialized and the serialization is
portable across versions.
The function used for the above process is pickle.dump().
Unpickling:
Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in
the file and loads the object to memory.
The function used for the above process is pickle.load().
Note: Python has another, more primitive, serialization module called marshall, which exists primarily
to support .pyc files in Python and differs significantly from the pickle.
28. What are generators in Python?
Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators,
in general, are used to create iterators with a different approach. They employ the use of yield keyword rather
than return to return a generator object.
Let's try and build a generator for fibonacci numbers -
PYTHONPATH is an environment variable which you can set to add additional directories where Python will
look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to
install in the global default location.
For Modules/Library objects, it returns a list of all attributes, contained in that module.
For Class Objects, it returns a list of all valid attributes and base attributes.
With no arguments passed, it returns a list of attributes in the current scope.
.py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We
get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It
is only created for the files that you import.
Before executing a python program python interpreter checks for the compiled files. If the file is present, the
virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then python
virtual machine executes it.
Having .pyc file saves you the compilation time.
Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the
implementation. Python is a bytecode(set of interpreter readable instructions) interpreted generally.
Source code is a file with .py extension.
Python compiles the source code to a set of instructions for a virtual machine. The Python interpreter is an
implementation of that virtual machine. This intermediate format is called “bytecode”.
.py source code is first compiled to give .pyc which is bytecode. This bytecode can be then interpreted by the
official CPython or JIT(Just in Time compiler) compiled by PyPy.
Pass by value: Copy of the actual object is passed. Changing the value of the copy of the object will not change
the value of the original object.
Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change
the value of the original object.
In Python, arguments are passed by reference, i.e., reference to the actual object is passed.
def appendNumber(arr):
arr.append(4)
arr = [1, 2, 3]
print(arr) #Output: => [1, 2, 3]
appendNumber(arr)
print(arr) #Output: => [1, 2, 3, 4]
An iterator is an object.
It remembers its state i.e., where it is during iteration (see code below to see how)
__iter__() method initializes an iterator.
It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching
the end of iterable object __next__() must return StopIteration exception.
It is also self-iterable.
Iterators are objects with which we can iterate over iterable objects like lists, strings, etc.
class ArrayList:
def __init__(self, number_list):
self.numbers = number_list
def __iter__(self):
self.pos = 0
return self
def __next__(self):
if(self.pos < len(self.numbers)):
self.pos += 1
return self.numbers[self.pos - 1]
else:
raise StopIteration
array_obj = ArrayList([1, 2, 3])
it = iter(array_obj)
print(next(it)) #output: 2
print(next(it)) #output: 3
print(next(it))
#Throws Exception
#Traceback (most recent call last):
#...
#StopIteration
import os
os.remove("ChangedFile.csv")
print("File Removed!")
You can use split() function to split a string based on a delimiter to a list of strings.
You can use join() function to join a list of strings based on a delimiter to give a single string.
*args
*args is a special syntax used in the function definition to pass variable-length arguments.
“*” means variable length and “args” is the name used by convention. You can use any other.
def multiply(a, b, *argv):
mul = a * b
for num in argv:
mul *= num
return mul
print(multiply(1, 2, 3, 4, 5)) #output: 120
**kwargs
**kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments.
Here, also, “kwargs” is used just by convention. You can use any other name.
Keyworded argument means a variable that has a name when passed to a function.
It is actually a dictionary of the variable names and its value.
def tellArguments(**kwargs):
for key, value in kwargs.items():
print(key + ": " + value)
tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3")
#output:
# arg1: argument 1
# arg2: argument 2
# arg3: argument 3
38. What are negative indexes and why are they used?
Negative indexes are the indexes from the end of the list or tuple or string.
Arr[-1] means the last element of array Arr[]
arr = [1, 2, 3, 4, 5, 6]
#get the last element
print(arr[-1]) #output 6
#get the second last element
print(arr[-2]) #output 5
To create a class in python, we use the keyword “class” as shown in the example below:
class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name
To instantiate or create an object from the class created above, we do the following:
emp_1=InterviewbitEmployee("Mr. Employee")
To access the name attribute, we just call the attribute using the dot operator as shown below:
print(emp_1.emp_name)
# Prints Mr. Employee
To create methods inside the class, we include the methods under the scope of the class as shown below:
class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name
def introduce(self):
print("Hello I am " + self.emp_name)
The self parameter in the init and introduce functions represent the reference to the current class instance
which is used for accessing attributes and methods of that class. The self parameter has to be the first parameter
of any method defined inside the class. The method of the class InterviewbitEmployee can be accessed as shown
below:
emp_1.introduce()
class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name
def introduce(self):
print("Hello I am " + self.emp_name)
Inheritance gives the power to a class to access all attributes and methods of another class. It aids in code
reusability and helps the developer to maintain applications without redundant code. The class inheriting from
another class is a child class or also called a derived class. The class from which a child class derives the
members are called parent class or superclass.
# Parent class
class ParentClass:
def par_func(self):
print("I am parent class function")
# Child class
class ChildClass(ParentClass):
def child_func(self):
print("I am child class function")
# Driver code
obj1 = ChildClass()
obj1.par_func()
obj1.child_func()
Multi-level Inheritance: The members of the parent class, A, are inherited by child class which is then
inherited by another child class, B. The features of the base class and the derived class are further inherited
into the new derived class, C. Here, A is the grandfather class of class C.
# Parent class
class A:
def __init__(self, a_name):
self.a_name = a_name
# Intermediate class
class B(A):
def __init__(self, b_name, a_name):
self.b_name = b_name
# invoke constructor of class A
A.__init__(self, a_name)
# Child class
class C(B):
def __init__(self,c_name, b_name, a_name):
self.c_name = c_name
# invoke constructor of class B
B.__init__(self, b_name, a_name)
def display_names(self):
print("A name : ", self.a_name)
print("B name : ", self.b_name)
print("C name : ", self.c_name)
# Driver code
obj1 = C('child', 'intermediate', 'parent')
print(obj1.a_name)
obj1.display_names()
Multiple Inheritance: This is achieved when one child class derives members from more than one parent
class. All features of parent classes are inherited in the child class.
# Parent class1
class Parent1:
def parent1_func(self):
print("Hi I am first Parent")
# Parent class2
class Parent2:
def parent2_func(self):
print("Hi I am second Parent")
# Child class
class Child(Parent1, Parent2):
def child_func(self):
self.parent1_func()
self.parent2_func()
# Driver's code
obj1 = Child()
obj1.child_func()
Hierarchical Inheritance: When a parent class is derived by more than one child class, it is called hierarchical
inheritance.
# Base class
class A:
def a_func(self):
print("I am from the parent class.")
# Driver's code
obj1 = B()
obj2 = C()
obj1.a_func()
obj1.b_func() #child 1 method
obj2.a_func()
obj2.c_func() #child 2 method
Following are the ways using which you can access parent class members within a child class:
By using Parent class name: You can use the name of the parent class to access the attributes as shown in the
example below:
class Parent(object):
# Constructor
def __init__(self, name):
self.name = name
class Child(Parent):
# Constructor
def __init__(self, name, age):
Parent.name = name
self.age = age
def display(self):
print(Parent.name, self.age)
# Driver Code
obj = Child("Interviewbit", 6)
obj.display()
By using super(): The parent class members can be accessed in child class using the super keyword.
class Parent(object):
# Constructor
def __init__(self, name):
self.name = name
class Child(Parent):
# Constructor
def __init__(self, name, age):
'''
In Python 3.x, we can also use super().__init__(name)
'''
super(Child, self).__init__(name)
self.age = age
def display(self):
# Note that Parent.name cant be used
# here since super() is used in the constructor
print(self.name, self.age)
# Driver Code
obj = Child("Interviewbit", 6)
obj.display()
Python does not make use of access specifiers specifically like private, public, protected, etc. However, it does
not derive this from any variables. It has the concept of imitating the behaviour of variables by making use of a
single (protected) or double underscore (private) as prefixed to the variable names. By default, the variables
without prefixed underscores are public.
Example:
# protected members
_emp_name = None
_age = None
# private members
__branch = None
# constructor
def __init__(self, emp_name, age, branch):
self._emp_name = emp_name
self._age = age
self.__branch = branch
#public member
def display():
print(self._emp_name +" "+self._age+" "+self.__branch)
Yes, it is possible if the base class is instantiated by other child classes or if the base class is a static method.
class EmptyClassDemo:
pass
obj=EmptyClassDemo()
obj.name="Interviewbit"
print("Name created= ",obj.name)
Output:
Name created = Interviewbit
The new modifier is used to instruct the compiler to use the new implementation and not the base class
function. The Override modifier is useful for overriding a base class function inside the child class.
Finalize method is used for freeing up the unmanaged resources and clean up before the garbage collection
method is invoked. This helps in performing memory management tasks.
The init method works similarly to the constructors in Java. The method is run as soon as an object is
instantiated. It is useful for initializing any attributes or default behaviour of the object at the time of
instantiation.
For example:
class InterviewbitEmployee:
# introduce method
def introduce(self):
print('Hello, I am ', self.emp_name)
emp = InterviewbitEmployee('Mr Employee') # __init__ method is called here and initializes the object name
with "Mr Employee"
emp.introduce()
This is done by using a method called issubclass() provided by python. The method tells us if any class is a
child of another class by returning true or false accordingly.
For example:
class Parent(object):
pass
class Child(Parent):
pass
# Driver Code
print(issubclass(Child, Parent)) #True
print(issubclass(Parent, Child)) #False
obj1 = Child()
obj2 = Parent()
print(isinstance(obj2, Child)) #False
print(isinstance(obj2, Parent)) #True
Pandas is an open-source, python-based library used in data manipulation applications requiring high
performance. The name is derived from “Panel Data” having multidimensional data. This was developed in
2008 by Wes McKinney and was developed for data analysis.
Pandas are useful in performing 5 major steps of data analysis - Load the data, clean/manipulate it, prepare it,
model it, and analyze the data.
A dataframe is a 2D mutable and tabular structure for representing data labelled with axes - rows and columns.
The syntax for creating dataframe:
import pandas as pd
dataframe = pd.DataFrame( data, index, columns, dtype)
where:
data - Represents various forms like series, map, ndarray, lists, dict etc.
index - Optional argument that represents an index to row labels.
columns - Optional argument for column labels.
Dtype - the data type of each column. Again optional.
df1.append(df2)
concat() method: This is used to stack dataframes vertically. This is best used when the dataframes have the
same columns and similar fields. Syntax:
pd.concat([df1, df2])
join() method: This is used for extracting data from various dataframes having one or more common columns.
df1.join(df2)
52. Can you create a series from the dictionary object in pandas?
One dimensional array capable of storing different data types is called a series. We can create pandas series
from a dictionary object as shown below:
import pandas as pd
dict_info = {'key1' : 2.0, 'key2' : 3.1, 'key3' : 2.2}
series_obj = pd.Series(dict_info)
print (series_obj)
Output:
x 2.0
y 3.1
z 2.2
dtype: float64
If an index is not specified in the input method, then the keys of the dictionaries are sorted in ascending order
for constructing the index. In case the index is passed, then values of the index label will be extracted from the
dictionary.
53. How will you identify and deal with missing values in a dataframe?
We can identify if a dataframe has missing values by using the isnull() and isna() methods.
missing_data_count=df.isnull().sum()
We can handle missing values by either replacing the values in the column with 0 as follows:
df[‘column_name’].fillna(0)
df[‘column_name’] = df[‘column_name’].fillna((df[‘column_name’].mean()))
Reindexing is the process of conforming a dataframe to a new index with optional filling logic. If the values are
missing in the previous index, then NaN/NA is placed in the location. A new object is returned unless a new
index is produced that is equivalent to the current one. The copy value is set to False. This is also used for
changing the index of rows and columns in the dataframe.
import pandas as pd
data_info = {'first' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'second' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(data_info)
#To add new column third
df['third']=pd.Series([10,20,30],index=['a','b','c'])
print (df)
#To add new column fourth
df['fourth']=df['first']+info['third']
print (df)
56. How will you delete indices, rows and columns from a dataframe?
To delete an Index:
Column 1
Names
John 1
Jack 2
Judy 3
Jim 4
df.index.name = None
# Or run the below:
# del df.index.name
print(df)
Column 1
John 1
Jack 2
Judy 3
Jim 4
This can be achieved by using the ~ (not/negation symbol) and isin() method as shown below.
import pandas as pd
df1 = pd.Series([2, 4, 8, 10, 12])
df2 = pd.Series([8, 12, 10, 15, 16])
df1=df1[~df1.isin(df2)]
print(df1)
"""
Output:
0 2
1 4
dtype: int64
"""
58. How will you get the items that are not common to both the given series A and B?
We can achieve this by first performing the union of both series, then taking the intersection of both series.
Then we follow the approach of getting items of union that are not there in the list of the intersection.
import pandas as pd
import numpy as np
df1 = pd.Series([2, 4, 5, 8, 10])
df2 = pd.Series([8, 10, 13, 15, 17])
p_union = pd.Series(np.union1d(df1, df2)) # union of series
p_intersect = pd.Series(np.intersect1d(df1, df2)) # intersection of series
unique_elements = p_union[~p_union.isin(p_intersect)]
print(unique_elements)
"""
Output:
0 2
1 4
2 5
5 13
6 15
7 17
dtype: int64
"""
59. While importing data from different sources, can the pandas library recognize dates?
Yes, they can, but with some bit of help. We need to add the parse_dates argument while we are reading data
from the sources. Consider an example where we read data from a CSV file, we may encounter different date-
time formats that are not readable by the pandas library. In this case, pandas provide flexibility to build our
custom date parser with the help of lambda functions as shown below:
import pandas as pd
from datetime import datetime
dateparser = lambda date_val: datetime.strptime(date_val, '%Y-%m-%d %H:%M:%S')
df = pd.read_csv("some_file.csv", parse_dates=['datetime_column'], date_parser=dateparser)
NumPy is one of the most popular, easy-to-use, versatile, open-source, python-based, general-purpose package
that is used for processing arrays. NumPy is short for NUMerical PYthon. This is very famous for its highly
optimized tools that result in high performance and powerful N-Dimensional array processing feature that is
designed explicitly to work on complex arrays. Due to its popularity and powerful performance and its
flexibility to perform various operations like trigonometric operations, algebraic and statistical computations,
it is most commonly used in performing scientific computations and various broadcasting functions. The
following image shows the applications of NumPy:
1D array creation:
import numpy as np
one_dimensional_list = [1,2,4]
one_dimensional_arr = np.array(one_dimensional_list)
print("1D array is : ",one_dimensional_arr)
2D array creation:
import numpy as np
two_dimensional_list=[[1,2,3],[4,5,6]]
two_dimensional_arr = np.array(two_dimensional_list)
print("2D array is : ",two_dimensional_arr)
3D array creation:
import numpy as np
three_dimensional_list=[[[1,2,3],[4,5,6],[7,8,9]]]
three_dimensional_arr = np.array(three_dimensional_list)
print("3D array is : ",three_dimensional_arr)
ND array creation: This can be achieved by giving the ndmin attribute. The below example demonstrates the
creation of a 6D array:
import numpy as np
ndArray = np.array([1, 2, 3, 4], ndmin=6)
print(ndArray)
print('Dimensions of array:', ndArray.ndim)
63. You are given a numpy array and a new column as inputs. How will you delete the second column
and replace the column with a new column value?
Example:
Given array:
[[35 53 63]
[72 12 22]
[43 84 56]]
Solution:
import numpy as np
#inputs
inputArray = np.array([[35,53,63],[72,12,22],[43,84,56]])
new_col = np.array([[20,30,40]])
# delete 2nd column
arr = np.delete(inputArray , 1, axis = 1)
#insert new_col to array
arr = np.insert(arr , 1, new_col, axis = 1)
print (arr)
64. How will you efficiently load data from a text file?
We can use the method numpy.loadtxt() which can automatically read the file’s header and footer lines and the
comments if any.
This method is highly efficient and even if this method feels less efficient, then the data should be represented
in a more efficient format such as CSV etc. Various alternatives can be considered depending on the version of
NumPy used.
Text files: These files are generally very slow, huge but portable and are human-readable.
Raw binary: This file does not have any metadata and is not portable. But they are fast.
Pickle: These are borderline slow and portable but depends on the NumPy versions.
HDF5: This is known as the High-Powered Kitchen Sink format which supports both PyTables and h5py format.
.npy: This is NumPy's native binary data format which is extremely simple, efficient and portable.
65. How will you read CSV data into an array in NumPy?
This can be achieved by using the genfromtxt() method by setting the delimiter as a comma.
66. How will you sort the array based on the Nth column?
Let us try to sort the rows by the 2nd column so that we get:
[[6, 1, 4],
[8, 3, 2],
[3, 6, 5]]
import numpy as np
arr = np.array([[8, 3, 2],
[3, 6, 5],
[6, 1, 4]])
#sort the array using np.sort
arr = np.sort(arr.view('i8,i8,i8'),
order=['f1'],
axis=0).view(np.int)
We can also perform sorting and that too inplace sorting by doing:
arr.view('i8,i8,i8').sort(order=['f1'], axis=0)
67. How will you find the nearest value in a given numpy array?
import numpy as np
def find_nearest_value(arr, value):
arr = np.asarray(arr)
idx = (np.abs(arr - value)).argmin()
return arr[idx]
#Driver code
arr = np.array([ 0.21169, 0.61391, 0.6341, 0.0131, 0.16541, 0.5645, 0.5742])
value = 0.52
print(find_nearest_value(arr, value)) # Prints 0.5645
68. How will you reverse the numpy array using one line of code?
reversed_array = arr[::-1]
where arr = original given array, reverse_array is the resultant after reversing all elements in the input.
69. How will you find the shape of any given NumPy array?
We can use the shape attribute of the numpy array to find the shape. It returns the shape of the array in terms
of row count and column count of the array.
import numpy as np
arr_two_dim = np.array([("x1","x2", "x3","x4"),
("x5","x6", "x7","x8" )])
arr_one_dim = np.array([3,2,4,5,6])
# find and print shape
print("2-D Array Shape: ", arr_two_dim.shape)
print("1-D Array Shape: ", arr_one_dim.shape)
"""
Output:
2-D Array Shape: (2, 4)
1-D Array Shape: (5,)
"""
The module is a single python file. A module can import other modules (other python files) as objects. Whereas,
a package is the folder/directory where different sub-packages and the modules reside.
A python module is created by saving a file with the extension of .py. This file will have classes and functions
that are reusable in the code as well as across modules.
Create a directory and give a valid name that represents its operation.
Place modules of one kind in this directory.
Create __init__.py file in this directory. This lets python know the directory we created is a package. The
contents of this package can be imported across different modules in other packages to reuse the functionality.
71. What are some of the most commonly used built-in modules in Python?
Python modules are the files having python code which can be functions, variables or classes. These go by .py
extension. The most commonly available built-in modules are:
os
math
sys
random
re
datetime
JSON
Lambda functions are generally inline, anonymous functions represented by a single expression. They are used
for creating function objects during runtime. They can accept any number of parameters. They are usually used
where functions are required only for a short period. They can be used as:
Python provides a module called random using which we can generate random numbers.
We have to import a random module and call the random() method as shown below:
o The random() method generates float values lying between 0 and 1 randomly.
import random
print(random.random())
To generate customised random numbers between specified ranges, we can use the randrange() method
Syntax: randrange(beginning, end, step)
For example:
import random
print(random.randrange(5,100,2))
74. Can you easily check if all characters in the given string is alphanumeric?
This can be easily done by making use of the isalnum() method that returns true in case the string has only
alphanumeric characters.
For Example -
Another way is to use match() method from the re (regex) module as shown:
import re
print(bool(re.match('[A-Za-z0-9]+$','abdc1321'))) # Output: True
print(bool(re.match('[A-Za-z0-9]+$','xyz@123$'))) # Output: False
Pickling is the conversion of python objects to binary form. Whereas, unpickling is the conversion of binary
form data to python objects. The pickled objects are used for storing in disks or external memory locations.
Unpickled objects are used for getting the data back as python objects upon which processing can be done in
python.
Python provides a pickle module for achieving this. Pickling uses the pickle.dump() method to dump python
objects into disks. Unpickling uses the pickle.load() method to get back the data as python objects.
GIL stands for Global Interpreter Lock. This is a mutex used for limiting access to python objects and aids in
effective thread synchronization by avoiding deadlocks. GIL helps in achieving multitasking (and not parallel
computing). The following diagram represents how GIL works.
Based on the above diagram, there are three threads. First Thread acquires the GIL first and starts the I/O
execution. When the I/O operations are done, thread 1 releases the acquired GIL which is then taken up by the
second thread. The process repeats and the GIL are used by different threads alternatively until the threads
have completed their execution. The threads not having the GIL lock goes into the waiting state and resumes
execution only when it acquires the lock.
It is an environment variable used for incorporating additional directories during the import of a module or a
package. PYTHONPATH is used for checking if the imported packages or modules are available in the existing
directories. Not just that, the interpreter uses this environment variable to identify which module needs to be
loaded.
PIP stands for Python Installer Package. As the name indicates, it is used for installing different python modules.
It is a command-line tool providing a seamless interface for installing different python modules. It searches
over the internet for the package and installs them into the working directory without the need for any
interaction with the user. The syntax for this is:
79. Are there any tools for identifying bugs and performing static analysis in python?
Yes, there are tools like PyChecker and Pylint which are used as static analysis and linting tools respectively.
PyChecker helps find bugs in python source code files and raises alerts for code issues and their complexity.
Pylint checks for the module’s coding standards and supports different plugins to enable custom features to
meet this requirement.
Shallow copy does the task of creating new objects storing references of original elements. This does not
undergo recursion to create copies of nested objects. It just copies the reference details of nested objects.
Deep copy creates an independent and new copy of an object and even copies all the nested objects of the
original element recursively.
In the world of programming languages, the main is considered as an entry point of execution for a program.
But in python, it is known that the interpreter serially interprets the file line-by-line. This means that python
does not provide main() function explicitly. But this doesn't mean that we cannot simulate the execution of
main. This can be done by defining user-defined main() function and by using the __name__ property of python
file. This __name__ variable is a special built-in variable that points to the name of the current module. This can
be done as shown below:
def main():
print("Hi Interviewbit!")
if __name__=="__main__":
main()
def function_name(*arg_list)
For example:
def func(*var):
for i in var:
print(i)
func(1)
func(20,1,6)
83. WAP (Write a program) which takes a sequence of numbers and check if all numbers are unique.
You can do this by converting the list to set by using set() method and comparing the length of this set with the
length of the original list. If found equal, return True.
def check_distinct(data_list):
if len(data_list) == len(set(data_list)):
return True
else:
return False;
print(check_distinct([1,6,5,8])) #Prints True
print(check_distinct([2,2,5,5,7,8])) #Prints False
84. Write a program for counting the number of every character of a given text file.
import collections
import pprint
with open("sample_file.txt", 'r') as data:
count_data = collections.Counter(data.read().upper())
count_value = pprint.pformat(count_data)
print(count_value)
85. Write a program to check and return the pairs of a given array A whose sum value is equal to a target
value N.
This can be done easily by using the phenomenon of hashing. We can use a hash map to check for the current
value of the array, x. If the map has the value of (N-x), then there is our pair.
# driver code
arr = [1, 2, 40, 3, 9, 4]
N=3
print_pairs(arr, N)
86. Write a Program to add two integers >0 without using the plus operator.
87. Write a Program to solve the given equation assuming that a,b,c,m,n,o are constants:
ax + by = c
mx + ny = o
a, b, c, m, n, o = 5, 9, 4, 7, 9, 4
temp = a*n - b*m
if n != 0:
x = (c*n - b*o) / temp
y = (a*o - m*c) / temp
print(str(x), str(y))
88. Write a Program to match a string that has the letter ‘a’ followed by 4 to 8 'b’s.
We can use the re module of python to perform regex pattern comparison here.
import re
def match_text(txt_data):
pattern = 'ab{4,8}'
if re.search(pattern, txt_data): #search for pattern in txt_data
return 'Match found'
else:
return('Match not found')
print(match_text("abc")) #prints Match not found
print(match_text("aabbbbbc")) #prints Match found
89. Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy format.
We can again use the re module to convert the date string as shown below:
import re
def transform_date_format(date):
return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\3-\\2-\\1', date)
date_input = "2021-08-01"
print(transform_date_format(date_input))
90. Write a Program to combine two different dictionaries. While combining, if you find the same keys,
you can add the values of these same keys. Output the new dictionary
91. How will you access the dataset of a publicly shared spreadsheet in CSV format stored in Google
Drive?
We can use the StringIO module from the io module to read from the Google Drive link and then we can use the
pandas library using the obtained data source.
Conclusion:
In this article, we have seen commonly asked interview questions for a python developer. These questions
along with regular problem practice sessions will help you crack any python based interviews. Over the years,
python has gained a lot of popularity amongst the developer’s community due to its simplicity and ability to
support powerful computations. Due to this, the demand for good python developers is ever-growing.
Nevertheless, to mention, the perks of being a python developer are really good. Along with theoretical
knowledge in python, there is an emphasis on the ability to write good quality code as well. So, keep learning
and keep practicing problems and without a doubt, you can crack any interviews.
Python MCQ
"Hello World"
"World Hello"
"dlroW olleH"
"olleH dlroW"
class B(A):
def __init__(self, a):
X.__init__(self, a)
def mul_three(self):
self.num *= 3
obj = B(4)
print(obj.num)
obj.mul_two()
print(obj.num)
obj.mul_three()
print(obj.num)
4 8 24
4 4 64
4 8 64
None of the above
def getHumanName(self):
return self.human_name
def isEmployee(self):
return False
class IBEmployee(Human):
def __init__(self, name, emp_id):
super(IBEmployee, self).__init__(name)
self.emp_id = emp_id
def isEmployee(self):
return True
def get_emp_id(self):
return self.emp_id
# Driver code
employee = IBEmployee("Mr Employee", "IB007")
print(employee.getHumanName(), employee.isEmployee(), employee.get_emp_id()
(None, True, ‘IB007’)
(‘Mr Employee’, True, ‘IB007’)
(“”, False, ‘IB007’)
Runtime error
13. Which among the below options will correct the below error obtained while reading “sample_file.csv” in
pandas?
Traceback (most recent call last): File "<input>", line 10, in<module> UnicodeEncodeError:
'ascii' codec can't encode character.
pd.read_csv(“sample_file.csv”, encoding=‘utf-8’)
pd.read_csv(“sample_file.csv”, compression=‘gzip’)
pd.read_csv(“sample_file.csv”, dialect=‘comma’)
None of the above
14.Which among the following options helps us to check whether a pandas dataframe is empty?
df.emptyframe
df.blank
df.isempty
df.empty
15.How will you find the location of numbers which are multiples of 5 in a series?
import pandas as pd
import numpy as np
series_data = pd.Series(np.random.randint(1, 20, 7))
#insert code here
np.search(series_data % 5)
np.find(series_data % 5 ==0)
np.argwhere(series_data % 5==0)
np.locate(series_data % 5)
first_name = "XYZ"
person = Person(first_name, "ABC")
first_name = "LMN"
person.last_name = "PQR"
print(person.first_name, person.last_name)
XYZ ABC
XYZ PQR
LMN ABC
LMN PQR
17.Which among the below options picks out negative numbers from the given list.
[num for num<0 in list]
[num<0 in list]
[num for num in list if num<0]
[num in list for num<0]
def display_values(self):
print(self.__num1, self.num2)
class Y(X):
def __init__(self):
super().__init__()
self.__num1 = 1
self.num2 = 6
obj = Y()
obj.display_values()
56
12
52
16
A list of frequently asked Python interview questions with answers for freshers and experienced are given
below.
1) What is Python?
39.5M
696
o Software development.
o Mathematics.
o System scripting.
2) Why Python?
o Python is compatible with different platforms like Windows, Mac, Linux, Raspberry Pi, etc.
o Python allows a developer to write programs with fewer lines than some other programming
languages.
o Python runs on an interpreter system, means that the code can be executed as soon as it is written. It
helps to provide a prototype very quickly.
o The Python interpreter and the extensive standard library are available in source or binary form
without charge for all major platforms, and can be freely distributed.
Python is used in various software domains some application areas are given below.
o Games
o Language development
o Operating systems
Python's standard library supports for E-mail processing, FTP, IMAP, and other Internet protocols.
Python's SciPy and NumPy helps in scientific and computational application development.
Interpreted: Python is an interpreted language. It does not require prior compilation of code and executes
instructions directly.
o It is Free and open source
Free and open source: It is an open-source project which is publicly available to reuse. It can be downloaded
free of cost.
o It is Extensible
o Object-oriented
Object-oriented: Python allows to implement the Object-Oriented concepts to build application solution.
Built-in data structure: Tuple, List, and Dictionary are useful integrated data structures provided by the
language.
o Readability
o High-Level Language
o Cross-platform
Portable: Python programs can run on cross platforms without affecting its performance.
5) What is PEP 8?
PEP 8 stands for Python Enhancement Proposal, it can be defined as a document that helps us to provide the
guidelines on how to write the Python code. It is basically a set of rules that specify how to format Python code
for maximum readability. It was written by Guido van Rossum, Barry Warsaw and Nick Coghlan in 2001.
Literals can be defined as a data which is given in a variable or constant. Python supports the following literals:
String Literals
String literals are formed by enclosing text in the single or double quotes. For example, string literals are string
values.
Example:
1. # in single quotes
2. single = 'JavaTpoint'
3. # in double quotes
4. double = "JavaTpoint"
5. # multi-line String
6. multi = '''''Java
7. T
8. point'''
9.
10. print(single)
11. print(double)
12. print(multi)
Output:
JavaTpoint
JavaTpoint
Java
T
point
Numeric Literals
Python supports three types of numeric literals integer, float and complex.
Example:
1. # Integer literal
2. a = 10
3. #Float Literal
4. b = 12.3
5. #Complex Literal
6. x = 3.14j
7. print(a)
8. print(b)
9. print(x)
Output:
10
12.3
3.14j
Boolean Literals
Boolean literals are used to denote Boolean values. It contains either True or False.
Example:
1. p = (1 == True)
2. q = (1 == False)
3. r = True + 3
4. s = False + 7
5.
6. print("p is", p)
7. print("q is", q)
8. print("r:", r)
9. print("s:", s)
Output:
p is True
q is False
r: 4
s: 7
Special literals
Python contains one special literal, that is, 'None'. This special literal is used for defining a null variable. If
'None' is compared with anything else other than a 'None', it will return false.
Example:
1. word = None
2. print(word)
Output:
None
A function is a section of the program or a block of code that is written once and can be executed whenever
required in the program. A function is a block of self-contained statements which has a valid name, parameters
list, and body. Functions make programming more functional and modular to perform modular tasks. Python
provides several built-in functions to complete tasks and also allows a user to create new functions as well.
o Built-In Functions: copy(), len(), count() are the some built-in functions.
o User-defined Functions: Functions which are defined by a user known as user-defined functions.
o Anonymous functions: These functions are also known as lambda functions because they are not
declared with the standard def keyword.
Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an
iterable, convert into iterator and aggregates the elements based on iterables passed. It returns an iterator of
tuples.
Signature
Parameters
iterator1, iterator2, iterator3: These are iterator objects that are joined together.
Return
Note: If the given lists are of different lengths, zip stops generating tuples when the first list ends. It means
two lists are having 3, and 5 lengths will create a 3-tuple.
o Pass by references
o Pass by value
By default, all the parameters (arguments) are passed "by reference" to the functions. Thus, if you change the
value of the parameter within a function, the change is reflected in the calling function as well. It indicates the
original variable. For example, if a variable is declared as a = 10, and passed to a function where it's value is
modified to a = 20. Both the variables denote to the same value.
The pass by value is that whenever we pass the arguments to the function only values pass to the function, no
reference passes to the function. It makes it immutable that means not changeable. Both variables hold the
different values, and original value persists even after modifying in the function.
Python has a default argument concept which helps to call a method using an arbitrary number of arguments.
Example:
1. class student:
2. def __init__(self, name):
3. self.name = name
4. def __init__(self, name, email):
5. self.name = name
6. self.email = email
7.
8. # This line will generate an error
9. #st = student("rahul")
10.
11. # This line will call the second constructor
12. st = student("rahul", "[email protected]")
13. print("Name: ", st.name)
14. print("Email id: ", st.email)
Output:
Name: rahul
Email id: [email protected]
11) What is the difference between remove() function and del statement?
The user can use the remove() function to delete a specific object in the list.
Example:
1. list_1 = [ 3, 5, 7, 3, 9, 3 ]
2. print(list_1)
3. list_1.remove(3)
4. print("After removal: ", list_1)
Output:
[3, 5, 7, 3, 9, 3]
After removal: [5, 7, 3, 9, 3]
If you want to delete an object at a specific location (index) in the list, you can either use del or pop.
Example:
1. list_1 = [ 3, 5, 7, 3, 9, 3 ]
2. print(list_1)
3. del list_1[2]
4. print("After deleting: ", list_1)
Output:
[3, 5, 7, 3, 9, 3]
After deleting: [3, 5, 3, 9, 3]
Note: You don't need to import any extra module to use these functions for removing an element from the
list.
We cannot use these methods with a tuple because the tuple is different from the list.
It is a string's function which converts all uppercase characters into lowercase and vice versa. It is used to alter
the existing case of the string. This method creates a copy of the string which contains all the characters in the
swap case. If the string is in lowercase, it generates a small case string and vice versa. It automatically ignores
all the non-alphabetic characters. See an example below.
Example:
Output:
it is in lowercase.
IT IS IN UPPERCASE.
To remove the whitespaces and trailing spaces from the string, Python providies strip([str]) built-in function.
This function returns a copy of the string after removing whitespaces if present. Otherwise returns original
string.
Example:
Output:
javatpoint
javatpoint
javatpoint
After stripping all have placed in a sequence:
Javatpoint
javatpoint
javatpoint
To remove leading characters from a string, we can use lstrip() function. It is Python string function which takes
an optional char type parameter. If a parameter is provided, it removes the character. Otherwise, it removes all
the leading spaces from the string.
Example:
Output:
javatpoint
javatpoint
After stripping all leading whitespaces:
javatpoint
javatpoint
After stripping, all the whitespaces are removed, and now the string looks like the below:
The join() is defined as a string method which returns a string value. It is concatenated with the elements of an
iterable. It provides a flexible way to concatenate the strings. See an example below.
Example:
1. str = "Rohan"
2. str2 = "ab"
3. # Calling function
4. str2 = str.join(str2)
5. # Displaying result
6. print(str2)
Output:
aRohanb
This method shuffles the given string or an array. It randomizes the items in the array. This method is present
in the random module. So, we need to import it and then we can call the function. It shuffles elements each time
when the function calls and produces different output.
Example:
Output:
Original LIST1:
['Z', 'Y', 'X', 'W', 'V', 'U']
The break statement is used to terminate the execution of the current loop. Break always breaks the current
execution and transfer control to outside the current block. If the block is in a loop, it exits from the loop, and if
the break is in a nested loop, it exits from the innermost loop.
Example:
Output:
2
X 11
X 22
X 33
Y 11
Y 22
Y 33
BREAK
A tuple is a built-in data collection type. It allows us to store values in a sequence. It is immutable, so no change
is reflected in the original data. It uses () brackets rather than [] square brackets to create a tuple. We cannot
remove any element but can find in the tuple. We can use indexing to get elements. It also allows traversing
elements in reverse order by using negative indexing. Tuple supports various methods like max(), sum(),
sorted(), Len() etc.
Example:
1. # Declaring tuple
2. tup = (2,4,6,8)
3. # Displaying value
4. print(tup)
5.
6. # Displaying Single value
7. print(tup[2])
Output:
(2, 4, 6, 8)
6
Example:
1. # Declaring tuple
2. tup = (2,4,6,8)
3. # Displaying value
4. print(tup)
5.
6. # Displaying Single value
7. print(tup[2])
8.
9. # Updating by assigning new value
10. tup[2]=22
11. # Displaying Single value
12. print(tup[2])
Output:
tup[2]=22
TypeError: 'tuple' object does not support item assignment
(2, 4, 6, 8)
The Python provides libraries/modules that enable you to manipulate text files and binary files on the file
system. It helps to create files, update their contents, copy, and delete files. The libraries are os, os.path, and
shutil.
Here, os and os.path - modules include a function for accessing the filesystem
while shutil - module enables you to copy and delete the files.
20) What are the different file processing modes supported by Python?
Python provides four modes to open files. The read-only (r), write-only (w), read-write (rw) and append mode
(a). 'r' is used to open a file in read-only mode, 'w' is used to open a file in write-only mode, 'rw' is used to open
in reading and write mode, 'a' is used to open a file in append mode. If the mode is not specified, by default file
opens in read-only mode.
o Read-only mode (r): Open a file for reading. It is the default mode.
o Write-only mode (w): Open a file for writing. If the file contains data, data would be lost. Other a new
file is created.
o Read-Write mode (rw): Open a file for reading, write mode. It means updating mode.
o Append mode (a): Open for writing, append to the end of the file, if the file exists.
An operator is a particular symbol which is used on some values and produces an output as a result. An operator
works on operands. Operands are numeric literals or variables which hold some values. Operators can be
unary, binary or ternary. An operator which requires a single operand known as a unary operator, which
require two operands known as a binary operator and which require three operands is called ternary
operator.
Example:
1. # Unary Operator
2. A = 12
3. B = -(A)
4. print (B)
5. # Binary Operator
6. A = 12
7. B = 13
8. print (A + B)
9. print (B * A)
10. #Ternary Operator
11. A = 12
12. B = 13
13. min = A if A < B else B
14.
15. print(min)
Output:
# Unary Operator
-12
# Binary Operator
25
156
# Ternary Operator
12
Python uses a rich set of operators to perform a variety of operations. Some individual operators like
membership and identity operators are not so familiar but allow to perform operations.
o Assignment Operators
o Logical Operators
o Membership Operators
o Identity Operators
o Bitwise Operators
Arithmetic operators perform basic arithmetic operations. For example "+" is used to add and "?" is used for
subtraction.
Example:
Output:
35
-11
276
0.5217391304347826
Relational Operators are used to comparing the values. These operators test the conditions and then returns
a boolean value either True or False.
Example:
1. a, b = 10, 12
2. print(a==b) # False
3. print(a<b) # True
4. print(a<=b) # True
5. print(a!=b) # True
Output:
False
True
True
True
Assignment operators are used to assigning values to the variables. See the examples below.
Example:
Output:
12
14
12
24
576
Logical operators are used to performing logical operations like And, Or, and Not. See the example below.
Example:
Output:
False
True
True
Membership operators are used to checking whether an element is a member of the sequence (list, dictionary,
tuples) or not. Python uses two membership operators in and not in operators to check element presence. See
an example.
Example:
Output:
False
True
Identity Operators (is and is not) both are used to check two values or variable which are located on the same
part of the memory. Two variables that are equal does not imply that they are identical. See the following
examples.
Example:
Output:
False
True
Bitwise Operators are used to performing operations over the bits. The binary operators (&, |, OR) work on
bits. See the example below.
Example:
Output:
8
14
6
-11
In Python 3, the old Unicode type has replaced by "str" type, and the string is treated as Unicode by default. We
can make a string in Unicode by using art.title.encode("utf-8") function.
Example:
Output:
Python is an interpreted language. The Python language program runs directly from the source code. It converts
the source code into an intermediate language code, which is again translated into machine language that has
to be executed.
Unlike Java or C, Python does not require compilation before execution.
o Memory management in python is managed by Python private heap space. All Python objects and data
structures are located in a private heap. The programmer does not have access to this private heap.
The python interpreter takes care of this instead.
o The allocation of heap space for Python objects is done by Python's memory manager. The core API
gives access to some tools for the programmer to code.
o Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can
be made available to the heap space.
Decorators are very powerful and a useful tool in Python that allows the programmers to add functionality to
an existing code. This is also called metaprogramming because a part of the program tries to modify another
part of the program at compile time. It allows the user to wrap another function to extend the behaviour of the
wrapped function, without permanently modifying it.
Example:
1. def function_is_called():
2. def function_is_returned():
3. print("JavaTpoint")
4. return function_is_returned
5. new_1 = function_is_called()
6. # Outputs "JavaTpoint"
7. new_1()
Output:
JavaTpoint
A function is a block of code that performs a specific task whereas a decorator is a function that modifies other
functions.
27) What are the rules for a local and global variable in Python?
Global Variables:
o Variables declared outside a function or in global space are called global variables.
o If a variable is ever assigned a new value inside the function, the variable is implicitly local, and we
need to declare it as 'global' explicitly. To make a variable globally, we need to declare it by using global
keyword.
o Global variables are accessible anywhere in the program, and any function can access and modify its
value.
Example:
1. A = "JavaTpoint"
2. def my_function():
3. print(A)
4. my_function()
Output:
JavaTpoint
Local Variables:
o Any variable declared inside a function is known as a local variable. This variable is present in the local
space and not in the global space.
o If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local.
Example:
1. def my_function2():
2. K = "JavaTpoint Local"
3. print(K)
4. my_function2()
Output:
JavaTpoint Local
The namespace is a fundamental idea to structure and organize the code that is more useful in large projects.
However, it could be a bit difficult concept to grasp if you're new to programming. Hence, we tried to make
namespaces just a little easier to understand.
A namespace is defined as a simple system to control the names in a program. It ensures that names are unique
and won't lead to any conflict.
Also, Python implements namespaces in the form of dictionaries and maintains name-to-object mapping where
names act as keys and the objects as values.
In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are the collection of
items, and it can be a list, tuple, or a dictionary. Python iterator implements __itr__ and next() method to iterate
the stored elements. In Python, we generally use loops to iterate over the collections (list, tuple).
In simple words: Iterators are objects which can be traversed though or iterated upon.
In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that
it yields expression in the function. It does not implements __itr__ and next() method and reduce other
overheads as well.
If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current
execution by saving its states and then resume from the same when required.
31) What is slicing in Python?
Slicing is a mechanism used to select a range of items from sequence type like list, tuple, and string. It is
beneficial and easy to get elements from a range by using slice way. It requires a : (colon) which separates the
start and end index of the field. All the data collection types List or tuple allows us to use slicing to fetch
elements. Although we can get elements by specifying an index, we get only single element whereas using
slicing we can get a group of elements.
Example:
Output:
The Python dictionary is a built-in data type. It defines a one-to-one relationship between keys and values.
Dictionaries contain a pair of keys and their corresponding values. It stores elements in key and value pairs.
The keys are unique whereas values can be duplicate. The key accesses the dictionary elements.
Example:
The following example contains some keys Country Hero & Cartoon. Their corresponding values are India,
Modi, and Rahul respectively.
Output:
Country: India
Hero: Modi
Cartoon: Rahul
Pass specifies a Python statement without operations. It is a placeholder in a compound statement. If we want
to create an empty class or functions, the pass keyword helps to pass the control without error.
Example:
1. class Student:
2. pass # Passing class
3. class Student:
4. def info():
5. pass # Passing function
The Python docstring is a string literal that occurs as the first statement in a module, function, class, or method
definition. It provides a convenient way to associate the documentation.
String literals occurring immediately after a simple assignment at the top are called "attribute docstrings".
String literals occurring immediately after another docstring are called "additional docstrings".
Python uses triple quotes to create docstrings even though the string fits on one line.
Docstring phrase ends with a period (.) and can be multiple lines. It may consist of spaces and other special
chars.
Example:
1. # One-line docstrings
2. def hello():
3. """A function to greet."""
4. return "hello"
35) What is a negative index in Python and why are they used?
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 go 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.
The Python pickle is defined as a module which accepts any Python object and converts it into a string
representation. It dumps the Python object into a file using the dump function; this process is called Pickling.
The process of retrieving the original Python objects from the stored string representation is called
as Unpickling.
37) Which programming language is a good choice between Java and Python?
Java and Python both are object-oriented programming languages. Let's compare both on some criteria given
below:
Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated
dump of built-in functions.
Help() function: The help() function is used to display the documentation string and also facilitates us to see
the help related to modules, keywords, and attributes.
Dir() function: The dir() function is used to display the defined symbols.
39) What are the differences between Python 2.x and Python 3.x?
Python 2.x is an older version of Python. Python 3.x is newer and latest version. Python 2.x is legacy now. Python
3.x is the present and future of this language.
The most visible difference between Python2 and Python3 is in print statement (function). In Python 2, it looks
like print "Hello", and in Python 3, it is print ("Hello").
The xrange() method has removed from Python 3 version. A new keyword as is introduced in Error handling.
In Python, some amount of coding is done at compile time, but most of the checking such as type, name, etc. are
postponed until code execution. Consequently, if the Python code references a user-defined function that does
not exist, the code will compile successfully. The Python code will fail only with an exception when the code
execution path does not exist.
41) What is the shortest method to open a text file and display its content?
The shortest way to open a text file is by using "with" command in the following manner:
Example:
Output:
Example:
1. list_1 = ["A","B","C"]
2. s_1 = "Javatpoint"
3. # creating enumerate objects
4. object_1 = enumerate(list_1)
5. object_2 = enumerate(s_1)
6.
7. print ("Return type:",type(object_1))
8. print (list(enumerate(list_1)))
9. print (list(enumerate(s_1)))
Output:
Return type:
[(0, 'A'), (1, 'B'), (2, 'C')]
[(0, 'J'), (1, 'a'), (2, 'v'), (3, 'a'), (4, 't'), (5, 'p'), (6, 'o'), (7, 'i'), (8, 'n'), (9, 't')]
Since indexing starts from zero, an element present at 3rd index is 7. So, the output is 7.
Type conversion refers to the conversion of one data type iinto another.
dict() - This function is used to convert a tuple of order (key,value) into a dictionary.
To send an email, Python provides smtplib and email modules. Import these modules into the created mail
script and send mail by authenticating a user.
It has a method SMTP(smtp-server, port). It requires two parameters to establish SMTP connection.
Example:
1. import smtplib
2. # Calling SMTP
3. s = smtplib.SMTP('smtp.gmail.com', 587)
4. # TLS for network security
5. s.starttls()
6. # User email Authentication
7. s.login("sender@email_id", "sender_email_id_password")
8. # Message to be sent
9. message = "Message_sender_need_to_send"
10. # Sending the mail
11. s.sendmail("sender@email_id ", "receiver@email_id", message)
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:
Output:
The anonymous function in python is a function that is defined without a name. The normal functions are
defined using a keyword "def", whereas, the anonymous functions are defined using the lambda function. The
anonymous functions are also called as lambda functions.
Lambda forms in Python does not have the statement because it is used to make the new function object and
return them in runtime.
A function is a block of code which is executed only when it is called. To define a Python function, the def
keyword is used.
Example:
1. def New_func():
2. print ("Hi, Welcome to JavaTpoint")
3. New_func() #calling the function
Output:
The __init__ is a method or constructor in Python. This method is automatically called to allocate memory when
a new object/ instance of a class is created. All classes have the __init__ method.
Example:
1. class Employee_1:
2. def __init__(self, name, age,salary):
3. self.name = name
4. self.age = age
5. self.salary = 20000
6. E_1 = Employee_1("pqr", 20, 25000)
7. # E1 is the instance of class Employee.
8. #__init__ allocates memory for E1.
9. print(E_1.name)
10. print(E_1.age)
11. print(E_1.salary)
Output:
pqr
20
25000
Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However,
this is not the case in Java where it's optional. It helps to differentiate between the methods and attributes of a
class with local variables.
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.
Random module is the standard module that is used to generate a random number. The method is defined as:
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:
randrange(a, b): it chooses an integer and define the range in-between [a, b). It returns the elements by
selecting it randomly from the range that is specified. It doesn't build a range object.
uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating
point number
normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a
sigma that is used for standard deviation.
The Random class that is used and instantiated creates independent multiple random number generators.
PYTHONPATH is an environment variable which is used when a module is imported. Whenever a module is
imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various
directories. The interpreter uses it to determine which module to load.
54) What are python modules? Name some commonly used built-in modules in Python?
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.
o os
o sys
o math
o random
o data time
o JSON
For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to
generate a list of integers for you to use, however you please. The only difference is that range returns a Python
list object and x range returns an xrange object.
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.
56) What advantages do NumPy arrays offer over (nested) Python lists?
o 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.
o 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.
o NumPy is not just more efficient; it is also more convenient. We get a lot of vector and matrix
operations for free, which sometimes allow one to avoid unnecessary work. And they are also
efficiently implemented.
o NumPy array is faster and we get a lot built in with NumPy, FFTs, convolutions, fast searching, basic
statistics, linear algebra, histograms, etc.
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.
58) Explain the use of session in Django framework?
Django provides a session that lets the user 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 good from a security perspective.
1) Which of the following statements is/are TRUE in respect of the Python programming language?
Statement 2: Python provides high-level data structures along with dynamic binding and typing for Rapid
Application Development and deployment.
Options:
a. Only Statement 1
b. Statement 1 and 2
c. Statement 1 and 3
Options:
3) Which of the following statements is/are NOT correct regarding Memory Management in Python?
Statement 1: Python Memory Manager handles the management regarding memory in Python
Statement 2: Python uses CMS (Concurrent Mark Sweep) approach as its Garbage Collection technique.
Statement 3: Python offers a core garbage collection to recycle the vacant memory for the private heap space.
Options:
a. Only Statement 3
b. Statement 1 and 3
c. Statement 2 and 3
d. Only Statement 2
4) Which of the following statements is/are NOT correct in respect to Python namespaces?
Statement 2: Python namespaces are classified into three types - local, global and built-in.
Statement 3: A Python namespace ensures that the names of the objects in a program are unique and can be
utilized, deprived of any inconsistency.
Options:
a. Only Statement 1
b. Only Statement 3
c. Statement 1 and 2
d. Statement 1 and 3
Options:
6) In respect to the scope in Python, which of the following statements is/are TRUE?
Statement 1: A variable created within a function belongs to the local scope and can be used outside that
function.
Statement 2: A local scope is referred to the object present through the execution of code since its inception.
Statement 3: A local scope is referred to the local object present in the current function.
Options:
a. Only Statement 2
b. Statement 1 and 3
c. Only Statement 3
Code:
1. # assigning a variable
2. myint = 10
3.
4. # defining a function
5. def myfunction():
6. # reassigning a variable
7. myint = 20
8.
9. # calling the function
10. myfunction()
11.
12. # printing the value of the variable
13. print(myint)
Options:
a. 10
b. 20
c. 0
d. Traceback Error
Code:
1. # assigning a variable
2. myint = 21
3.
4. # using if False statement
5. if False:
6. # reassigning a variable
7. myint = 34
8.
9. # defining a function
10. def myfunction():
11. if True:
12. # reassigning a variable
13. myint = 65
14.
15. # calling the function
16. myfunction()
17.
18. # printing the value of the variable
19. print(myint)
Options:
a. 65
b. Traceback Error
c. 21
d. 34
Show Answer Workspace
9) Among the following statements based on the difference between lists and tuples, which one statement is
TRUE?
Options:
a. Statement 1
b. Statement 4
c. Statement 2
d. Statement 3
Code:
1. # defining a list
2. my_list = [7, 9, 8, 2, 5, 0, 1, 3, 6]
3. # using the pop() function
4. my_list.pop(2)
5. # printing the final list
6. print(my_list)
Options:
a. [7, 9, 2, 5, 0, 1, 3, 6]
b. [7, 9, 8, 2, 5, 0, 3, 6]
c. [7, 8, 2, 5, 0, 1, 3, 6]
d. [7, 9, 8, 2, 5, 0, 1, 6]
Python Basic Interview Questions
1. What is Python?
Python is a high-level and object-oriented programming language with unified semantics designed primarily
for developing apps and the web. It is the core language in the field of Rapid Application Development (RAD)
as it offers options such as dynamic binding and dynamic typing.
Speed and Productivity: Utilizing the productivity and speed of Python will enhance the process
control capabilities and possesses strong integration.
Extensive Support for Libraries: Python provides a large standard library that includes areas such
as operating system interfaces, web service tools, internet protocols, and string protocols. Most of the
programming tasks are already been scripted in the standard library which reduces effort and time.
User-friendly Data Structures: Python has an in-built dictionary of data structures that are used to
build fast user-friendly data structures.
Existence of Third Party Modules: The presence of third-party modules in the Python Package
Index (PyPI) will make Python capable to interact with other platforms and languages.
Easy Learning: Python provides excellent readability and simple syntaxes to make it easy for
beginners to learn.
The following are the significant features of Python, and they are:
Interpreted Language: Python is an interpreted language that is used to execute the code line by
line at a time. This makes debugging easy.
Highly Portable: Python can run on different platforms such as Unix, Macintosh, Linux, Windows,
and so on. So, we can say that it is a highly portable language.
Extensible: It ensures that the Python code can be compiled on various other languages such as C,
C++, and so on.
GUI programming Support: It implies that Python provides support to develop graphical user
interfaces
Python is suitable for scripting, but in general, it is considered a general-purpose programming language.
Top 10 Programming Languages that you need to watch out to boost your career in 2022
List
Tuple
These lists performance is slower Tuple performance is faster when compared to lists
Syntax: list_1 = [20, ‘Mindmajix’, 30] Syntax: tup_1 = (20, ‘Mindmajix’, 30)
Global Variables in Python: The variables that are declared outside the function are called global variables.
These variables can be accessed or invoked by any function in the program.
Example:
def v() :
print g
g = "welcome to mindmajix"
v()
Output:
Welcome to mindmajix
Local Variables in Python: The variables that are declared inside a function are called local variables. These
types of variables can be accessed only inside the function.
PYTHONPATH is an environmental variable that is used when we import a module. Suppose at any time we
import a module, PYTHONPATH is used to check the presence of the modules that are imported in different
directories. Loading of the module will be determined by interpreters.
PEP 8 is the Python latest coding convention and it is abbreviated as Python Enhancement Proposal. It is all
about how to format your Python code for maximum readability.
In Python memory management is done using private heap space. The private heap is the storage
area for all the data structures and objects. The interpreter has access to the private heap and the
programmer cannot access this private heap.
The storage allocation for the data structures and objects in Python is done by the memory manager.
The access for some tools is provided by core API for programmers to code.
The built-in garbage collector in Python is used to recycle all the unused memory so that it can be
available for heap storage area.
Function
Java Python
In Java, we need to write a long code to print In Python coding is simple and smaller when
Coding
something. compared to Java
In Java, we need to declare the type for each In this case, codes are dynamically typed and
Dynamic
variable this is also known as duck typing
Java is not easy to use because of its larger In Python, it is very easy to code and perform
Easy to use
coding very easily.
Java Database Connectivity (JDBC) is more In Python database access layers are weaker
Databases
popular and used most commonly. when compared to Java.
13. Define modules in Python?
The module is defined as a file that includes a set of various functions and Python statements that we want to
add to our application.
In order to create a module first, we need to save the code that we want in a file with .py extension.
def wishes(name):
Print("Hi, " + name)
Integer
Complex numbers
Floating-point numbers
Strings
Built-in functions
Decorator is the most useful tool in Python as it allows programmers to alter the changes in the behavior of
class or function.
@gfg_decorator
def hi_decorator():
print("Gfg")
We can detect bugs in python source code using a static analysis tool named PyChecker. Moreover, there is
another tool called PyLint that checks whether the Python modules meet their coding standards or not.
py files are Python source files. .pyc files are the compiled bytecode files that are generated by the Python
compiler
18. How do you invoke the Python interpreter for interactive use?
By using python or pythonx. y we can invoke a Python interpreter. where x.y is the version of the Python
interpreter.
String in Python is formed using a sequence of characters. Value once assigned to a string cannot be modified
because they are immutable objects. String literals in Python can be declared using double quotes or single
quotes.
Example:
print("Hi")
print('Hi')
A namespace in Python can be defined as a system that is designed to provide a unique name for every object
in python. Types of namespaces that are present in Python are:
Local namespace
Global namespace
Built-in namespace
Scope refers to the availability and accessibility of an object in the coding region.
In Python, an iterator can be defined as an object that can be iterated or traversed upon. In another way, it is
mainly used to iterate a group of containers, elements, the same as a list.
Slicing is a procedure used to select a particular range of items from sequence types such as Strings, lists, and
so on.
26. What happens when a function doesn’t have a return statement? Is this valid?
Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of
code that is executed (i.e., the indenting) not by any explicit keyword.
In order to make a Python script executable on Unix, we need to perform two things. They are:
OS.unlink(filename) or OS.remove(filename) are the commands used to delete files in Python Programming.
Example:
import OS
OS.remove("abc.txt")
Pickling in Python: The process in which the pickle module accepts various Python objects and converts
them into a string representation and dumps the file accordingly using the dump function is called pickling.
Unpickling in Python: The process of retrieving actual Python objects from the stored string representation
is called unpickling.
Local namespaces are created within a function when that function is called. Global namespaces are created
when the program starts.
33. What are Python String formats and Python String replacements?
Python String Format: The String format() method in Python is mainly used to format the given string into an
accurate output or result.
Python String Replace: This method is mainly used to return a copy of the string in which all the occurrence of
the substring is replaced by another substring.
sys module
OS module
random module
collection module
JSON
Math module
In Python, functions are defined as a block of code that is executable only when it is called. The def keyword is
used to define a function in Python.
Example:
def Func():
print("Hello, Welcome toMindmajix")
Func(); #calling the function
These are mostly used as syntax constructions to ease the creation of lists and dictionaries based on existing
iterable.
37. Define the term lambda?
Lambda is the small anonymous function in Python that is often used as an inline function.
Triple quotes ‘’” or ‘“ are string delimiters that can span multiple lines in Python. Triple quotes are usually
used when spanning multiple lines, or enclosing a string that has a mix of single and double quotes contained
therein.
In Python self is defined as an object or an instance of a class. This self is explicitly considered as the first
parameter in Python. Moreover, we can also access all the methods and attributes of the classes in Python
programming using self keyword.
In the case of the init method, self refers to the newer creation of the object. Whereas in the case of other
methods self refers to the object whose method was called.
The _init_ is a special type of method in Python that is called automatically when the memory is allocated for a
new object. The main role of _init_ is to initialize the values of instance members for objects.
Example:
class Student:
def _init_ (self, name, age, marks):
self.name = name
self.age = age
self.marks = 950
S1 = Student("ABC", 22, 950)
# S1 is the instance of class Student.
# _init allocates memory for S1.
print(S1.name)
print(S1.age)
print(S1.marks)
Output:
ABC
22
950
The docstring in Python is also called a documentation string, it provides a way to document the Python
classes, functions, and modules.
Example:
str = 'XYZ'
print(str.lower())
Output:
xyz
Ans: The elements can be removed from a Python array using the remove() or pop() function. The difference
between pop() and remove() will be explained in the below example.
Example:
Output:
7.3
4.8
array(‘d’, [2.2, 3.4, 5.2, 6.6])
For More Info: Array Example in Python
Syntax:
try{
//statements that may cause an exception
}
Example:
We can access the module written in Python from C by using the following method.
Module == PyImport_ImportModule("<modulename>");
By using the list.reverse(): we can reverse the objects of the list in Python.
Output:
def pyfun(r):
for a in range(r):
print(' '*(r-x-1)+'*'*(2*x+1))
pyfun(9)
Output:
*
***
*****
*******
*********
***********
*************
***************
*****************
54. Write a program to check whether the given number is prime or not?
Output:
55. Write Python code to check the given sequence is a palindrome or not?
# Python code to check a given sequence
# is palindrome or not
my_string1 = 'MOM'
My_string1 = my_string1.casefold()
# reverse the given string
rev_string1 = reversed(my_string1)
# check whether the string is equal to the reverse of it or not
if list(my_string1) == list(rev_string1):
print("It is a palindrome")
else:
print("It is not a palindrome")
Output:
it is a palindrome
Output:
1, 5, 8, 13, 16
x = ['ab','cd']
print(list(map(list, x)))
58. What is the procedure to install Python on Windows and set path variables?
We need to implement the following steps to install Python on Windows, and they are:
First, you need to install Python from https://www.python.org/downloads/
After installing Python on your PC, find the place where it is located in your PC using the cmd python
command.
Then visit advanced system settings on your PC and add a new variable. Name the new variable as
PYTHON_NAME then copy the path and paste it.
Search for the path variable and select one of the values for it and click on ‘edit’.
Finally, we need to add a semicolon at the end of the value, and if the semicolon is not present then
type %PYTHON_NAME%.
NumPy
SciPy
It is used for performing general and efficient computations on numerical This is an entire collection of tools in Python mainl
data which is saved in arrays. For example, indexing, reshaping, sorting, perform operations like differentiation, integration
and so on many more.
There are some of the linear algebraic functions present in this module For performing algebraic computations this modul
but they are not fully-fledged. contains some of the fully-fledged operations
60. How do Python arrays and lists differ from each other?
Arrays
Lists
Since array stores only a similar type of data so it occupies less List stores different types of data so it requires a huge amo
amount of memory when compared to the list. memory
The length of the array is fixed at the time of designing and no more The length of the list is no fixed, and adding items in the m
elements can be added in the middle. possible in lists.
61. Can we make multi-line comments in Python?
In python, there is no specific syntax to display multi-line comments like other languages. In order to display
multi-line comments in Python, programmers use triple-quoted (docstrings) strings. If the docstring is not
used as the first statement in the present method, it will not be considered by the Python parser.
Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!
Both the methods are mainly used in Python to iterate the for loop for a fixed number of times. They differ
only when we talk regarding Python versions.
Range() method
Xrange() method
The xrange() method is not supported in Python3 so that the The xrange() method is used only in Python version 2 for t
range() method is used for iteration in for loops. iteration in loops.
It occupies a huge amount of memory as it stores the complete list It occupies less memory because it only stores one number
of iterating numbers in memory. in memory.
Excellent documentation
Python web framework
SEO optimized
High scalability
Versatile in nature
Offers high security
Thoroughly tested
Provides rapid Development
Django is a high-level Python web framework that was developed for realistic design, clean, rapid
development.
One of the important advantages of Django is it is a framework of python language which is very
simple to learn
Django is a multifaceted framework
When it comes to security Django is the best framework
Scalability is added advantage of Django
The main goal to designing Django is to make it simple to its users, to do this Django uses:
The principles concerning rapid development, which implies developers can complete more than one
iteration at a time without beginning the full schedule from scratch;
DRY philosophy — Do not Replicate Yourself — that means developers can reuse surviving code and
also focus on the individual one.
68. List the common security issues that can be avoided by using Django?
A few common security issues that can be avoided by using Django are:
Clickjacking
Cross-site scripting and
SQL injection
69. List a few of the famous companies that are using Django?
Few well-known companies that are using the Django framework are
Instagram
Spotify
Mozilla
Dropbox
NASA
Here is an exciting reality: Django has first created to power a web application as a newspaper publisher, the
Lawrence Journal-World. You all can demand it to be very good about handling projects by volumes from the
text files, media, including extremely high traffic, or else something that operates as a web publication.
Ans: There are only three main steps for setting up Django static files
Django web framework is operated and also maintained by an autonomous and non-profit organization
designated as Django Software Foundation (DSF). The initial foundation goal is to promote, support, and
advance this Django Web framework.
urlpatterns = [
path('appmajix/', appmajix.site.urls),
A session comprises a mechanism to store information on a specific server-side at the interaction by the web
application. By default, session reserves in the database and allows file-based and cache-based sessions.
A cookie is a piece of information that is stored in a client's browser for a specific time. When the specific time
is completed cookie gets automatically removed from the client browser.
78. Mentions the methods used for setting and getting cookie values?
It is an automatically built file inside each Django project. It is a flat wrapper encompassing the Django-
admin.py. It possesses the following usage:
Django has described as a loosely coupled framework because of the MTV architecture it’s based upon.
Django’s architecture means a variant of MVC architecture and also MTV is helpful because this completely
separates the server code of the client’s machine.
we can make use of the edit mysite/setting.py command, which is a simple Python module that consists of
levels for presenting or displaying Django settings.
By default Django uses SQLite; this also makes it easy for Django users in case of any other type of
installations. For example, if your database choice is different then you need to follow certain keys in the
DATABASE like default items to match database connection settings.
Engines: By these engines you change the database by using commands such as
‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.sqlite3’, ‘django.db.backends.oracle’,
‘django.db.backends.mysql’, and so on.
Name: This represents the name of your own database. If you are familiar with using SQLite as your
database, in such cases database is available as a file on your particular system. Moreover, the name
should be as a fully absolute or exact path along with the file name of the particular file.
Suppose if we are not using SQLite as your database then additional settings such as password, user,
the host must be added.
Django mainly uses SQLite as its default database to store entire information in a single file of the filesystem.
If you want to use different database servers rather than SQLite, then make use of database administration
tools to create a new database for the Django project. Another way is by using your own database in that
place, and the remaining is to explain Django about how to use it. This is the place in which Python’s project
settings.py file comes into the picture.
DATABASE = {
‘Default’ : {
‘ENGINE’ : ‘django.db.backends.sqlite3’,
‘NAME’ : os.path.join(BASE_DIR, ‘db.sqlite3’),
}
}
There are three possible inheritance styles in Django, and they are:
Proxy models: This style is mainly used for those who want to modify the Python level behavior of
the model, without modifying the model’s fields.
Abstract Base Classes: This inheritance style is used only when we want to make parent class hold
the data which they don’t want to repeat again in the child class.
Multi-table Inheritance: This inheritance style is used only when we want to subclass an existing
model and there must a database table designed for each model on its own.
85. How to save an image locally using Python in which we already know the URL address?
The following code is used to save the image locally from the URL address which we know.
import urllib.request
urllib.request.urlretrieve("URL", "local-filename.jpg")
87. Is flask an MVC model? If yes, justify your answer by showing an example of your application with
the help of the MVC pattern?
Basically, a flask is a minimalistic framework that behaves the same as the MVC framework. So MVC will be
perfectly suitable for the flask and we will consider the MVC pattern in the below example.
@app.route(“/”)
Def hey():
return “Welcome to Appmajix”
app.run(debug = True)
Database-powered applications are supported by the flask. The relational database systems need to create a
schema that requires piping the schema.sql file into an SQLite3 command. So, in this case, you need to install
the SQLite3 command on your system to initiate and create the database in the flask.
We can request a database using flask in three ways, and they are:
before_request(): Using this we can request database before only without passing arguments.
after_request(): This method is called after requesting the database and also send the response to
the client.
teardown_request(): This method is called in the cases where the responses are not guaranteed and
the exception is raised. They have no access to modify the request.
89. Explain the procedure to minimize or lower the outages of the Memcached server in your Python
development?
The following are the steps used to minimize the outages of the Memcached server in your Python
development, and they are.
When a single instance fails, this will impact on larger load of the database server. The client makes
the request when the data is reloaded. In order to avoid this, the code that you have written must be
used to lower cache stampedes then it will be used to leave a minimal impact.
The other way is to bring out the instance of the Memcached on a new machine by using the IP
address of the lost machine.
Another important option is to lower the server outages is code. This code provides you with the
liberty to modify the Memcached server list with minimal work
another way is by setting a timeout value that will be one of the options for memcac
Class Student:
def __init__(self, name):
self.name = name
S1=Student("XYZ")
print(S1.name)
hed clients to implement the Memcached server outage. When the performance of the server goes
down, the client keeps on sending a request until the timeout limit is reached.
This is defined as an occurrence of an event when the cache expires and also when the websites are hit with
more requests by the client at a time. This dogpile effect can be averted by the use of a semaphore lock. If in
the particular system the value expires then, first of all, the particular process receives the lock and begins
generating new value.
Ans: Python is also an object-oriented programming language like other programming languages. It also
contains different OOP's concepts, and they are
Object
Class
Method
Encapsulation
Abstraction
Inheritance
Polymorphism
Related Article: Top 50 OOPs Interview Questions
An object in Python is defined as an instance that has both state and behavior. Everything in Python is made
of objects.
Class is defined as a logical entity that is a huge collection of objects and it also contains both methods and
attributes.
In Python programming, the class is created using a class keyword. The syntax for creating a class is as
follows:
class ClassName:
#code (statement-suite)
Output:
XYZ
<object-name> = <class-name>(<arguments>)
The Method is defined as the function associated with a particular object. The method which we define should
not be unique as a class instance. Any type of object can have methods.
Multiple inheritances are supported in python. It is a process that provides flexibility to inherit multiple base
classes in a child class.
class Calculus:
def Sum(self,a,b):
return a+b;
class Calculus1:
def Mul(self,a,b):
return a*b;
class Derived(Calculus,Calculus1):
def Div(self,a,b):
return a/b;
d = Derived()
print(d.Sum(10,30))
print(d.Mul(10,30))
print(d.Div(10,30))
Output:
40
300
0.3333
In simple words, abstraction can be defined as hiding unnecessary data and showing or executing necessary
data. In technical terms, abstraction can be defined as hiding internal processes and showing only the
functionality. In Python abstraction can be achieved using encapsulation.
Encapsulation is one of the most important aspects of object-oriented programming. The binding or wrapping
of code and data together into a single cell is called encapsulation. Encapsulation in Python is mainly used to
restrict access to methods and variables.
By using polymorphism in Python we will understand how to perform a single task in different ways. For
example, designing a shape is the task and various possible ways in shapes are a triangle, rectangle, circle,
and so on.
Python does not make use of access specifiers and also it does not provide a way to access an instance
variable. Python introduced a concept of prefixing the name of the method, function, or variable by using a
double or single underscore to act like the behavior of private and protected access specifiers.
Empty class in Python is defined as a class that does not contain any code defined within the block. It can be
created using pass keywords and object to this class can be created outside the class itself.
Example:
class x:
pass
obj=x()
obj.id="123"
print("Id = ",obj.id)
Output:
123
Constructor is a special type of method with a block of code to initialize the state of instance members of the
class. A constructor is called only when the instance of the object is created. It is also used to verify that they
are sufficient resources for objects to perform a specific task.
Parameterized constructor
Non-parameterized constructor
The _init_ method in Python stimulates the constructor of the class. Creating a constructor in Python can be
explained clearly in the below example.
class Student:
def __init__(self,name,id):
self.id = id;
self.name = name;
def display (self):
print("ID: %d nName: %s"%(self.id,self.name))
stu1 =Student("nirvi",105)
stu2 = Student("tanvi",106)
#accessing display() method to print employee 1 information
stu1.display();
#accessing display() method to print employee 2 information
stu2.display();
Output:
ID: 1
Name: nirvi
ID: 106
Name: Tanvi
When an object of child class has the ability to acquire the properties of a parent class then it is called
inheritance. It is mainly used to acquire runtime polymorphism and also it provides code reusability.