Professional Documents
Culture Documents
i += 2
# Driver Code
if __name__ == "__main__":
n = 100
SieveOfEratosthenes(n)
for i in range(1, n+1) :
if (i == 2) :
print( i, end = " ")
elif (i % 2 == 1 and Primes[i // 2] == 0) :
print( i, end = " ")
Example
What are all prime numbers less than 20. (Use the Sieve of
Eratosthenes method).
Solution: Let us first write the numbers from 2 to 20.
2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
•Start from 2
•In the next step, encircle 2 and cross the multiples of 2 (4, 6, 8, 10, 12, 14, 16, 18, 20)
•Encircle 3 and cross the left multiples of 3 (9, 15)
•Encircle 5 and cross the left multiples of 5 (only 10 is left)
•Now, encircle the rest of the numbers 7, 11, 13, 17 and 19.
Therefore, the required prime numbers between 1 to 20 are 2, 3, 5, 7, 11,
13, 17 and 19.
Fill all prime numbers less than or equal to 30.
Solution
•Step 1: The first step is to list all the numbers.
2, 3, 4, 5, 6 ,7 ,8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, and 30.
•Step 2: Write in bold all multiples of 2, except 2 itself.
2, 3, 4, 5, 6 , 7 , 8, 9, 10,11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, and 30.
•Step 3: The next unshaded number is 3. Write its square (32 = 9) in bold.
2, 3, 4, 5, 6 , 7 , 8, 9, 10,11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, and 30.
•Step 4: Now the third unshaded number is 5. Write its square 52=25 in bold.
2, 3, 4, 5, 6 , 7 , 8, 9, 10,11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, and 30.
•Step 5: The fourth unshaded number is 7 and more than the square root of 30.
Therefore, there are no multiples of 7 left since they have been eliminated by 2 and 3 as 14,
28, and 21 respectively. The remaining numbers 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29 are
prime.
File Handling
• Python has several functions for creating, reading, updating, and deleting files.
• The key function for working with files in Python is the open() function.
• The open() function takes two parameters; filename, and mode.
Syntax
f= open("demofile.txt")
Note: To open a file for reading it is enough to specify the name of the file:
File Handling
There are four different methods (modes) for opening a file:
• "r" -Read-Default value: Opens a file for reading, error if the file does not exist
• "a" –Append: Opens a file for appending, creates the file if it does not exist
• "w" – Write: Opens a file for writing, creates the file if it does not exist
• "x" –Create: Creates the specified file, returns an error if the file exist
In addition you can specify if the file should be handled as binary or text mode
By default the read() method returns the whole text, but you can also specify how
many characters you want to return:
Example:
f= open("demo.txt", "r")
print(f.read(6))
OUTPUT:
python
Read Line:
You can return one line by using the readline() method.
Example:
f= open("demofile.txt", "r")
print(f.readline())
File Handling
Close Files: Write to an Existing File¶
It is a good practice to always close the file To write to an existing file, you must add a
when you are done with it parameter to the open() function:
• "a" -Append-will append to the end of the
Example: file
• "w" -Write-will over write any existing
f= open("demofile.txt", "r") content
print(f.readline())
f.close()
Example:
f= open("demofile1.txt", "a")
f.write("Now the file has more content!")
f.close()
f= open("demofile1.txt", "r")
print(f.read())
Delete a File
To delete a file, you must import the OS
Check if File exist:
module, and run its os.remove() function
• To avoid getting an error, you might
want to check if the file exists before
Example: you try to delete it:
import os • Example
os.remove("demofile2.txt") • Check if file exists, then delete it:
Delete Folder
Example:
To delete an entire folder, use the
os.rmdir() method:
import os
if os.path.exists("demofile2.txt"):
#Example os.remove("demofile2.txt")
#Remove the folder"myfolder": else:
import os print("The file does not exist")
os.rmdir(“myfolder")
Exception Handling
• When an error occurs, or exception as we call it, Python will normally stop
and generate an error message.
• An exception is an unexpected event that occurs during program execution.
For example.
• divide_by_zero = 7 / 0
• The above code causes an exception as it is
not possible to divide a number by 0
• Errors that occur at runtime (after passing the syntax test) are called exceptions
or logical errors.
For instance, they occur when we
•try to open a file(for reading) that does not exist (FileNotFoundError)
•try to divide a number by zero (ZeroDivisionError)
•try to import a module that does not exist (ImportError) and so on.
Important Terms
• try
• except
• else
• finally
Python try...except Block
try: Example:
# code that may cause exception try:
except: numerator = 10
# code to run when exception occurs denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
Error: Denominator cannot be 0.
Catching Specific Exceptions in Python
• For each try block, there can be zero or more except blocks.
Multiple except blocks allow us to handle each exception
differently.
• The argument type of each except block indicates the type of
exception that can be handled by it. For example,
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
Python try with else
Example:
# program to print the reciprocal of even
numbers
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)
OUTPUT:
Enter a number: 3 Not an even number!
Python try...finally
• In Python, the finally block is always executed no matter whether there is an
exception or not.
• The finally block is optional. And, for each try block, there can be only one finally
block.
Let's see an example,
Example:
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block.")
What is a Module
For example:
import math
• Imports the math built-in module
• A module is a file with the extension .py and contains executable
Python or C code
• A file containing a set of functions you want to include in your
application.
• It is the smallest piece of software. It is set of methods/functions
ready to be used somewhere else.
Types of Modules in Python
Built-in Modules in Python User-defined Modules in Python
The user-define model is written by the user at
• math module the time of program writing
• os module
• random module How to create a user-define module?
• datetime module To create a module just write a python code in a
file with file extension as .py
Example:
def greeting(name):
print("Hello, " + name)
Abstract Data Types define the conceptual framework for 'what' needs to be accomplished but
leaves the 'how' of it all up to developers. In this way, ADTs are very much like upper
management—complete with a lack of regard for your personal time.
Characteristics of ADTs
• Encapsulates a Data Type and set of operations to manipulate the Type
• Operations are only defined by inputs and outputs
• Operation details are hidden from the user through encapsulation
• Theoretical in nature
• Define what is getting done not how it is getting done
• Allows internal implementation details to change without
ADT operations
Classes and Objects
class <Classname>:
Class data
data1 = value1
attributes
...
dataM = valueM
def <function1>(self,arg1,...,argK):
Class
<block>
...
member
functions
def <functionN>(self,arg1,...,argK):
<block>
Instances of Classes
instances.
Each object instance takes on the properties of the class from which it was
created.
Instances of Classes
Creating Classes
class <Classname>:
Class data
data1 = value1
attributes
...
dataM = valueM
def <function1>(self,arg1,...,argK):
Class
<block>
...
member
functions
def <functionN>(self,arg1,...,argK):
<block>
Defining Functions in Classes
function.
... def
__init__(self):
>>> p1 = Person()
>>> p2 = Person() The self Change to class attribute company
>>> p1.company =prefix
..."ibm"
is
self.age affects all instances (p1 and p2)
= 23
>>> print p2.company
always required.
'ibm'
Constructor
• When an instance of a class is created, the class constructor function is
automatically called.
• The constructor is always named init ()
• It contains code for initializing a new instance of the class to a specific initial state
(e.g. setting instance attribute values).
Deriving a new class form existing class so that new class inherits all
Inheritance
members(attributes + methods) of existing class is called as inheritance
Inheritance
Construct
>>> r1 = Rectangle( 10, 5 )
>>> print r1.width object instance
10
>>> print r1.height
5
>>> print r1.area()
50
>>> print r1.color Inherited
(0, 0, 0) attribute
Overriding
When inheriting from a class, we can alter the behavior of the original superclass by
"overriding" functions (i.e. declaring functions in the subclass with the same name).
class CustomCounter(Counter):
class Counter: def init (self,size):
def init (self): Counter. init (self)
self.value = 0 self.stepsize = size
class salary(Employees):
def Salary(self):
print("Salary: 10000")
class Designation(salary):
def desig(self):
print("Designation: Test Engineer")
call = Designation()
call.Name()
call.Salary()
call.desig()
Multiple Inheritance
# hybrid inheritance
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
# a getter function
def get_version(self):
print(f'The sensor version is sensor1 = Sensor('Acc', 'Berkeley')
{self.__version}') print(sensor1.name)
print(sensor1._location)
# a setter function print(sensor1.__version)
def set_version(self, version):
self.__version = version
Polymorphism
• Polymorphism is another fundamental concept in OOP, which means multiple
forms
• Two objects of different classes but supporting the same set of functions or
attributes can be treated identically.
• The implementations may differ internally, but the outward "appearance" is the
same.
• Polymorphism allows us to use a single interface with different underlying
forms such as data types or classes
Polymorphism
Create Student
>>> compsci = Department()
>>> compsci.enroll( Student( "Smith", "John" ) ) instances and add
>>> compsci.enroll( Student( "Murphy", "Alice" ) ) to Department
instance
>>> for s in compsci.students:
... print "%s %s" % (s.firstname,s.lastname)
...
John Smith