You are on page 1of 101

Inheritance Types

● 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

Multiple child class Inheritance:

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.C_Name=" puppy "

ch_A1. show_parent

ch_A1. show_child

object of dog

ch_A2=dog()

ch_A2.P_Name="cat"

ch_A2.C_Name=" puppy "

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

Multiple parent class Inheritance.

This Muliple class inheritance can be explained by program as follws.

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

called as Multilevel Inheritance.

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.M_Name=" puppy "

s1. show_ Family

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

is called as Call parent class constructor form child class Inheritance.

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 Exception Handling

● 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:

Exception Name Definition

Exception It is a class for all exceptions

It rises when next() method of an iterator


Stop iteration
does not point to any yield object

SystemExit Raised by sys.exit() function.

Base class for all built-in exceptions except


StandardError
StopIteration and SystemExit.

Base class for all errors that occur for


ArithmeticError
arithmetic calculation.

ImportError Raised when an import statement fails.


Raised when an index is not found in a
IndexError
sequence of list or tuple.

IOError
Raised when an input/ output operation fails,
such as the print statement etc….

Raised when there is an syntax error in


SyntaxError
script

Raised when indentation is not specified


IndentationError
correctly.

Raised when an operation or function is


TypeError attempted that is invalid for the specified
data type.

Raised when the built-in function for a data


ValueError type has the valid type of arguments, but the
arguments have invalid values specified.

Raised when a generated error does not


RuntimeError
comes into any category

Get Prepared for Python Interviews !

Examples for Exception Error:


How to Handle an Exception Error:

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

occurred previously or not.

Syntax:

Example:

Python Advanced topics

The Advance Python concepts contain the following topics as follows

● 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__()

Example 1: Iterator Values in array

mylist=("a","b","c")

mylis=iter(mylist)

print(next(mylis))

print(next(mylis))

print(next(mylis))

Example 2: Iterator Values in string

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))

Example 3: Iterator in loops

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

then it is called as Generator Function.

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

called in the statement.

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()

return self.name + self.mark

@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)

s1.gotmarks(''abc got 45 '')

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)

Become a Python Certified Expert in 25Ho

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

Hexa Decimal Number

The hexadecimal number variable called 16. if the python hexadecimal

value prefixed with “0x” or “0X”.

Syntax :

hex(x)
Parameters :
x - an integer number (int object)

Returns: Returns hexadecimal string.

Example :

