Week 8,9
Week 8,9
Week 9
escription:This program uses the random module to generate random numbers and writes
D
E7
them to a file named random_numbers.txt. The numbers are written line by line, ensuring each
number is stored separately for easy retrieval.
Program:
import random
for _ in range(20):
number = random.randint(1, 100)
file.write(str(number) + "\n")
05
with open("random_numbers.txt", "w") as file:
1A
print("20 random numbers have been written to 'random_numbers.txt'")
Output:
33
3
2
87
56
12
98
23
...
Inference:Writing random numbers to a file mightseem simple, but it’s an essential step in
working with file handling.Open method in python can also be used but the choice to use with
open comes from the intuition to have code written in more pythonic way (as with open will
automatically close the file).A separate with open statement can be written to read to the
contents in file as well.
rogram 2: Demonstrating seek(), tell(), and flush()
P
Methods
Aim:To illustrate the usage of seek(), tell(), and flush() methods for file pointer manipulation.
escription:The program writes data to a file and demonstrates how to move the file pointer
D
using seek(), retrieve the current position using tell(), and forcefully write buffered data using
flush().
Program:
E7
with open("example.txt", "w") as file:
file.write("Hello, this is a test file.")
file.flush()
content = file.read(5)
print("Read content:", content)
print("Current Position:", file.tell())
05
print("After seek(7), Position:", file.tell())
1A
Output:
Initial Position: 0
After seek(7), Position: 7
33
Inference:The seek() and tell() functions make navigating a file much easier, which is useful
23
when working with large files or when we need to edit specific portions of data. The flush()
function ensures that data is saved immediately, which is especially helpful in real-time
applications. These methods help us manage file operations more efficientl
rogram 3: Demonstrating read(), readline(), and
P
readlines() Methods
Aim:To illustrate different file reading methods: read(), readline(), and readlines().
escription:This program writes multiple lines to a file and demonstrates how different reading
D
methods retrieve data in various ways.
Program:
with open("sample.txt", "w") as file:
E7
file.write("Line 1: Hello World!\n")
file.write("Line 2: Python is great.\n")
file.write("Line 3: File handling is useful.\n")
Output:
33
sing read():
U
Line 1: Hel
sing readline():
U
23
sing readlines():
U
['Line 1: Hello World!\n', 'Line 2: Python is great.\n', 'Line 3: File handling is useful.\n']
Inference:Reading files is one of the most common tasks in programming, and Python gives us
different ways to do it. The read() method is useful when we need to fetch a specific number of
characters, readline() helps when we only want a single line, and readlines() makes it easy to
grab everything at once. Knowing when to use each of these makes working with files much
more efficient.
PYTHON PROGRAMMING LAB
Week 8
inoperator andwrite a Python program to count the number of
im:To illustrate the use of the
A
E7
lowercase characters in a string.
Program:
05
lowercase_count = sum(1 for char in string if char.islower())
1A
print("Number of lowercase characters:", lowercase_count)
Output:
escription:Lists in Python provide built-in functions to manipulate and modify data. This
D
program demonstrates how these functions work.
Program:
E7
my_list = [5, 2, 8, 1]
05
1A
my_list.extend([10, 12])
my_list.sort()
33
my_list.append(7)
my_list.insert(2, 15)
my_list.remove(8)
print("After removing 8:", my_list)
Output:
Length of list: 4
E7
After sort: [1, 2, 5, 8, 10, 12]
05 len()
Inference:Lists provide several useful functionsthat enhance data manipulation. The
extend()allows adding multiple
function returns the number of elements in a list, while
1A
append()
elements from another iterable, unlike , whichadds a single element at the end. The
sort()function arranges elements in ascending orderby default. The
insert()method
llows elements to be added at a specific position, whereas
a remove()deletes the first
occurrence of a specified value. Understanding these methods is important for handling data
efficiently and avoiding errors, especially when modifying lists dynamically.
33
23
Program 3: Passing a List as an Argument to a Function
Aim:To illustrate how lists can be passed as argumentsto functions.
Program:
def square_elements(lst):
E7
return [x**2 for x in lst]
squared_numbers = square_elements(numbers)
Inference:Lists are mutable, meaning any changesinside a function can directly affect the
23
original list unless explicitly handled otherwise. Functions make code more reusable and
modular, allowing operations like transformations to be applied efficiently. List comprehensions,
as shown in this program, provide an elegant way to process list elements without writing
lengthy loops.
Program 4: Demonstrating Dictionary Methods
keys()
Aim:To illustrate the use of dictionary methods: values()
, items()
, pop()
, , and
del
.
Program:
E7
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print("Keys:", my_dict.keys())
print("Values:", my_dict.values())
print("Items:", my_dict.items())
05
1A
my_dict.pop("age")
del my_dict["city"]
33
Output:
E7
Program 5: Reverse Dictionary Lookup
Aim:To perform a reverse lookup in a dictionary,finding keys based on values.
Program:
value_to_find = 10
33
Output: