Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

UNIT 4

Sieve of Eratosthenes
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small
number.
Example:
Input : n =10
Output : 2 3 5 7

Input : n = 20
Output: 2 3 5 7 11 13 17 19
The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when
n is smaller than 10.

Following is the algorithm to find all the prime numbers less than or equal to a given integer n by
Eratosthenes’ method:
1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n).
2. Initially, let p equal 2, the first prime number.
3. Starting from p2, count up in increments of p and mark each of these numbers greater
than or equal to p2 itself in the list. These numbers will be p(p+1), p(p+2), p(p+3), etc..
4. Find the first number greater than p in the list that is not marked. If there was no such
number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat
from step 3.

When the algorithm terminates, all the numbers in the list that are not marked are prime.
Explanation with Example:
Let us take an example when n = 50. So we need to print all print numbers smaller than or equal
to 50.
We create a list of all numbers from 2 to 50.
According to the algorithm we will mark all the numbers which are divisible by 2 and are greater
than or equal to the square of it.

Now we move to our next unmarked number 3 and mark all the numbers which are multiples of
3 and are greater than or equal to the square of it.

We move to our next unmarked number 5 and mark all multiples of 5 and are greater than or
equal to the square of it.

We continue this process and our final table will look like below:

So the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47.
# Python program to print all primes smaller than or equal to
# n using Sieve of Eratosthenes

def SieveOfEratosthenes(n):

# Create a boolean array "prime[0..n]" and initialize


# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
prime = [True for i in range(n + 1)]
p=2
while (p * p <= n):

# If prime[p] is not changed, then it is a prime


if (prime[p] == True):

# Update all multiples of p


for i in range(p * 2, n + 1, p):
prime[i] = False
p += 1
prime[0]= False
prime[1]= False
# Print all prime numbers
for p in range(n + 1):
if prime[p]:
print p,

# driver program
if __name__=='__main__':
n = 30
print "Following are the prime numbers smaller",
print "than or equal to", n
SieveOfEratosthenes(n)
Output:
Following are the prime numbers below 30
2 3 5 7 11 13 17 19 23 29
Python File I/O

What is a file?

File is a named location on disk to store information. It is used to permanently store data in a
non-volatile memory (e.g. hard disk). Since, we all know that random access memory (RAM) is
volatile (temporary) which loses its data when computer is turned off, we use files for future use
of the data.

When we want to read from or write to a file we need to open it first. When we are done different
operations, it needs to be closed, so that resources that are tied with the file are freed.

Hence, in Python, a file operation takes place in the following order.

1. Open a file

2. Read or write (perform operation)

3. Close the file

In other words, we were taking the input from the console and writing it back to the console to
interact with the user.

Sometimes, it is not enough to only display the data on the console. The data to be displayed may
be very large, and we all know that only a limited amount of data can be displayed on the
console, and since the memory is volatile (temporary), it is impossible to recover the
programmatically generated data again and again.

However, if we need to do so, we may store it onto the local file system which is volatile and can
be accessed every time. Here, comes the need of file handling.

1. Opening a file

Python has a built-in function open () to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly. We use open () function
along with two arguments, that accepts file name and the mode, whether to read or write.
So, the syntax being:

open(filename, mode).

>>> f = open("python.txt") # open file in current directory


>>> f = open("C:/Python33/README.txt") # specifying full path

We can specify the mode while opening a file. In mode, we specify whether we want to read 'r',
write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or
binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.

On the other hand, binary mode returns bytes and this is the mode to be used when dealing with
non-text files like image or exe files.

Python File Modes

Mode Description

'r' Open a file for reading. (default)

Open a file for writing. Creates a new file if it does not exist or truncates the file if it
'w'
exists.

'x' Open a file for exclusive creation. If the file already exists, the operation fails.

Open for appending at the end of the file without truncating it. Creates a new file if it
'a'
does not exist.

't' Open in text mode. (default)

'b' Open in binary mode.

'+' Open a file for updating (reading and writing)

f = open("test.txt") # equivalent to 'r' or 'rt'


f = open("test.txt",'w') # write in text mode
2. Closing a file Using Python
When we are done with operations to the file, we need to properly close the file. Closing a file
will free up the resources that were tied with the file and is done using Python close() method.

Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to
close the file.

f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
# perform file operations

3. Reading the file

To read a file using the python script, the python provides us the read() method. The read()
method reads a string from the file. It can read the data in the text as well as binary format.

The syntax of the read() method is given below.

1. fileobj.read(<count>)

Here, the count is the number of bytes to be read from the file starting from the beginning of the
file. If the count is not specified, then it may read the content of the file until the end.

Consider the following example.

Example

1. #open the file.txt in read mode. causes error if no such file exists.
2. filepy = open("file.txt","r");
3.
4. #stores all the data of the file into the variable content
5. content = filepy.read(9);
6.
7. #prints the content of the file
8. print(content)
9.
10. #closes the opened file
11. filepy.close()

Output:

Hi, I am
4. Read Lines of the file

Python facilitates us to read the file line by line by using a function readline(). The readline()
method reads the lines of the file from the beginning, i.e., if we use the readline() method two
times, then we can get the first two lines of the file.

Consider the following example which contains a function readline() that reads the first line of
our file "file.txt" containing three lines.

Example

1. #open the file.txt in read mode. causes error if no such file exists.
2. filepy = open("file.txt","r");
3.
4. #stores all the data of the file into the variable content
5. content = filepy.readline();
6.
7. #prints the content of the file
8. print(content)
9.
10. #closes the opened file
11. filepy.close()

Output:

Hi, I am the file and being used as

5. Looping through the file


By looping through the lines of the file, we can read the whole file.

Example

1. #open the file.txt in read mode. causes an error if no such file exists.
2.
3. filepy = open("file.txt","r");
4.
5. #running a for loop
6. for i in filepy:
7. print(i) # i contains each line of the file
Output:

Hi, I am the file and being used as


an example to read a
file in python.

6. Writing the file

To write some text to a file, we need to open the file using the open method with one of the
following access modes.

a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if
no file exists.

w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.

Consider the following example.

Example 1

1. #open the file.txt in append mode. Creates a new file if no such file exists.
2. filepy = open("file.txt","a");
3.
4. #appending the content to the file
5. filepy.write("Python is the modern day language. It makes things so simple.")
6.
7. #closing the opened file
8. filepy.close();

Now, we can see that the content of the file is modified.

File.txt:

1. Hi, I am the file and being used as


2. an example to read a
3. file in python.
4. Python is the modern day language. It makes things so simple.

Example 2

1. #open the file.txt in write mode.


2. filepy = open("file.txt","w");
3.
4. #overwriting the content of the file
5. filepy.write("Python is the modern day language. It makes things so simple.")
6.
7. #closing the opened file
8. filepy.close();

Now, we can check that all the previously written content of the file is overwritten with the new
text we have passed.

File.txt:

1. Python is the modern day language. It makes things so simple.

7. Creating a new file

The new file can be created by using one of the following access modes with the function
open(). x: it creates a new file with the specified name. It causes an error a file exists with the
same name.

a: It creates a new file with the specified name if no such file exists. It appends the content to the
file if the file already exists with the specified name.

w: It creates a new file with the specified name if no such file exists. It overwrites the existing
file.

Consider the following example.

Example

1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","x");
3.
4. print(filepy)
5.
6. if filepy:
7. print("File created successfully");

Output:

File created successfully


Exception handling in Python

Exceptions

An exception can be defined as an abnormal condition in a program resulting in the disruption in


the flow of the program.

Whenever an exception occurs, it means there is an error because of which the program halts the
execution, and thus the further code is not executed. Therefore, an exception is the error which
python script is unable to tackle with.

