0% found this document useful (0 votes)
3 views

Unit-3 Python Lab Programs

This document outlines several Python exercises focused on file handling, exception handling, and creating modules. It includes detailed algorithms, example programs, and expected outputs for tasks such as writing numbers to a file, implementing a Fibonacci iterator, and handling errors like file not found and zero division. Each exercise concludes with a statement confirming successful execution of the program.

Uploaded by

sibi00424
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit-3 Python Lab Programs

This document outlines several Python exercises focused on file handling, exception handling, and creating modules. It includes detailed algorithms, example programs, and expected outputs for tasks such as writing numbers to a file, implementing a Fibonacci iterator, and handling errors like file not found and zero division. Each exercise concludes with a statement confirming successful execution of the program.

Uploaded by

sibi00424
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Unit – 3

Files and Exceptions Handling, Modules, Packages

Ex.No:3.1
Create a text file called "numbers.txt" and write the numbers from 1 to 10 in words, each on
a separate line.

Aim: To create a text file called "numbers.txt" and write the numbers from 1 to 10 in words,
each on a separate line using python.

Algorithm:

1. Open a new text file named "numbers.txt" in write mode.


2. Create a list of number words from 1 to 10.
3. Iterate through the list and write each word to the file followed by a newline
character.
4. Close the file.

Program:
numbers_in_words = ["One","Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten"]

# Open the file in write mode and write the numbers in words

with open("numbers.txt", "w") as file:


for number, word in enumerate(numbers_in_words, start=1):
file.write(f"{word}\n")

print("File 'numbers.txt' has been created with numbers written in words.")

Output:

Copy and paste this code into a Python file numbers_file.py and run it.
It will generate a file named "numbers.txt" with each number from 1 to 10 written in words
on separate lines.

Result:
Thus the given Python program was executed successfully.
Ex.No:3.2
Write a python program that Implement a custom iterator that generates a sequence of Fibonacci
numbers and print the first10 numbers.
Aim:
To write a program to Implement a custom iterator that generates a sequence of Fibonacci numbers
and prints the first 10 Numbers

Algorithm: Fibonacci Iterator


1. Create a class named FibonacciIterator.
2. Initialize class attributes (limit, a, b, count) in the _init_ method.
3. Implement the _iter_ method to return the iterator object.
4. Implement the _next_ method to generate the next Fibonacci number.
- Update a and b, increment count.
- Check if count >= limit, raise StopIteration.
- Return the current Fibonacci number.
5. Instantiate FibonacciIterator with the desired limit.
6. Iterate over the Fibonacci sequence using a for loop.
- Print each generated Fibonacci number.
7. Run the program.

Program:
class FibonacciIterator:
def __init__(self, limit): # Fix: Correct method name from _init_ to __init__
self.limit = limit
self.a, self.b = 0, 1
self.count = 0

def __iter__(self): # Fix: Correct method name from _iter_ to __iter__


return self

def __next__(self): # Fix: Correct method name from _next_ to __next__


if self.count >= self.limit:
raise StopIteration

result = self.a
self.a, self.b = self.b, self.a + self.b
self.count += 1
return result

# Example usage:
if __name__ == "__main__": # Fix: Correct _name_ and _main_ to __name__ and __main__
fibonacci_sequence = FibonacciIterator(10)

for number in fibonacci_sequence:


print(number)
Output:
Here's the output for the provided Python program that implements a custom iterator for generating
the first 10 Fibonacci numbers:
0
1
1
2
3
5
8
13
21
34
This output corresponds to the first 10 Fibonacci numbers in the sequence. The iterator starts with 0
and 1 and generates subsequent numbers by adding the previous two numbers in the sequence.

Result:
Thus the given program was executed successfully.

Ex.No:3.3
Write a Python program to create a try except block to catch a „File not Found‟ Error and print
message when file is not found.

Aim:
Create a try except block to catch a „File not Found‟ Error and print message when file is not found.

Algorithm:
1: Start program
2: Try opening the file using Open command
3: If file not found print „file not found‟
4: End Program

Program:
try:
file1 =open("Myfolder/abc.txt")
except:
print("file not found")
Output:
file not found
Result:
Thus the given Python program was executed successfully.

Ex.No:3.4
Write a python program that HANDLES A Zero Division Error and prints a custom error message
to the console.
Aim :
To write a python program that HANDLES A Zero Division Error and prints a custom error
message to the console

Algorithm:
1. Check if the divisor is zero: Before performing division, the program checks if the divisor is zero.
2. If divisor is zero:
 If the divisor is zero, raise an exception (often a ZeroDivisionError in many programming
languages).
 The program may terminate or proceed to handle the exception based on the context.
3. If divisor is not zero:
 Perform the division operation as usual.
 Return the result or proceed with further computations depending on the program's logic.
4. Handle exceptions (optional):
 In many programming languages, developers can choose to handle the ZeroDivisionError
exception explicitly using try-except blocks.
 Handling the exception allows the program to gracefully respond to the error condition,
potentially avoiding crashes or providing meaningful feedback to the user.

Program:
try:
numerator = 10
denominator = 0
# Check if denominator is zero
if denominator == 0:
raise ZeroDivisionError("Division by zero!")
# Perform division
result = numerator / denominator
print("Result:", result)

except ZeroDivisionError as e:
print("Error:", e)

Output:
Error: Division by zero!
Result:Thus the given Python program was executed successfully.
Ex.No:3.5
Create a module called "greetings.py" with a function called "hello" that prints "Hello,
World!" Import the module into another script and use the "hello" function.
Aim- To write a python program to create a module called “greeting.py” with a function called
“hello” the print “Hello, World!”.

Algorithm:
1. Create a Module Named “greetings.py”.
2. Create a Function Named “hello”.
3. Import that module in another program by using the “hello” function.
4. Print "Hello, World!".

Program:

# greetings.py
def Hello():
print('Hello, World! ')

# main.py
import greetings
greetings.Hello()
Output:
Hello, World!
Hello, World!
Result:
Thus the given Python program was executed successfully.

Ex.No:3.6
Install the numpy package using PIP, import the package and create a numpy array with random
values.
Aim: To create a numpy array with random values in python

Algorithm:

1. Import the numpy library:


o Import numpy as np to work with arrays.
2. Define a 1D array:
o Create a 1D array my_array with the following elements:
[[1, 2, 3, 4],
[5, 6, 7, 8]]
o Set the data type of the array to int.
3. Define a 2D array:
o Create a 2D array my_2d_array with the following elements:
[[1, 2, 3, 4],
[5, 6, 7, 8]]

o Set the data type of the array to int64.


4. Define a 3D array:
o Create a 3D array my_3d_array with the following elements:
[[[1, 2, 3, 4],
[5, 6, 7, 8]],
[[1, 2, 3, 4],
[9, 10, 11, 12]]]

o Set the data type of the array to int64.


5. Print the 1D array:
o Output the contents of my_array with the label: "Printing my_array:".
6. Print the 2D array:
o Output the contents of my_2d_array with the label: "Printing my_2d_array:".
7. Print the 3D array:
o Output the contents of my_3d_array with the label: "Printing my_3d_array:".

Program:
import numpy as np
# Define a 1D array
my_array = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]],
dtype=np.int64)
# Define a 2D array
my_2d_array = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]],
dtype=np.int64)
# Define a 3D array
my_3d_array = np.array([[[1, 2, 3, 4],
[5, 6, 7, 8]],
[[1, 2, 3, 4],
[9, 10, 11, 12]]],
dtype=np.int64)
# Print the 1D array
print("Printing my_array:")
print(my_array)
# Print the 2D array
print("Printing my_2d_array:")
print(my_2d_array)
# Print the 3D array
print("Printing my_3d_array:")
print(my_3d_array)
Output:
Printing my_array:
[[1 2 3 4]
[5 6 7 8]]
Printing my_2d_array:
[[1 2 3 4]
[5 6 7 8]]
Printing my_3d_array:
[[[ 1 2 3 4]
[ 5 6 7 8]]

[[ 1 2 3 4]
[ 9 10 11 12]]]

Result:Thus the given Python program was executed successfully.

You might also like