print("hexadecimal data value form of 16"


+ hex(16))
print("The hexadecimal value"
"from the ascii value 'a' is " + hex(ord('a')))
print("The hexadecimal value form of 2.6 is "

+ 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.

Two terms used in Function are


1. Called Function
2. Callee Function

Called Function

Function definition is called function.

Callee Function

Function from where it is invoked is known as 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

with arguments and no return value:

In this type, we are passing arguments in caller function and value will pass in function

definition.Here we are not returning any value from function definition.


with arguments and with return value

In this type,we pass arguments in caller function and value will pass in function definition.Here we

are returning value from function definition.


Get Prepared for Python Interview !

without arguments and without return value:

In this type,we are not passing any arguments in caller function to function definition.Here we are

not returning any value from function definition.


without arguments and with return value:

In this type,we are not passing arguments in caller function to function definition.Here we are

returning value from function definition.


Multiple return values from Function definition:

In this,we are returning more than one values from function definition.
Python Classes and Objects

Python is an object oriented programming language it has the following features

Inheritance

derived class will inherit properties of base class or parent class

Polymorphism

● Based on type of objects their functionality will differ.


● Same function or method but based on type of objects their functionality will differ.
● It is achieved using function overloading and operator overloading.

Abstraction

Data hiding (Hiding of data )

Encapsulation

Wraping up of data and method (method will work on data )

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

methods are called instance methods.

Get Prepared for Python Interviews !

Objects:

In order to access variables and methods in class, need to create object for that class. Object is the

instance of the class.

Creating object for the class Employee as follow.

emp = Employee(‘Rajan’, ‘EM0001,’25000’,’1000’)

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

net_salaray = emp. get_net_salary()


In the same way, want to display details of the employee, need to call method

display_employee_detail() as follow. It will display of the details of employee

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.

It is possible to create any number of objects for single class as follow.

emp1 = Employee(‘Jothi’, ‘EM0002’,’65000’,’8000’)


emp2 = Employee(‘Mukesh’, ‘EM0003’,’44000’,’3000’)

emp3 = Employee(‘Rajan’, ‘EM004’,’35000’,’7000’)

Python String
Strings are represented as collection of characters. It is immutable. We can represent single quotes

or double quotes to represent strings.

To use multi-line char’s, we use triple quotes to represent strings.

Example:

str = input(“enter your programming language”)

print(str)

The above example gets input string from user and prints it. Python version 2, we use raw_input

method instead of input()

Consider a string,

str = “python”
we can use slicing to extract each char’s.

Example:

str[0] #p

str[0:2] #py

Let’s understand the basic methods in brief

1. capitalize()
Converts first char in to capital letter.

Example:

str = “python”

print(str.capitalize())

Output:

Python

2. Center()

It returns a string which is padded with the specified character.

Example

str = “python”

print(str.center(15,’*’))

output:
*****python****

3. count()

Count the occurrences or substring in a string.

Example:

str = ‘python is very easy to learn’

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

Similarly, you can try upper().

5. startswith()

Checks the given char is starting in the specified string.

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

Similarly you can use rfind() to check from right side.

7. format()

formats the given string.

Example:

print(“{0} is {1} to learn program”.format(‘python’,’easy’))

Output:
python is easy to learn program

8. index()

Returns the index position of the given string.

Example:

str = “python”

print(str.index(‘p’))

Output:

You can access in for loop,


Example:

for i in str:

print(str.index(i))

Output:

9. strip()

Removes both left side and right side whitespaces.


Example:

str = “ this is easy to learn “

print(str.strip())

Output:

this is easy to learn.

If you want to remove only left side, lstrip() is used.

rstrip() is used for right side removing whitespaces.

10. title()

It converts all the char’s first starting letter into capital letter.

Example:

str = “hi python”

print(str.title())
Output:

Hi Python

11. isalnum ()

It checks the string contains either alphabets or numbers.

12. isupper()

checks the given string is upper case or not. similarly, you can find islower().

13.Casefold

case fold – Converts all the characters to lower

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

myencodedstring = “I Ã¥m leărn\\ing PythÅ on”

print(myencodedstring.encode(encoding = ‘ascii’, errors =

‘backslashreplace’))

print(myencodedstring.encode(encoding = ‘ascii’, errors = ‘ignore’))

print(myencodedstring.encode(encoding = ‘ascii’, errors = ‘namereplace’))

print(myencodedstring.encode(encoding = ‘ascii’, errors = ‘strict’))

print(myencodedstring.encode(encoding = ‘ascii’, errors = ‘replace’))

print(myencodedstring.encode(encoding = ‘ascii’, errors =

‘xmlcharrefreplace’))

print(“\n”)

print(myencodedstring.encode(encoding = ‘cp437’, errors =


‘backslashreplace’))

print(myencodedstring.encode(encoding = ‘cp437’, errors = ‘ignore’))

b’I \x86m le\\u0103rning Pyth\\u0160on’

b’I \x86m lerning Python’

b’I \\N{LATIN SMALL LETTER A WITH RING ABOVE}m le\\N{LATIN SMALL LETTER A

WITH BREVE}rning Pyth\\N{LATIN CAPITAL LETTER S WITH CARON}on’

b’I ?m le?rning Pyth?on’

b’I &#229;m le&#259;rning Pyth&#352;on’

15.Endswith
Example:

infotext = “Welcome to Python”

print(infotext.endswith(“Python”))

print(infotext[0:7])

print(infotext.endswith(“Welcome”,0,7))

print(infotext[2:8])

print(infotext.endswith(“Welcome”,2,8))

infotext1 = “Welcome to Python ”

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 tomy world2

welcome to my world3

Hello

Hello

Hello

Hello

Hello

Hello

Hello

17.Split
Example

Fruits = “apple,orange, grapes, guava, pineapple”

#Split(“characterseparator”,max) max -maximum no of times to split

AllFruits = Fruits.split(“,”)

print(AllFruits)

ThreeFruits = Fruits.split(“,”,2)

print(ThreeFruits)

[‘apple’, ‘orange’, ‘ grapes’, ‘ guava’, ‘ pineapple’] [‘apple’, ‘orange’, ‘ grapes, guava, pineapple’]

18.Isalpha,Isdecimal

Alpha, Alphanumeric and Decimal Checking


Example

myalpha =”abcd” #contains characters [a-zA-Z] myalphanumeric = “abcdef123” #contains

characters [a-zA-Z0-9] mynotalphanumeric= “&abcdef123″ # Not fitting all three cases (Contain

symbol)

mydecimal =”123” #contains characters [0-9] print(“myalpa string is alpha –

{}”.format(myalpha.isalpha()))

print(“myalphanumeric string is alpha –

{}”.format(myalphanumeric.isalpha()))

print(“mynotalphanumeric string is alpha –

{}”.format(mynotalphanumeric.isalpha()))

print(“mydecimal string is alpha – {}”.format(mydecimal.isalpha()))

print(“\n”)

print(“myalpa string is alphanumeric – {}”.format(myalpha.isalnum()))

print(“myalphanumeric string is alphanumeric –


{}”.format(myalphanumeric.isalnum()))

print(“mynotalphanumeric string is alphanumeric –

{}”.format(mynotalphanumeric.isalnum()))

print(“mydecimal string is alphanumeric – {}”.format(mydecimal.isalnum()))

print(“\n”)

print(“myalpa string is decimal – {}”.format(myalpha.isdecimal()))

print(“myalphanumeric string is decimal –

{}”.format(myalphanumeric.isdecimal()))

print(“mynotalphanumeric string is decimal –

{}”.format(mynotalphanumeric.isdecimal()))

print(“mydecimal string is decimal – {}”.format(mydecimal.isdecimal()))

Output
myalpa string is alpha – True

myalphanumeric string is alpha – False

mynotalphanumeric string is alpha – False

mydecimal string is alpha – False

myalpa string is alphanumeric – True

myalphanumeric string is alphanumeric – True

mynotalphanumeric string is alphanumeric – False

mydecimal string is alphanumeric – True

myalpa string is decimal – False

myalphanumeric string is decimal – False

mynotalphanumeric string is decimal – False

mydecimal string is decimal – True

19.Substring
Example

#: stands for sequence

#[] stands for the position holders

#value before the : is the start sequence, after the colon is the end

sequence

# start: end: step

TestString = “Hello Python”

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

Python can process two types of files

● Text file (default)


● Binary file

Text file:

A text file is nothing but which is containing alphabates,numbers,symbols,no specific formatings it is

called Text file.

Text file contains alphabets , numbers , symbols.

Binary file:

File not readable by human and understandable by machines.

To Open File:

File is opened using open() and it will return file descriptor.

Listed down modes available to open a file


F = open(“test_sample.txt”) #to open file in current directory

F= open(“D:/Documents:/README.txt”) #specifying full path

By default file will be opened in read mode in text format

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:

images or exe files)

Mode Description

Open a file for reading .If file is not found in

specified path ‘FileNotFound’ Exception will


‘r’
be raised.

Open a file for writing . If file is not found in

specified path , it will create new file .If file is

already found in that path , it truncates the file


‘w’
(it will delete all contents from file and will

write from beginning of the file).

Open a file for exclusive creation .If file is not


‘x’
found , it will create new file .If file already

exists it won’t truncate the file instead it will


throw error ‘FileExistsError’.

Open a file in append mode . If file is not

found , it will create new file . If file is already


‘a’ present , file pointer will be moved to the end

of the file to perform append operation.

Open a file for reading and writing . If file is

not found , it will create new file .If file is

already present the file content will get


‘w+’
truncated and opened for reading and writing

purpose.

Open a file for reading and writing . If file is

not found , it will create new file .If file is

already present the file content will get


‘r+’
truncated and opened for reading and writing

purpose.

Open a file for appending and reading . If file

is not found , it will create new file .If file is

found already , the new contents will get


‘a+’ appended to the already existing content in

the file (the older contents in file won’t get

truncated).
Open a file in binary mode for writing content

to file .If file is not found ,a new binary file will


‘wb’ get created .If file is already found , it will get

truncated.

Open a file in binary mode for reading

contents from the file .If file is not found

,FileNotFoundError will be raised .If file is


‘rb’
found , it would be used for reading contents