Python provides us with the way to handle the Exception so that the other part of the code can be
executed without any disruption. However, if we do not handle the exception, the interpreter
doesn't execute all the code that exists after that.

In other words, Python has many built-in exceptions which force your program to output an error
when something in it goes wrong.
When these exceptions occur, it causes the current process to stop and passes it to the calling
process until it is handled. If not handled, our program will crash.

For example, if function A calls function B which in turn calls function C and an exception
occurs in function C. If it is not handled in C, the exception passes to B and then to A.
If never handled, an error message is spit out and our program comes to a sudden, unexpected
halt.

Common Exceptions

A list of common exceptions (errors) that can be thrown from a normal python program is given
below.

1. ZeroDivisionError: Occurs when a number is divided by zero.


2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

To handle the exception of programs, we have

• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The finally block lets you execute code, regardless of the result of the try- and except blocks.
Problem without handling exceptions

As we have already discussed, the exception is an abnormal condition that halts the execution of
the program. Consider the following example.

Example
1. a = int(input("Enter a:"))
2. b = int(input("Enter b:"))
3. c = a/b
4. print(c)
5.
6. #other code:
7. print("Hi I am other part of the program")

Output:

Enter a:10
Enter b:0 #This causes the error
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b
ZeroDivisionError: division by zero #This is Error or Exception because of which program
will not be executed

How to handle exception

If the python program contains suspicious code that may throw the exception,

• we must place that code in the try block.


• The try block must be followed with the except statement which contains a block of code that
will be executed if there is some exception in the try block.
Syntax
1. try:
2. #block of code
3.
4. except Exception1: #Error1 generated
5. #block of code
6.
7. except Exception2: #Error2 generated
8. #block of code
9.
10. #other code

We can also use the else statement with the try-except statement in which, we can place the
code which will be executed in the scenario if no exception occurs in the try block.

The syntax to use the else statement with the try-except statement is given below.

1. try:
2. #block of code
3.
4. except Exception1:
5. #block of code
6.
7. else:
8. #this code executes if no except block is executed
Example
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b
5. print(c)
6. except Exception:
7. print("can't divide by zero")
8. else:
9. print("Hi I am else block")

Output:

Enter a:10
Enter b:2
a/b = 5
Hi I am else block

NOTE: In the above example, as you see that the value of b is 2, so it will generate any
exception but if we will try to input 0 in b, it will be go into except block and the program will
not be stopped. We will use try…except block to renew the execution.

Example
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b;
5. print("a/b = %d"%c)
6. except:
7. print("can't divide by zero")
8. else:
9. print("Hi I am else block")

Output:

Enter a:10
Enter b:0
can't divide by zero
The finally block

We can use the finally block with the try block in which, we can place the important code which
must be executed before the try statement throws an exception.

The syntax to use the finally block is given below.

Syntax

1. try:
2. # block of code
3. # this may throw an exception
4. finally:
5. # block of code
6. # this will always be executed

Example
1. try:
2. fileptr = open("file.txt","r")
3. try:
4. fileptr.write("Hi I am good")
5. finally:
6. fileptr.close()
7. print("file closed")
8. except:
9. print("Error")

Output:

file closed
Error

Raise an exception

We can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use
the raise keyword.

Example

Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

The raise keyword is used to raise an exception. You can define what kind of error to raise, and
the text to print to the user.

Example

Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

Example

1. try:
2. age = int(input("Enter the age:"))
3. if age<18:
4. raise ValueError;
5. else:
6. print("the age is valid")
7. except ValueError:
8. print("The age is not valid")
Output:

Enter the age: 17


The age is not valid

Example

1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. if b is 0:
5. raise ArithmeticError;
6. else:
7. print("a/b = ",a/b)
8. except ArithmeticError:
9. print("The value of b can't be 0")

Output:

Enter a:10
Enter b:0
The value of b can't be 0

You might also like