2. Sieve of Eratosthenes Algo.
SK Classes ….
(Sanjeev Kr. Kapoor, AP, KIET Group of
Institutions)
1. Define a list of consecutive integers from 2 to given
value of n: (2, 3, 4, …, n).
2. Start from first prime number 2 To find next prime
3. Move to p2 (Square of p)with increments of p
thereafter and mark/strike or delete every such
element till n.
4. Find the first number greater than Previous p in the
list that is not marked/striked/deleted.This is next
prime number. If there was no such number, stop.
5. Repeat from step 3 for next prime numbers
7. File Manipulation in
python
• Python too supports file handling and allows
users to handle files i.e., to read and write
files, along with many other file handling
options, to operate on files
• You can use a file to store data permanently
SK Classes ….
(Sanjeev Kr. Kapoor, AP, KIET Group of
Institutions)
8. Working of open() function
• We use open () function in Python to open a file in read or write mode. As
explained above, open ( ) will return a file object.
• The syntax being:
file_variable= open(filename, mode).
There are three kinds of mode, that Python provides and how files can be
opened:
• “ r “, for reading.
• “ w “, for writing.
• “ a “, for appending.
• “ x “, creates specified file returns error if file already exist.
• If not passed, then Python will assume it to be “ r ” by default
• "t" - Text - Default value. Text mode
• "b" - Binary - Binary mode (e.g. images)
• The default is reading in text mode. In this mode, we get strings when reading from the file.
9. example
• file = open('geek.txt', 'r')
• # This will print every line one by one in the
file
• for each in file:
• print (each)
10. Creating a file
• sales_file = open('sales.txt', 'w')
• File named sales.txt will be created
• Variable sales_file will reference a file object
that we can use to write data to the file
11. Specifying the Location of a File
• Suppose a current program is located in the
following folder on a
C:UsersBlakeDocumentsPython
• If you specify a different path in a string literal
(particularly on a Windows computer), be sure
to prefix the string with the letter r.
• E.g.:
test_file =
open('C:UsersBlaketemptest.txt', 'w')
12. The file object atrributes:
• One we open a file. An file object is
created and we can do number of things
on it.
• Here is a list of all attributes related to file
object:
• file.closed: True if file is closed,otherwise
return false
• file.mode: Returns access mode with which
file was opened
• file.name: Return name of the file.
13. • Example:
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
• This would produce following result:
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
14. Writing Data to a File
• Once we have opened a file in file object, we
can use this objects methods to perform
various operations like writing data.
• file_variable.write(string)
• If we write three names using above
statement separately
• File content: name1nname2nname3n
15. USE of Append Mode—
Example—
f = open("demofile.txt", "a")
f.write("This line is added at the end by write command")
f = open("demofile.txt", "r")
print(f.read( ))
f.close( )
USE of Write Mode—
f = open("demofile.txt", "w")
f.write("Sorry! the contents are deleted")
16. • Check if File exist:
• To avoid getting an error, we might want to check if the file exists before we try to delete it:
• Example
• Check if file exists, then delete it:
•
• import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete a File
To delete a file, we must import the OS module, and run its os.remove() function:
Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
17. Reading data from file
• Data can be read using open() function with read
mode. Content are read into memory as buffer
and referenced the file reference object.
• infile = open(‘filename.txt', 'r')
• Data= Infile.read() will read file content as a string
and will assign to corresponding variable.
• Read(optional numeric parameter)
• If we pass a number less than total number of
character in file. It will read only those many
character in the file. By default all characters are
read or we can pass -1 to read whole file.
18. readline()
• We can read the content of file line by line using
this function
• File_variable.readline() will read one line at a
time.
infile = open('philosophers.txt', 'r')
# Read three lines from the file.
line1 = infile.readline()
line2 = infile.readline()
line3 = infile.readline()
infile.close()
19. Read lines separately
• Syntax is
• f = open("demofile.txt", "r")
• print(f.readlines( ))
• OUTPUT—
•
• ['Hello World!n', 'This file is only for testing purpose.n', 'File handling in Python.n', 'All the
Best!!!’]
• (File content as list of lines)
• NOTE:
• 1. After performing any operations, we must close the file.
• f.close( )
• 2. By looping through the lines of the file, we can read the whole file, line by line:
• f = open("demofile.txt", "r")
for lines in f:
print(lines)
20. F.seek, F.tell
• Seek() used to change the position of file
handler/pointer to given position.
Sytax: f.seek(offset, from_what) from_what(0:
mode, 1 current, 2 Last accordingly offset could
be positive or negative in case of binary mode. )
Text mode ‘t’ only used from starting. And don’t
accept from_what argument.
• f.tell() gives the current location of file pointer.
21. Exceptions
• An exception is an error that occurs while a program is
running,
• It causes the program to abruptly halt.
• You can use the try/except statement to gracefully handle
exceptions.
• Exceptions are error scenarios that alter the normal
execution flow of the program
num1 = int(input('Enter a number: '))
num2 = int(input('Enter another number: '))
result = num1 / num2
print(num1, 'divided by', num2, 'is', result)
22. Handling Exceptions
• Python, like most modern programming
languages, allows you to write code that
responds to exceptions when they are raised,
and prevents the program from abruptly
crashing
• Such code is called an exception handler,
23. Accessing Exceptions:
You can access the exception object in the except block.
Try:
<body>
except ExceptionName:
<handler>
• If try suite raises an exception as specified in the except clause, then the
handler in the that except clause executes.
• Then, the program resumes execution with the statement immediately
following the try/except statement.
• Program will halt with a trace back error message if no exception name
matches
• Normal execution follow after except block/s if no error in occurs in try
block.
24. Example
• try:
• # Get the number of hours worked.
• hours = int(input('How many hours did you work? '))
• # Get the hourly pay rate.
• pay_rate = float(input('Enter your hourly pay rate: '))
• # Calculate the gross pay.
• gross_pay = hours * pay_rate
• # Display the gross pay
• print('Gross pay: $', format(gross_pay, ',.2f'), sep='')
• except ValueError:
• print('ERROR: Hours worked and hourly pay rate must')
• print('be valid integers.')
25. Standard Exceptions..
• EOFError
• Raised when there is no input from either the input() function or the end of file is reached.
• ImportError
Raised when an import statement fails.
• KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
• IndexError
Raised when an index is not found in a sequence.
• KeyError
Raised when the specified key is not found in the dictionary.
• NameError
• Raised when an identifier is not found in the local or global namespace.
26. Standard Exceptions
• UnboundLocalError
Raised when trying to access a local variable in a function or method but no value has been assigned to it.
• IOError
Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that
does not exist.
• OSError
Raised for operating system-related errors.
• SyntaxError
Raised when there is an error in Python syntax.
• IndentationError
Raised when indentation is not specified properly.
• TypeError
Raised when an operation or function is attempted that is invalid for the specified data type.
• RuntimeError
Raised when a generated error does not fall into any category.
27. Raising Exceptions
• You learned how to write the code to handle exceptions in the preceding
section.
• Where does an exception come from? How is an exception created?
• Exceptions are objects and objects are created from classes.
• An exception is raised from a function. When a function detects an error, it can
create an object of an appropriate exception class and raise the object, using the
following syntax:
raise ExceptionClass("Something is wrong")
Used with try,Except but can be used to raise the
customexception as well
28. Exception Handling Special cases.
try – except with else
Try-except with finally
Try-except-else-finally
30. Important Points
• With one try Clause we can have multiple
except clause indicating different exceptions
• Last except clause could be mentioned with
exception name to handle any leftover
exception.
• Multiple exception can be mentioned in one
except clause as coma separated tuple syntax
within parenthesis.
32. Assertion
• Some times while execution if we want to validate the
value of certain variables we can make use of assert
statement
• Its Equivalent to exception handling in general.
• Checks a condition if True normal execution is followed
if false raise the assertion error.
• We can also a mention a message if assertion fails.
General Syntax:
assert condition, Optional Message
33. Demo example
• a=10
• assert a>0,"Not allowed"
• print(a+9)
“Normal Execution”
OR
a=-1
assert a>0,"Not allowed"
print(a+9)
“Error” in this case and print the message ” Not allowed ”
34. Need of Assert
• Helps in validating the statement of code
during execution
• Used when you want to "stop" the script
based on a certain condition and return
something which help to debug faster
35. raise exception, assertion vs. try-
except
• Raise can be used for custom
exception, and can also be used re
raising the exception.
• Assertion is condition base,
• try-except is execution based.?
37. Modules In Python
• A module is a file consisting of Python code. A
module can define functions, classes and
variables.
• Increase reusability of same function in
various programs without writing their
definition again.
• You can use any Python source file as a
module by executing an import statement in
other python code
38. Module…
• So a module contain definitions and statements
• In python module file is saved with .py
• No need to mention .py while importing
• While importing module first searches the local
directory and then in the directory mentioned in
Path variable.
• Built in Module(os, numpy, math) vs. User
defined modules
• The dir() function usage
39. Importing Modules
• Importing Specific functions
• Importing all functions.
Describe the valid import statements
from module import function
Import module
Import *
from module import *
Import os *
40. __main__, __name__ special variable
SK Classes ….
(Sanjeev Kr. Kapoor, AP, KIET Group of
Institutions)
• In python we don’t have main function, by default
execution starts from zero indentation first statement
• But we have two special variable to identify main module
and imported module
• __main__, is default name assigned to __name__ variable
if code belongs to main program which we are running
• __name__ is assigned the name of imported module name
if the code of imported module is being executed.
41. Demo Example:- on Special variables
SK Classes ….
(Sanjeev Kr. Kapoor, AP, KIET Group of
Institutions)
File1.py# default is __main__
a=9
b=2
def sum(a,b):
print(__name__)
return (a+b)
File2.py
from file1 import *
print(a,b)
print(sum(2,4))
print(__name__)
If execute File2.py
43. Abstract Data Types
• Abstract Data type (ADT) is a type (or class) for objects
whose behavior is defined by a set of value and a set of
operations.
• The definition of ADT only mentions what operations are
to be performed but not how these operations will be
implemented
• It does not specify how data will be organized in memory
and what algorithms will be used for implementing the
operations.
• It is called “abstract” because it gives an
implementation-independent view.
• The user of data type does not need to know how that
data type is implemented
• E.g. we have been using Primitive values like int, float,
char
44. ADT operations.
Abstract data types can be viewed like black box. User
programs interact with instances of the ADT by
invoking one of the several operations defined by its
interface. The set of operations can be grouped into
four categories: ˆ
• Constructors: Create and initialize new instances of the
ADT. ˆ
• Accessors: Return data contained in an instance
without modifying it. ˆ
• Mutators: Modify the contents of an ADT instance. ˆ
• Iterators: Process individual data components
sequentially
45. Implementing ADTs: Towards OOPs
• Classes are the Python representation for “Abstract Data Types,”
• So we need to understand the OOPs concept of classes in python to
implement ADT.
• e.g. Stack if we consider as ADT. We need to understand what
operations it needs to perform:
1. Push(): To insert the element in stack list
2. Pop(): To delete the element from stack list
3. Create(): To create a stack
4. Isempty: To check whether stack empty or not
5. Size(): to Know size of stack
such signature of various operation on ADT under consideration are said
to interface to ADT.
So we need to understand OOPs concept in Python to Define and
implement ADT in Python
46. Major principles of object-oriented
programming system are given below.
• Class
• Object
• Method
• Inheritance
• Polymorphism
• Data Abstraction
• Encapsulation
47. Understanding Class and Objects in
Python
• Object oriented programming (OOP) is centered on
creating objects
• Python is actually object oriented every thing is object
in python.
• Object: An object is a software entity that contains
both data and procedures.
• Attributes: Data contained in an object is known as the
object’s data attributes.
• Methods: The procedures that an object performs are
known as methods
• Methods are functions that perform operations on the
object’s data attributes
48. Classes
• A class is code that specifies the data attributes and
methods for a particular type of object.
• Class could be considered as design of object/Blue print of
object/layout from which object can be created.
• The programmer determines the data attributes and
methods that are necessary, and then creates a class. This
class so created could be considered as ADT specification.
So a class is code that specifies the data attributes and
methods of a particular type of object
• Creating object called creating instance of the
class/blueprint
49. Defining Class in Python
Class
The class can be defined as a collection of objects. It is a logical entity
that has some specific attributes and methods. For example: if you
have an employee class, then it should contain an attribute and
method, i.e. an email id, name, age, salary, etc.
• Using class keyword
class ClassName:
<statement-1>
.
.
<statement-N>
50. Inheritance
• Simulates the real-world concept of inheritance.
It specifies that the child object acquires all the
properties and behaviors of the parent object.
• By using inheritance, we can create a class which
uses all the properties and behavior of another
class.
• The new class is known as a derived class or child
class, and the one whose properties are acquired
is known as a base class or parent class.
• It provides the re-usability of the code.
51. Polymorphism, Encapsulation
• Polymorphism contains two words "poly" and
"morphs". Poly means many, and morph means shape.
By polymorphism, we understand that one task can be
performed in different ways.
• Encapsulation is also an essential aspect of object-
oriented programming. It is used to restrict access to
methods and variables. In encapsulation, code and
data are wrapped together within a single unit from
being modified by accident.
• Data abstraction is achieved through Encapsulation
52. Creating classes in Python
class Employee:
id = 10
name = "Devansh"
def display (self):
print(self.id,self.name)
The self-parameter refers to the current instance of the class and
accesses the class variables
Creating an instance of the class
<object-name> = <class-name>(<arguments>)
Emp=Employee()
Emp.display()
53. Constructors in Python Class
• In Python, the method the __init__() simulates
the constructor of the class. This method is called
when the class is instantiated. It accepts the self-
keyword as a first argument which allows
accessing the attributes or method of the class
Constructors can be of two types.
1.Parameterized Constructor
2.Non-parameterized Constructor
54. def __init__(self):
self.items =
• The first method, which is named __init__, is defined, is
special method .
• __init__, which is automatically executed when an instance
of the class is created in memory.(double Underscore
before and after init indicates that it is system defined)
• __init__ is also called initializer method as it initialise object
data attributes.
• Immediately after an object is created in memory, the
__init__ method executes,
• The self parameter is automatically assigned the object that
was just created
• self.items = statement assigns any data to the items data
attribute belonging to the object that was just created
56. Code to Count the number objects
using constructor(Non-Parameterized
Constructor)
57. Stack Class / Blueprint: defining Class
with only methods
class Stack:
def __init__(self):
self.items = []
def IsEmpty(self):
return self.items == []
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def top(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)!
58. Access Specifier
• _underscore before variable name in class
attribute is protected members.(Non Fully
comparable with protected keyword of java)
• Leading Double Underscore, (Private
members)
• double underscore both side of class/Instance
variable
• Instance Variable vs. Class variable
60. Types of Variable and Methods in
OOP(Object Oriented Python)
• Instance variable vs. class variable/Static variable
• Instance Methods vs. Class methods vs. Static methods
64. Class method vs Instance Method
example
Decorator is function that
takes another function as
parameter,
add some functionality and
then returns. Functionality
is added without changing
original function definition.
65. Static method
• Neither related to object nor related to class
• i.e. Don’t required either self or cls keyword.
• Can be invoked through both object and class
but will give static output
66. Some special attributes of Class
Attributes Name Description
• __doc__ Document reference string of class
• __name__ Gives name Class name
• __module__ Module name in which class is defined
• __bases__ tuple of names of all the super classes
69. General Syntax of Class
inheritance
• In object-oriented programming, inheritance is used to
create an “is a” relationship among classes
• This allows you to extend the capabilities of a class by
creating another class
• Inheritance involves a superclass and a subclass
• The subclass inherits attributes and methods from the
superclass without need of rewriting them.
class superclass:
superclass attributes and methods
class subclass(superclass):
attributes and methods of subclass
77. Special methods on objects
Method(Comparison) Result
__lt__(self,other) self < other
__le__(self,other) self <= other
__gt__(self,other) self > other
__ge__(self,other) self >= other
__eq__(self,other) self == other
__ne__(self,other) self != other
3.14 Methods for Comparisons
Method Result
__add__(self,other) self + other
__sub__(self,other) self - other
__mul__(self,other) self * other
__div__(self,other) self / other
Method Description
__new__(cls [,*args [,**kwargs]])
A static method called to create a new
instance
__init__(self [,*args [,**kwargs]]) Called to initialize a new instance
__del__(self) Called to destroy an instance
__repr__(self)
Creates a full string representation of an
object
__str__(self) Creates an string representation
__cmp__(self,other)
Compares two objects and returns
negative, zero, or positi
78. Problem
• Write an efficient program to do bitwise
ANDing of two given binary numbers.
• Input:-1000111010101110011
101100001111101010101011
• Output file:- 000000000111000000100011
• and for other similar operations
80. • Write an efficient program to print the sum
of the individual digits of numbers from m to
n.
81. 1. a = int(input("From:-"));
2. b = int(input("Upto:-"));
3.
4. add = 0;
5. n = a;
6.
7. for i in range(a,b+1,1):
8. while n>0:
9. num=n%10
10. add=add+num
11. n=n//10
12. n = n+1
13. print("Total Sum:-",add)
82. • Write an efficient program to print the
reverse of a given numbers from m to n.
Input 978, 1000
84. • . Write an efficient program to find which
numbers from range m to n are perfect
numbers. A perfect number is a positive integer
that is equal to the sum of it divisors. However,
for the case of a perfect number, the number
itself is not included in the sum. For example
divisors of 6 are 1,2 and 3 and their sum is 6.
Input 1 500
Output 6 28 496