from the file.

Open a file in binary mode for appending

contents to the file .If file is not found , it will

create new file .If file is already found , the


‘ab’
newer data will get appended to the already

existing content in the file.

Open a file in binary mode for reading and

writing contents to the file It will create new

file , if file is not found .If file is found ,it will


‘wb+’
truncate the content of file and will be used for

reading and writing contents.

F = open(“sample_new.txt”) #this as well as mode = ‘r’ both are similar

F= open(“sample_new”,’w’) #performs write operation in text file


F= open(“animal.bmp”,’r+b’) #performs read and write in binary file

Get Prepared for Python Interviews !

To close file:

f.close() ->to perform file close operation

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

disk (this happens only if the file is closed properly)

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

operations and file is not closed properly.

Better way to achieve this

f = open(“msg.txt”,”w”)

try :

f.write(“Good morning”)

Finally:

f.close()
Writing into a file using write()

Writing into a file is achieved using ‘x’ ,’a’,’w’,’r+’ modes

Return value :Number of bytes written

Code snippet:

with open(“sample_new.txt”,mode=’w’,encoding = ‘utf-8’) as fp:

fp.write(“This is first line\n”)

fp.write(“This is second line”)

fp.write(“This is third line”)

’sample_new.txt’ will get created if it does not exist. If it does exist, it is overwritten , the old content

will be truncated

Reading a file using read()

Code snippet:

F=open(“sample_new.txt”,encoding=’utf-8’)

F.read(4) #reads first 4 bytes —>’This’

F.read(4) #reads next 4 bytes –>’ is ’

F.read() #reads the entire content of file from current file pointer

First line

This is second line

This is third line


F.read() #further reading returns empty string

Moving File point cursor to required location

tell ->returns current file pointer location

Seek(from_what,offset) ->moves file pointer to the location specified

tell() Returns the current position of file pointer

Moves the file pointer to from_what position

seek(from_what,offset) and then move file pointer to offset mentioned

bytes from the file pointer position

f.seek(from_what,offset)

Possible values of from_what

0 ->moves file pointer to begging to file

1 ->moves file pointer to current location

2 ->moves file pointer to end of file

It will move the file pointer to the location based of from_what value and from there file pointer will be

moved to number of bytes mentioned as offset.

Example :

f.seek(0,10)
->from starting of file , file pointer f will be moved 10 bytes

f.seek(1,10)

->from current file pointer will be moved 10 bytes

f.tell() ->to get the exact bytes where the file pointer is currently available

To read file contents line by line

Reading a file line by line using for loop

Code Snippet :

with open (“file_context.txt”) as f:

for line in f:

Print(line,end=””)

Output:

This is my first line

This file

Contains three lines

readline()

readline() will read a single line from current file pointer.

Code snippet:

To open a file and read its first and second line using readline()
with open (“file_readline.txt”) as f:

print(f”File first line {f.readline()}”)

print(f”File second line {f.readline()}”)

Output:

File first line This is first line

File second line This is second line

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:

[“This is first line”,”This is second line”,”This is third line”]

Writeline()

To write a single line to the file.

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

making errors is something that computers do well.

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

print(“iterated trough 5 values”)

Note: For more details on while loop please goto python control flow.

Iteration statements can be controlled by the following keyword:

• 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

immediately after the body of the loop.

Syntax:

break;

Flow Chart For Break Statements


Example:

break_test.py

for val in "string":


if val == "i":
break
print(val)

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;

Flow chart for Continue Statements


Example:

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:

In Python programming, pass is a null statement.

Syntax:

Pass;

Example:

pass_test.py

sequence = {'p', 'a', 's', 's'}


for val in sequence:
pass

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

is mainly used for to protect data.

Methods of Tuple in Python

max method:

Example:

t = (200,300,100,400)

print(max(t))

Output:

400

Comparing tuples

We can compare two tuples with relational operators.

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:

200 (the first element)

Slicing:

We can access a range of elements from a tuple by using colon (:).

Example:

t = (200,300,100,400)
print(t[0:2])

print(t[2:4])

Output:

(200, 300)

(100, 400)

Constructing Tuples

The construction of tuples uses () with elements separated by commas.

For example:

Create a tuple
t = (1,2,3) u = 1.0+2j, 3.0+3j,"a","bb"

