Professional Documents
Culture Documents
● Single inheritance
● Multiple child class
● Multiple parent class
● Multilevel Inheritance
● Call parent class constructor form child class
Single Inheritance:
The single inheritance can be achieved by passing Old Parents class arguments to the child
class.
Program:
Class Parent:
P_Name=""
C_Name=""
def show_parent(self):
print(self. P_Name)
Class child(Parent):
P_Name=""
C_Name=""
def show_child(self):
print(self. C_Name)
arguments
ch_name=child()
ch_name.P_Name="Kumar"
ch_name.C_Name="vijay"
ch_name. show_parent
ch_name. show_child
Two or more child classes can inherit from old parent class.This is called as Multiple child
class.
Program:
Class Parent:
P_Name=""
C_Name=""
def show_parent(self):
print(self. P_Name)
Class cat(Parent):
def show_child(self):
print(self. C_Namee)
Class dog(Parent):
def show_child(self):
print(self. C_Name)
object of cat
ch_A1=cat()
ch_A1.P_Name="cat"
ch_A1. show_parent
ch_A1. show_child
object of dog
ch_A2=dog()
ch_A2.P_Name="cat"
ch_A2. show_parent
ch_A2. show_child
Multiple parent class Inheritance :
In this type of inheritance child class can inherit from a parnet old class.This is called as
Program:
Class mother:
M_Name=""
def show_mother(self):
print(self. M_Nam)
Class father:
F_Name=""
def show_father(self):
print(self. F_Name)
Class son(father,mother):
P_Name=""
C_Name=""
def show_parent(self):
print(self. F_Name)
print(self. M_Name)
object of son
s1=son()
s1.F_Name="cat"
s1.M_Name=" puppy "
s1. show_parent
Multilevel Inheritance :
In this type of Inheritance, a class can inherit from base class and child classes. This is
Program:
Class Family:
def show_Family(self):
print("This is my Family")
Class mother(Family):
M_Name=""
def show_mother(self):
print(self. M_Nam)
Class father(Family):
F_Name=""
def show_father(self):
print(self. F_Name)
Class son(father,mother):
P_Name=""
C_Name=""
def show_parent(self):
print(self. F_Name)
print(self. M_Name)
object of son
s1=son()
s1.F_Name="cat"
s1.show_parent
Call parent class constructor form child class Inheritance
In this type of inheritance, child class constructor initializes the parent class attributes. This
Program:
Class Family:
def __init__(self,name):
self.name=name
Class mother(Family):
M_Name=""
def __init__(self,name,age):
Family .__init__(self,name)
self.age=age
object of son
MM=mother("aaa",45)
print(MM.name)
print(MM.age)
● Python has many built-in exceptions which handles a program and throw error on console
if program is not properly working
● When these exception error occurs, python should handle this exception properly to avoid
program crash
● It is used to handle errors in python.
● Raise an exception in your program by using the raise exception statement.
Exception Errors:
IOError
Raised when an input/ output operation fails,
such as the print statement etc….
try-except exception:
‘try’ and ‘except’ are Python identifiers which is used to handle this exceptions.·
Syntax:
Example:
try-finally Exception:
It is intended to define actions that should be execute under all circumstances· A
finally clause is always executes before leaving the try statement, whether an exception has
Syntax:
Example:
● Python Iterator
● Python Generator
● Python Property
● Python Decorators
Python Iterator:
The Iterator Object has formally two methods to traverse to all values. This is called as python
Iterator.
Methods:
● ___iter__()
● __next__()
mylist=("a","b","c")
mylis=iter(mylist)
print(next(mylis))
print(next(mylis))
print(next(mylis))
value="Chennai"
city=iter(value)
print(next(city))
print(next(city))
print(next(city))
print(next(city))
print(next(city))
print(next(city))
print(next(city))
print(next(city))
value="Chennai"
for k in value:
print(k)
Python Generator :
The python Generator uses the keyword yield. The Generator function consists of two types
● Generator function
● Genrator Object
Generator Function:
It is a normal function with a statement to return a value, if the function contains one yield statement
Example:
def fun():
yield 1
yield 2
yield 3
for value in fun():
print(value)
Generator Object:
The Generator Function Returns the generator Object with the use of the next statement is being
Example:
def fun():
yield 1
yield 2
yield 3
x=fun()
print(x.next())
print(x.next())
print(x.next())
Python Property :
The python property is the concepts that make them easier. These built-in decorators. The python
Property is one of the hte decorators let us see an example using python property.
Example:
Class student:
def __init__(name,mark):
self.name=name
self.mark=mark
@property
def gotmark()
@property ##gotmarks.setter
def gotmark(self,kk)
nam,rand,marks=kk.split(' ')
self.name=name
self.mark=mark
s1=student(''abc","54")
print(s1.name)
printI(s1.mark)
print(s1.gotmarks)
print(s1.name)
printI(s1.mark)
print(s1.gotmarks)
Python Decorators:
This allows make simple modifications to callable objects like functions,methods and class.
Example1:
@decorator
def fun(args):
return value
fun1=decorator_func(fun)
print(fun1)
Example 2:
@decorator_ upper_case
def wraper(value):
value=function()
upper_case=value . upper()
return upper_case
fun1=decorator_ upper_case(value)
print(fun1)
Python Numbers
● Python will be supported at multiple data type integer, float, Boolean
and complex data type.
● By default, the interpreter preference considers the data type
depends upon simultaneous the usage of number.
Example code :
int= 10
float=12.5
boolean=True
complex=20+35j
print type(inte)
print type(floate)
print type(boolean)
print type(complexe)
Output :
<type 'int'>
<type 'float'>
<type 'bool'>
<type 'complex'>
Decimal Number
This becomes under regular character form which we are doing in general. We can also request it a
base 10 format.
Octal number
● Oct() function methods are one of the built-in methods using python.
● Oct() python method will be taken as an integer and return.
● Oct() python function data type value representation in string format.
Example Code:
print(oct(dec),"in octal.")
Oct(16)
Binary Number
bin(8)
print(bin(dec),"in binary.")
Output :
1101
Syntax :
hex(x)
Parameters :
x - an integer number (int object)
Example :
+ float.hex(2.6))
Python Functions
● Sequence of statements are grouped together under a unique name called function.
● It is more efficient when reusable parts are placed under function.
● It makes code more readable .
● It is easy to integrate different pieces of code together in a distributed development environment.
● It reduces effort for Testing and debugging.
Called Function
Callee Function
Types of Function:
1. with arguments and no return value
2. with arguments and with return value
3. without arguments and without return value
4. without arguments and with return value.
5. Multiple return values from Function definition
In this type, we are passing arguments in caller function and value will pass in function
In this type,we pass arguments in caller function and value will pass in function definition.Here we
In this type,we are not passing any arguments in caller function to function definition.Here we are
In this type,we are not passing arguments in caller function to function definition.Here we are
In this,we are returning more than one values from function definition.
Python Classes and Objects
Inheritance
Polymorphism
Abstraction
Encapsulation
Class
Class is one of the most important key feature in python. It is the collection of variables and
methods. In which methods are working on variables to perform targeted task.It act as template for
creating object.
sample classes:
class Employee(object):
def __init__(name, emp_no, salary, bonus):
self.name = name
self.emp_no = emp_no
self.salary = salary
self.bonus = bonus
def get_net_salary(self):
return self.salary + self.bonus
def display_employee_detail(self):
print(“Employee Name : {}”.format(self.name))
print(“Employe No : {}”.format(self.emp_no))
print(“Salary : {}”.format(self.salary))
Above one is the example for class. Name must follow keyword class. Class Employee consists of
four variables called name , emp_no, salaray, bonus. These varialbes are called instance variables.
Also, It having two methods named get_net_salary() and display_employee details(). These
Objects:
In order to access variables and methods in class, need to create object for that class. Object is the
Here, emp is the object for the class Employee. When instantiating object for the class , it is
mandatory to pass values to all variable used in __init__(). It is the special method in python for
initialing instance variable for that object. Each object will hold separate copy of the variables used in
the class. So it is called instance variables and methods working on these instance variable is called
instance method.
While creating object , it will call special method __init__() and initializing instance variables with
passed values. As created object, it could able to access variable and methods in class.
Suppose we want to know net salary of employee, Need to call method get_net_salary() method
using object as follow. It will return net salary of the employee by adding salary and bonus
emp.display_employee_detail()
Note that, methods are not doing anything interdependently. It just perform some task using
variables. Not only method, instance variables are also accessible using object as follow.
print(emp.name)
Print(emp.emp_no)
Suppose want to alter any of the instance variable after creating object. It can be done as follow.
emp.name = ‘Ram’
In order to ensure the change in the variable name , just calling the method
display_employee_details(). Now, it will display Ram as name instead of Rajan. In the same way ,
any of the instance variables can be altered with the help of the object.
Python String
Strings are represented as collection of characters. It is immutable. We can represent single quotes
Example:
print(str)
The above example gets input string from user and prints it. Python version 2, we use raw_input
Consider a string,
str = “python”
we can use slicing to extract each char’s.
Example:
str[0] #p
str[0:2] #py
1. capitalize()
Converts first char in to capital letter.
Example:
str = “python”
print(str.capitalize())
Output:
Python
2. Center()
Example
str = “python”
print(str.center(15,’*’))
output:
*****python****
3. count()
Example:
Output:
print(str.count(‘o’))
4. lower()
Returns all the char’s into lower case. upper() is the reverse process.
Example:
str = “PYTHON”
print(str.lower())
Output:
python
5. startswith()
Example:
print(str.startswith(‘p’))
Output:
True
Similarly, you can check endwith() method to find the char ended in the string or not.
6. find()
Returns the index of the given substring position. If the value is not found it returns, -1.
Example:
str = “python”
print(str.find(‘p’))
print(str.find(‘z’))
-1
7. format()
Example:
Output:
python is easy to learn program
8. index()
Example:
str = “python”
print(str.index(‘p’))
Output:
for i in str:
print(str.index(i))
Output:
9. strip()
print(str.strip())
Output:
10. title()
It converts all the char’s first starting letter into capital letter.
Example:
print(str.title())
Output:
Hi Python
11. isalnum ()
12. isupper()
checks the given string is upper case or not. similarly, you can find islower().
13.Casefold
Example
c = “123Hello”
a = “HellO worLd”
b = a.casefold()
print(b)
print(b.casefold())
Output
hello world
hello world
14. Encode
encode #execute this in command prompt, it depends upon the ide which supports the special
character
Example
‘backslashreplace’))
‘xmlcharrefreplace’))
print(“\n”)
b’I \\N{LATIN SMALL LETTER A WITH RING ABOVE}m le\\N{LATIN SMALL LETTER A
15.Endswith
Example:
print(infotext.endswith(“Python”))
print(infotext[0:7])
print(infotext.endswith(“Welcome”,0,7))
print(infotext[2:8])
print(infotext.endswith(“Welcome”,2,8))
print(infotext1[0:8])
print(infotext1.startswith(“Welcome”,0,8))
print(infotext1.endswith(“Welcome”,0,8))
Output
True
me to Python
False
Welcome
True
True
Welcome
True
lcome
False
Welcome
True
False
16.Expandtabs
Example
#mytabbedstring = “H e l l o”
mytabbedstring = “H\te\tl\tl\to”
print(mytabbedstring)
print(mytabbedstring.expandtabs(0))
print(mytabbedstring.expandtabs(2))
print(mytabbedstring.expandtabs(4))
print(mytabbedstring.expandtabs(tabsize = 5))
print(mytabbedstring.expandtabs(6))
print(mytabbedstring.expandtabs(8))
print(“\n”)
Output
welcome to my world1
welcome to my world3
Hello
Hello
Hello
Hello
Hello
Hello
Hello
17.Split
Example
AllFruits = Fruits.split(“,”)
print(AllFruits)
ThreeFruits = Fruits.split(“,”,2)
print(ThreeFruits)
[‘apple’, ‘orange’, ‘ grapes’, ‘ guava’, ‘ pineapple’] [‘apple’, ‘orange’, ‘ grapes, guava, pineapple’]
18.Isalpha,Isdecimal
characters [a-zA-Z0-9] mynotalphanumeric= “&abcdef123″ # Not fitting all three cases (Contain
symbol)
{}”.format(myalpha.isalpha()))
{}”.format(myalphanumeric.isalpha()))
{}”.format(mynotalphanumeric.isalpha()))
print(“\n”)
{}”.format(mynotalphanumeric.isalnum()))
print(“\n”)
{}”.format(myalphanumeric.isdecimal()))
{}”.format(mynotalphanumeric.isdecimal()))
Output
myalpa string is alpha – True
19.Substring
Example
#value before the : is the start sequence, after the colon is the end
sequence
print(TestString[0:5])
print(TestString[:5])
print(TestString[6:12])
print(TestString[5:])
print(TestString[-5:-1])
#print(TestString[::-1])
print(TestString[:-1])
print(TestString[-3:-5])
print(TestString[:])
#print(TestString[:-1:])
#print(TestString[:2:1])
#Reverse a string
print(TestString[::1])
print(TestString[::2])
print(TestString[::3])
print(TestString[::-1])
print(TestString[::-2])
Output
Hello
Hello
Python
Python
ytho
Hello Pytho
Hello Python
Hello Python
HloPto
HlPh
nohtyP olleH
nhy le
Python Files
File is a named location in disk to store data. In Python, a file operation takes place in the following
order.
● Open a file
● Read or write (perform operation)
● Close the file
Text file:
Binary file:
To Open File:
The default is reading in text mode. In this mode, we get strings when reading from the file.
In open() method explicitly need to mention mode = ‘b’ if you want to open binary files
Example:
Mode Description
purpose.
purpose.
truncated).
Open a file in binary mode for writing content
truncated.
To close file:
Python will automatically delete all cleanup resources like deleting objects or closing files at the end
of our program execution , to avoid data corruption ->programmer need to explicitly close the file.
f.close() ->need to be performed by programmer to ensure that data written to file buffer is flushed to
f.open(“msg.txt”,’w’)
f.write(“world”)
f.close()
In the above mentioned scenario , there may be chances of exception is raised during file write
f = open(“msg.txt”,”w”)
try :
f.write(“Good morning”)
Finally:
f.close()
Writing into a file using write()
Code snippet:
’sample_new.txt’ will get created if it does not exist. If it does exist, it is overwritten , the old content
will be truncated
Code snippet:
F=open(“sample_new.txt”,encoding=’utf-8’)
F.read() #reads the entire content of file from current file pointer
First line
f.seek(from_what,offset)
It will move the file pointer to the location based of from_what value and from there file pointer will be
Example :
f.seek(0,10)
->from starting of file , file pointer f will be moved 10 bytes
f.seek(1,10)
f.tell() ->to get the exact bytes where the file pointer is currently available
Code Snippet :
for line in f:
Print(line,end=””)
Output:
This file
readline()
Code snippet:
To open a file and read its first and second line using readline()
with open (“file_readline.txt”) as f:
Output:
readlines()
readlines() -> to read all lines from file and return it as list.
Code snippet :
With open(“file_sample.txt”) as f:
Print(f”f.readlines {f.readlines()}”)
Output:
Writeline()
writelines()
writelines() -> to read all lines from file and return it as list.
Python Iteration Statements
Iteration:
Iteration repeats the execution of a sequence of code. Iteration is useful for solving many
programming problems. Iteration and conditional execution form the basis for algorithm construction.
Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without
One form of iteration in Python is the while statement. Here is a simple program that counts down
from five.
Example:
iteration.py
n = 5
while n > 0:
print n
n = n-1
Note: For more details on while loop please goto python control flow.
• break
• continue
• Pass
In Python, break and continue statements can alter the flow of a normal loop.
Break Statements
The break statement terminates the loop containing it. Control of the program flows to the statement
Syntax:
break;
break_test.py
print("The end")
Output
s
t
r
The end
Continue Statement:
The continue statement is used to skip the rest of the code inside a loop for the current iteration only.
Loop does not terminate but continues on with the next iteration.
Syntax:
Continue;
continue_test.py
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Output
s
t
r
n
g
The end
Pass Statement:
Syntax:
Pass;
Example:
pass_test.py
Output
#no output pass is just a placeholder for functionality to be added later. So no output.
Note: pass is mostly used in defualt cases, where just for future handling a case is defined.
Python Tuples
A Tuple is same as lists used to store sequence of objects separated by comma enclosed with
parentheses. The value of items stored in the list can be mutable while the tuple is immutable. Tuple
max method:
Example:
t = (200,300,100,400)
print(max(t))
Output:
400
Comparing tuples
Example:
a=(5,2)b=(1,4)if (a>b):
print("a is bigger")
else:
print("b is bigger")
Output:
a is bigger
Length method:
Example:
t = (200,300,100,400)
print(len(t))
Output:
Indexing:
We can access the elements of tuple based on index value which starts from 0.
Example:
t = (200,300,100,400)
Print(t[0])
Output:
Slicing:
Example:
t = (200,300,100,400)
print(t[0:2])
print(t[2:4])
Output:
(200, 300)
(100, 400)
Constructing Tuples
For example:
Create a tuple
t = (1,2,3) u = 1.0+2j, 3.0+3j,"a","bb"
w = tuple()
print(type(t))
print(type(u))
print(type(v))
print(type(w))
<class 'tuple'="">
<class 'tuple'="">
<class 'tuple'="">
<class 'tuple'="">
w = u + v
print(w)
((1+2j), (3+3j), 'a', 'bb', 1, 1.0, (2+3j), 'a', ['aa', 'bb'], (1.0, 2.0,
3.0), {1, 2, 3}, {'a': 1})
v[0] = t + u
print( element ,type(element)) #the same can done with lists also.
a <class 'str'="">
bb <class 'str'="">
1 <class 'int'="">
a <class 'str'="">
TypeError
3 <class 'int'="">
False
Tuples have built-in methods, but not as many as lists do. Let’s look at two of them:
● Use .index to enter a value and return the index
● Use .count to count the number of times a value appears
print(t1.index('apple'))
print("count is {}".format(t1.count('apple')))
0
count is 2
Note:
len(zoo))
new_zoo = 'monkey', 'camel', zoo
len(new_zoo))
print('All animals in new zoo are', new_zoo)
len(new_zoo)-1+len(new_zoo[2]))
Output :
Number of animals in the zoo is 3
Number of cages in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python', 'elephant',
'penguin'))
Animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
Flow Control
Control flow (or alternatively, flow of control) refers to the specification of the order in which the
individual statements, instructions or function calls of a program are executed or evaluated. In order
Conditional Programming
Python provides conditional branching with if statements and looping with while and for statements.
Python also has a conditional expression—this is a kind of if statement that is Python’s answer to the
ternary operator (?:) used in C-style languages. Please find below example for the conditional flow of
statements.
values.
Conditional Operators
● > – Greater
● < – Lesser
● == – equal
● <= – Lesser or equal
● >= – Greater or equal
● != – Not equal
Boolean Operators
● True = 1
● False = 0
Logical Operators
It evaluates an expression and, based on the result, choose which part of the code to execute
(decision making is required when we want to execute code only if a certain condition is satisfied).
if boolean_expression1
Statement1
elif boolean_expression2:
Statement2
.
.
else:
Default Statement
There can be zero or more elif clauses and the final else clause is optional. In some cases, we
can reduce an if…else statement down to a single conditional expression.
In above example you can see that the program is dependent on the boolean_expression, If the
otherwise, the
result is expression2.
Syntax of if…elif…else:
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Flowchart of if…elif…else
Example 1: test1.py
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
if num == 0:
print ("Zero")
elif num > 0:
print (“Positive number”)
else:
(Create a file and copy above script and execute using python. Change the value of “num” and verify
different
combinations.)
Ternary operator
The short version of an if/else. When the value of a name is to be assigned according to some
condition, sometimes it’s easier and more readable to use the ternary operator instead of a proper if
clause. In the following example, the two code blocks do exactly the same thing:
Example :
print(order_total, discount)
Repetition Structures
A repetition structure causes a statement or set of statements to execute repeatedly. Two broad
In Python, you use the while statement to write a condition-controlled loop, and you use
Condition-Controlled Loop
The while loop gets its name from the way it works: while a condition is true, do some
task.
while condition :
Code block
(Or) statements
As a block, all the statements that comprise the block must be indented the same number of spaces
from the left. As with the if statement, the block must be indented more spaces than the line that
begins the while statement. The block technically is part of the while statement. The below example
natural_number_sum.py
# Program to add natural
# sum = 1+2+3+...+n
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
Infinite Loops
An infinite loop continues to repeat until the program is interrupted. If a loop does not have a way of
Example: Infinity.py
keep_going = ‘y’
Count-Controlled Loop
A count-controlled loop iterates a specific number of times. In Python, you use the for statement to
write a count-controlled loop. In Python, the for statement is designed to work with a sequence of
data
items. When the statement executes, it iterates once for each item in the sequence.
statement
Example: test_for.py
print(n)
Note: The expression range(1, 11) creates an object known as an iterable that allows the for loop to
assign
to the variable n the values 1, 2, . . . , 10. During the first iteration of the loop, n’s value is 1 within
Syntax:
range( begin,end,step )
where,
● begin is the first value in the range; if omitted, the default value is 0
● the end is one past the last value in the range; the end value may not be omitted
● change is the amount to increment or decrement; if the change parameter is omitted, it defaults
to 1
(counts up by ones).
● begin, end, and step must all be integer values; floating-point values and other types are not
allowed.
Example: simple_loop.py
print(num)
● What is RMO?
them?
performance?
shot at some interviews. To increase your chances of clearing them, here is a list of 20 Python
multithreading is to speed the code then using the package is not the go-to option.
The package has something called the GIL or Global Interpreter Lock, which is a construct. It
ensures that one and only one of the threads execute at any given time. A thread acquires the
GIL and then do some work before passing it to the next thread.
This happens so fast that to a user it seems that threads are executing in parallel. Obviously,
this is not the case as they are just taking turns while using the same CPU core. Moreover, GIL
Hence, if you intend to use the threading package for speeding up the execution, using the
Answer: In terms of functionality, both range and xrange are identical. Both allow for generating
a list of integers. The main difference between the two is that while range returns a Python list
Xrange is not able to generate a static list at runtime the way range does. On the contrary, it
creates values along with the requirements via a special technique called yielding. It is used
If you have a very enormous range for which you need to generate a list, then xrange is the
function to opt for. This is especially relevant for scenarios dealing with a memory-sensitive
requirement is gigantic. Hence, in creating an array of integers to suit the needs, it can result in
Answer: Inheritance enables a class to acquire all the members of another class. These
The class which acquires is known as the child class or the derived class. The one that it
acquires from is known as the superclass or base class or the parent class. There are 4 forms
superclass
Question: Explain how is it possible to Get the Google cache age of any URL or webpage using
Python.
Answer: In order to Get the Google cache age of any URL or webpage using Python, following
http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE
Simply replace URLGOESHERE with the web address of the website or webpage whose cache
Answer: The process of setting up a database is initiated by using the command edit
settings. Django relies on SQLite by default, which is easy to be used as it doesn’t require any
other installation.
SQLite stores data as a single file in the filesystem. Now, you need to tell Django how to use the
database. For this, the project’s setting.py file needs to be used. Following code must be added
to the file for making the database workable with the Django project:
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.sqlite3',
'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
If you need to use a database server other than the SQLite, such as MS SQL, MySQL, and
PostgreSQL, then you need to use the database’s administration tools to create a brand new
You have to modify the following keys in the DATABASE ‘default’ item to make the new
● NAME – Whether using SQLite or some other database management system, the
database is typically a file on the system. The NAME should contain the full path
NOTE: – Settings like Host, Password, and User needs to be added when not choosing SQLite
as the database.
Question: How will you differentiate between deep copy and shallow copy?
Answer: We use shallow copy when a new instance type gets created. It keeps the values that
are copied in the new instance. Just like it copies the values, the shallow copy also copies the
reference pointers.
Reference points copied in the shallow copy reference to the original objects. Any changes
made in any member of the class affects the original copy of the same. Shallow copy enables
Deep copy is used for storing values that are already copied. Unlike shallow copy, it doesn’t
copy the reference pointers to the objects. Deep copy makes the reference to an object in
addition to storing the new object that is pointed by some other object.
Changes made to the original copy will not affect any other copy that makes use of the
referenced or stored object. Contrary to the shallow copy, deep copy makes execution of a
program slower. This is due to the fact that it makes some copies for each object that is called.
Question: How will you distinguish between NumPy and SciPy?
Answer: Typically, NumPy contains nothing but the array data type and the most basic
operations, such as basic element-wise functions, indexing, reshaping, and sorting. All the
As one of NumPy’s most important goals is compatibility, the library tries to retain all features
supported by either of its predecessors. Hence, NumPy contains a few linear algebra functions
despite the fact that these more appropriately belong to the SciPy library.
SciPy contains fully-featured versions of the linear algebra modules available to NumPy in
A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]
print(A0,A1,A2,A3,A4,A5,A6)
Answer:
A0 = {‘a’: 1, ‘c’: 3, ‘b’: 2, ‘e’: 5, ‘d’: 4} # the order may vary
A1 = range(0, 10)
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
Question: Python has something called the dictionary. Explain using an example.
such as a map. Dictionary holds key:value pair. It helps in defining a one-to-one relationship
between keys and values. Indexed by keys, a typical dictionary contains a pair of keys and
corresponding values.
Let us take an example with three keys, namely Website, Language, and Offering. Their
corresponding values are hackr.io, Python, and Tutorials. The code for the example will be:
dict={‘Website’:‘hackr.io’,‘Language’:‘Python’:‘Offering’:‘Tutorials’}
print dict[Website] #Prints hackr.io
print dict[Language] #Prints Python
print dict[Offering] #Prints Tutorials
Question: Python supports negative indexes. What are they and why are they used?
Answer: The sequences in Python are indexed. It consists of the positive and negative numbers.
Positive numbers use 0 as the first index, 1 as the second index, and so on. Hence, any index for
Unlike positive numbers, index numbering for the negative numbers start from -1 and it
represents the last index in the sequence. Likewise, -2 represents the penultimate index. These
● Removing any new-line spaces from the string, thus allowing the string to except
Question: Suppose you need to collect and print data from IMDb top 250 Movies page. Write a
program in Python for doing so. (NOTE: – You can limit the displayed information for 3 fields;
Answer:
Answer: The output of the program will be “invalid code.” This is because a new exception class
Answer: The dynamic modifications made to a class or module at runtime are termed as
# m.py
class MyClass:
def f(self):
print "f()"
import m
def monkey_f(self):
print "monkey_f()"
m.MyClass.f = monkey_f
obj = m.MyClass()
obj.f()
Output for the program will be monkey_f().
The examples demonstrate changes made in the behavior of f() in MyClass using the function
Question: What do you understand by the process of compilation and linking in Python?
Answer: In order to compile new extensions without any error, compiling and linking is used in
Python. Linking initiates only and only when the compilation is complete.
In the case of dynamic loading, the process of compilation and linking depends on the style that
is provided with the concerned system. In order to provide dynamic loading of the configuration
setup files and rebuilding the interpreter, the Python interpreter is used.
Question: What is Flask and what are the benefits of using it?
Answer: Flask is a web microframework for Python with Jinja2 and Werkzeug as its
● Because there is a little external dependency to update and fewer security bugs,
list of the results. The value returned from the map() function can then be passed on to
Typically, the given function is the first argument and the iterable is available as the second
argument to a map() function. Several tables are given if the function takes in more than one
arguments.
Answer: The Pickle module in Python allows accepting any object and then converting it into a
string representation. It then dumps the same into a file by means of the dump function. This
The reverse process of pickling is known as unpickling i.e. retrieving original Python objects
Question: Whenever Python exits, all the memory isn’t deallocated. Why is it so?
Answer: Upon exiting, Python’s built-in effective cleanup mechanism comes into play and try to
However, Python modules that are having circular references to other objects or the objects that
are referenced from the global namespaces aren’t always deallocated or destroyed.
This is because it is not possible to deallocate those portions of the memory that are reserved
by the C library.
Question: Write a program in Python for getting indices of N maximum values in a NumPy
array.
Answer:
import numpy as np
arr = np.array([1, 3, 2, 4, 5])
print(arr.argsort()[-3:][::-1])
Output:
[4 3 1]
Question: Write code to show randomizing the items of a list in place in Python along with the
output.
Answer: