Python Unit 4 Part 1
Python Unit 4 Part 1
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):
# 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.
1. Open a 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).
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.
Mode Description
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.
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
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.
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.
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:
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:
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.
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();
File.txt:
Example 2
Now, we can check that all the previously written content of the file is overwritten with the new
text we have passed.
File.txt:
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.
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:
Exceptions
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.
• 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
If the python program contains suspicious code that may throw the exception,
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.
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
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
x = "hello"
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:
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