#mixed type of objects v = (1,1.0,2.0+3.0j,"a",["aa","bb"],(1.0,2.0,3.0),


{1,2,3},{"a":1})#mixed type of objects with parenthesis enclosure

w = tuple()

print(type(t))

print(type(u))

print(type(v))

print(type(w))

<class 'tuple'="">

<class 'tuple'="">

<class 'tuple'="">

<class 'tuple'="">

create another tuple from existing tuples u and v

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})

Doesnt’ support item assignment

v[0] = t + u

TypeError Traceback (most recent call last) in () —-> 1 v[0] = t + u


TypeError: ‘tuple’ object does not support item assignment

lets verify the datatype for the above for element in w:

print( element ,type(element)) #the same can done with lists also.

(1+2j) <class 'complex'="">

(3+3j) <class 'complex'="">

a <class 'str'="">

bb <class 'str'="">

1 <class 'int'="">

1.0 <class 'float'="">

(2+3j) <class 'complex'="">

a <class 'str'="">

['aa', 'bb'] <class 'list'="">

(1.0, 2.0, 3.0) <class 'tuple'="">

{1, 2, 3} <class 'set'="">

{'a': 1} <class 'dict'="">

creating tuple from another tuple

#Slicing is supported print(t[1])

Indexing u[2] = "aa"

TypeError

Traceback (most recent call last) in ()


print(t[1])

Indexing ----> 4 u[2] = "aa"

TypeError: 'tuple' object does not support item assignment

The tuple contains nested tuples

t1 = ("apple", 3, 1.4, ("banana", 5))

for element in t1: print( element ,type(element))

apple <class 'str'="">

3 <class 'int'="">

1.4 <class 'float'="">

('banana', 5) <class 'tuple'="">

● check the membership of an element in a tuple


● in operation is used to check the membership
● membership is true if the value is present else false

t1 = ("apple", "banana", "cherry","apple")


print( "banana" in t1 )
print( "orange" in t1 )
print( "banana" not in t1 )
True
False

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:

● I would recommend always using parentheses


● to indicate start and end of tuple
● even though parentheses are optional.
● Explicit is better than implicit.

zoo = 'python', 'elephant', 'penguin'

print('Number of animals in the zoo is',

len(zoo))
new_zoo = 'monkey', 'camel', zoo

print('Number of cages in the new zoo is',

len(new_zoo))
print('All animals in new zoo are', new_zoo)

print('Animals brought from old zoo are', new_zoo[2])

print('Last animal brought from old zoo is', new_zoo[2][2])

print('Number of animals in the new zoo is',

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

Number of animals in the new zoo is 5

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

to control the flow of a program, we have conditional programming and looping.

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.

Flowchart for conditional execution of statements


In the above flow chart, it shows a control flow of statements based upon the given inputs of x and y

values.

Conditional Operators

● > – Greater
● < – Lesser
● == – equal
● <= – Lesser or equal
● >= – Greater or equal
● != – Not equal

Boolean Operators

● True = 1
● False = 0

Logical Operators

● and – logical AND operation


● or – logical OR operation

If …elif…else Conditional Statements

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).

Please find below example:

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.

The syntax for a conditional expression is:

expression1 if boolean_expression else expression2

In above example you can see that the program is dependent on the boolean_expression, If the

boolean_expression evaluates to True, the result of the conditional expression is expression1;

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

In below example we are going to validate a numerical value using 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:

print ("Negative number")

(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 :

ternary.py # python script


order_total = 247
# classic if/else form
if order_total > 100:
discount = 25
else:
discount = 0
print(order_total, discount)
# ternary operator
discount = 25 if order_total > 100 else 0

print(order_total, discount)

Repetition Structures
A repetition structure causes a statement or set of statements to execute repeatedly. Two broad

categories of loops: condition-controlled and count-controlled.

● A condition-controlled loop uses a true/false condition to control the number of


times that it repeats.
● A count-controlled loop repeats a specific number of times.

In Python, you use the while statement to write a condition-controlled loop, and you use

the for the statement to write a count-controlled loop.

Condition-Controlled Loop

The while loop gets its name from the way it works: while a condition is true, do some

task.

The loop has two parts

● A condition that is tested for a true or false value


● A statement or set of statements that is repeated as long as the condition is true.

Flowchart for Condition Controlled Loop


In the above figure you can identify the logic of a while loop.

The while statement has the general form:(SYNTAX)

while condition :
Code block

(Or) statements

● The reserved word “while” begins the while statement.


● The “condition” determines whether the body will be (or will continue to be) executed.
● A colon (:) must follow the condition.
● Code bloc is a block of one or more statements to be executed as long as the condition is true.

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

will give the usage of while.


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

print("The sum is", sum)

Infinite Loops

An infinite loop continues to repeat until the program is interrupted. If a loop does not have a way of

stopping, it is called an infinite loop. Please find the below example:

Example: Infinity.py

# This program demonstrates an infinite loop.

# Create a variable to control the loop.

keep_going = ‘y’

# Warning! Infinite loop!

while keep_going == ‘y’:

# Get a salesperson’s sales and commission rate.

sales = float(input(‘Enter the amount of sales: ‘))


comm_rate = float(input(‘Enter the commission rate: ‘))

# Calculate the commission.

commission = sales * comm_rate

# Display the commission.

print(‘The commission is $’.format(commission, ‘,.2f’), sep=’ ‘)

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.

Here is the general format: SYNTAX

for variable in [value1, value2, etc.]:


statement

statement

Flow chart of “for” loop:


The for statement iterates over a range of values. These values can be a numeric range, or, as we

shall, elements of a data structure like a string, list, or tuple.

Example: test_for.py

for n in range(1, 11):

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

the block. In the loop’s second iteration, n has the value of 2.


The general form of the range function

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

# This program demonstrates a simple for loop


# that uses a list of numbers.
print('I will display the numbers 1 through 5.')
for num in [1, 2, 3, 4, 5]:

print(num)

What Is a Virtual Environment?


At its core, the main purpose of Python virtual environments is to create an
isolated environment for Python projects. This means that each project can
have its own dependencies, regardless of what dependencies every other
project has.
is used to manage Python packages for different projects. Usingvirtualenv allows you
to avoid installing Python packages globally which could break system tools or other
projects. You can install virtualenv using pip

Connect mysql to django.(127.0.0.1)


Go to settings.py then to the DATABASE key ,then modify django.db.backends.nme of
database.
Modify the dictionary to the name of the database, then user to root, and password of
the mysql database, then add host to localhost, and port to 3306 . standard port that
mysql runs on

Then finally run migrate command.


Navigate to project folder in cmd.
Then write
Python manage.py migrate. This command keeps track of all the changes in database
settings in project, and keeps the database in sync with the settings and models files

● What is the Python Standard Library? What are some of the

useful Standard Library modules?

● What styles of inheritance does Python have?

● What is RMO?

● How does Django work?

● Explain the MVC pattern in Django. What’s peculiar about the

MVC model in Django?

● What key features are available in Django?

● How are requests and responses processed in Django?

● What are Django middlewares and when should you use

them?

● What databases does Django support?

● How do you set up a database in Django?


● What does Django use field class types for?

● What’s the Django ORM?

● What ways of optimizing database queries using the Django

ORM do you know?

● How do you customize features of the admin interface?

● What are Django-admin.py and manage.py? What’s the

difference between them?

● How do you set up static files in Django?

● What styles of inheritance are there in Django?

● What caching techniques can you use to improve Django

performance?

● What command line is used to load data into Django?

● What is the session framework used for?

● What are Django signals? What are their key components?

● How do you decide where to go with packages, when to

optimize them, and when to write code from scratch?

Python Interview Questions


Once you’ve had enough understanding of the various concepts of Python, it’s time to give a

shot at some interviews. To increase your chances of clearing them, here is a list of 20 Python

interview questions that you must know answers to:

Question: Describe how multithreading is achieved in Python.


Answer: Even though Python comes with a multi-threading package, if the motive behind

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

passing adds to the overall overhead to the execution.

Hence, if you intend to use the threading package for speeding up the execution, using the

package is not recommended.

Question: Draw a comparison between the range and xrange in Python.

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

object, xrange returns an xrange object.

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

with a type of object known as generators.

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

system, such as a smartphone.


The range is a memory beast. Using it requires much more memory, especially if the

requirement is gigantic. Hence, in creating an array of integers to suit the needs, it can result in

a Memory Error and ultimately lead to crashing the program.

Question: Explain Inheritance and its various types in Python?

Answer: Inheritance enables a class to acquire all the members of another class. These

members can be attributes, methods, or both. By providing reusability, inheritance makes it

easier to create as well as maintain an application.

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

of inheritance supported by Python:

● Single Inheritance – A single derived class acquires from on single superclass.

● Multi-Level Inheritance – At least 2 different derived classes acquire from two

distinct base classes.

● Hierarchical Inheritance – A number of child classes acquire from one

superclass

● Multiple Inheritance – A derived class acquires from several superclasses.

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

URL format is used:

http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE
Simply replace URLGOESHERE with the web address of the website or webpage whose cache

you need to retrieve and see in Python.

Question: Give a detailed explanation about setting up the database in Django.

Answer: The process of setting up a database is initiated by using the command edit

mysite/setting.py. This is a normal Python module with a module-level representation of Django

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

database for your Django project.

You have to modify the following keys in the DATABASE ‘default’ item to make the new

database work with the Django project:


● ENGINE – For example, when working with a MySQL database replace

‘django.db.backends.sqlite3’ with ‘django.db.backends.mysql’

● 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

to the file, including the name of that particular file.

NOTE: – Settings like Host, Password, and User needs to be added when not choosing SQLite

as the database.

Check out the advantages and disadvantages of Django.

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

faster execution of the program.

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

numerical code resides in SciPy.

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

addition to several other numerical algorithms.

People Also Read:

● NumPy Matrix Multiplication

Question: Observe the following code:

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)

Write down the output of the code.

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]

A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

Question: Python has something called the dictionary. Explain using an example.

Answer: A dictionary in Python programming language is an unordered collection of data values

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

a positive number n is n-1.

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

are known as negative indexes. Negative indexes are used for:

● Removing any new-line spaces from the string, thus allowing the string to except

the last character, represented as S[:-1]

● Showing the index to representing the string in the correct order

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;

namely movie name, release year, and rating.)

Answer:

from bs4 import BeautifulSoup


import requests
import sys
url = 'http://www.imdb.com/chart/top'
response = requests.get(url)
soup = BeautifulSoup(response.text)
tr = soup.findChildren("tr")
tr = iter(tr)
next(tr)
for movie in tr:
title = movie.find('td', {'class': 'titleColumn'} ).find('a').contents[0]
year = movie.find('td', {'class': 'titleColumn'} ).find('span', {'class':
'secondaryInfo'}).contents[0]
rating = movie.find('td', {'class': 'ratingColumn
imdbRating'} ).find('strong').contents[0]
row = title + ' - ' + year + ' ' + ' ' + rating
print(row)
Question: Take a look at the following code:
try:
if '1' != 1:
raise "someError"
else:
print("someError has not occured")
except "someError":
print ("someError has occured")

What will be the output?

Answer: The output of the program will be “invalid code.” This is because a new exception class

must inherit from a BaseException.

Question: What do you understand by monkey patching in Python?

Answer: The dynamic modifications made to a class or module at runtime are termed as

monkey patching in Python. Consider the following code snippet:

# m.py
class MyClass:
def f(self):
print "f()"

We can monkey-patch the program something like this:

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

we defined i.e. monkey_f() outside of the module m.

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

dependencies. As such, it has some notable advantages:

● Flask has little to no dependencies on external libraries

● Because there is a little external dependency to update and fewer security bugs,

the web microframework is lightweight to use.

● Features an inbuilt development server and a fast debugger.

Question: What is the map() function used for in Python?


Answer: The map() function applies a given function to each item of an iterable. It then returns a

list of the results. The value returned from the map() function can then be passed on to

functions to the likes of the list() and set().

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.

Question: What is Pickling and Unpickling in Python?

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

process is known as pickling.

The reverse process of pickling is known as unpickling i.e. retrieving original Python objects

from a stored string representation.

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

deallocate or destroy every other object.

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:

from random import shuffle


x = ['hackr.io', 'Is', 'The', 'Best', 'For', 'Learning', 'Python']
shuffle(x)
print(x)
Output:

['For', 'Python', 'Learning', 'Is', 'Best', 'The', 'hackr.io']

You might also like