0% found this document useful (0 votes)
11 views10 pages

Week 8,9

The document provides a series of Python programming lab exercises aimed at teaching file handling, list and dictionary manipulation, and various built-in functions. It includes programs for generating random numbers, demonstrating file pointer methods, and illustrating list and dictionary methods, along with their respective outputs and inferences. Each program is designed to enhance understanding of Python's capabilities in handling data efficiently.

Uploaded by

23331a05e7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views10 pages

Week 8,9

The document provides a series of Python programming lab exercises aimed at teaching file handling, list and dictionary manipulation, and various built-in functions. It includes programs for generating random numbers, demonstrating file pointer methods, and illustrating list and dictionary methods, along with their respective outputs and inferences. Each program is designed to enhance understanding of Python's capabilities in handling data efficiently.

Uploaded by

23331a05e7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

‭PYTHON PROGRAMMING LAB‬

‭Week 9‬

‭Program 1: Writing 20 Random Numbers to a File‬


‭Aim:‬‭To generate 20 random numbers in the range of‬‭1 to 100 and write them to a file.‬


‭ 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

‭...‬

I‭nference:‬‭Writing random numbers to a file might‬‭seem 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()‬

‭with open("example.txt", "r") as file:‬


‭print("Initial Position:", file.tell())‬
‭file.seek(7)‬

‭content = file.read(5)‬
‭print("Read content:", content)‬
‭print("Current Position:", file.tell())‬
05
‭print("After seek(7), Position:", file.tell())‬
1A
‭Output:‬

I‭nitial Position: 0‬
‭After seek(7), Position: 7‬
33

‭Read content: this‬


‭Current Position: 12‬

I‭nference:‬‭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
f‭ile.write("Line 1: Hello World!\n")‬
‭file.write("Line 2: Python is great.\n")‬
‭file.write("Line 3: File handling is useful.\n")‬

‭with open("sample.txt", "r") as file:‬


‭print("Using read():")‬
‭file.seek(0)‬
‭print(file.read(10))‬
‭print("\nUsing readline():")‬
‭file.seek(0)‬
05
1A
‭print(file.readline()‬
‭print("\nUsing readlines():")‬
‭file.seek(0)‬
‭print(file.readlines())‬

‭Output:‬
33

‭ sing read():‬
U
‭Line 1: Hel‬

‭ sing readline():‬
U
‭23

‭Line 1: Hello World!‬

‭ sing readlines():‬
U
‭['Line 1: Hello World!\n', 'Line 2: Python is great.\n', 'Line 3: File handling is useful.\n']‬

I‭nference:‬‭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‬

in‬‭Operator and Counting‬


‭ rogram 1: Using the‬‭
P
‭Lowercase Characters in a String‬


in‬‭operator and‬‭write a Python program to count the number of‬
‭ im:‬‭To illustrate the use of the‬‭
A

E7
‭lowercase characters in a string.‬

in‬‭operator checks if a substring‬‭exists within a string. This program also‬


‭Description:‬‭The‬‭
islower()‬‭method.‬
‭iterates over a given string and counts lowercase characters using the‬‭

‭Program:‬

‭string = input("Enter a string: ")‬

05
‭lowercase_count = sum(1 for char in string if char.islower())‬
1A
‭print("Number of lowercase characters:", lowercase_count)‬

‭Output:‬

‭Enter a string: Hello World!‬


33

‭Number of lowercase characters: 8‬


‭23

in‬‭operator is a fundamental way to‬‭check for substring existence in Python,‬


‭Inference:‬‭The‬‭
islower()‬‭function simplifies checking lowercase‬
‭ aking it useful for validation tasks. The‬‭
m
‭letters in a string. Understanding how to iterate through strings efficiently is crucial for text‬
‭analysis, form validation, and search operations.‬
‭Program 2: Demonstrating List Functions‬
len()‬
‭Aim:‬‭To illustrate various list functions:‬‭ extend()‬
‭,‬‭ sort()‬
‭,‬‭ append()‬
‭,‬‭ insert()‬
‭,‬‭ ‭,‬
remove()‬
‭and‬‭ ‭.‬

‭ 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]‬

‭print("Original List:", my_list)‬

‭print("Length of list:", len(my_list))‬

05
1A
‭my_list.extend([10, 12])‬

‭print("After extend:", my_list)‬

‭my_list.sort()‬
33

‭print("After sort:", my_list)‬


‭23

‭my_list.append(7)‬

‭print("After append:", my_list)‬

‭my_list.insert(2, 15)‬

‭print("After insert at index 2:", my_list)‬

‭my_list.remove(8)‬
‭print("After removing 8:", my_list)‬

‭Output:‬

‭Original List: [5, 2, 8, 1]‬

‭Length of list: 4‬

‭After extend: [5, 2, 8, 1, 10, 12]‬


E7
‭After sort: [1, 2, 5, 8, 10, 12]‬

‭After append: [1, 2, 5, 8, 10, 12, 7]‬

‭After insert at index 2: [1, 2, 15, 5, 8, 10, 12, 7]‬

‭After removing 8: [1, 2, 15, 5, 10, 12, 7]‬

05 len()‬
‭Inference:‬‭Lists provide several useful functions‬‭that 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‬‭ ‭, which‬‭adds a single element at the end. The‬
sort()‬‭function arranges elements in ascending order‬‭by 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 arguments‬‭to functions.‬

‭Description:‬‭Python allows lists to be passed to functions,‬‭enabling efficient data manipulation.‬

‭Program:‬


‭def square_elements(lst):‬

E7
‭return [x**2 for x in lst]‬

‭numbers = [1, 2, 3, 4, 5]‬

‭squared_numbers = square_elements(numbers)‬

‭print("Original List:", numbers)‬

‭print("Squared List:", squared_numbers)‬


05
1A
‭Output:‬

‭Original List: [1, 2, 3, 4, 5]‬


33

‭Squared List: [1, 4, 9, 16, 25]‬

I‭nference:‬‭Lists are mutable, meaning any changes‬‭inside 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‬
‭ ‭.‬

‭ escription:‬‭Dictionaries in Python allow key-value‬‭storage. This program demonstrates useful‬


D
‭dictionary methods.‬


‭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")‬

‭print("After pop:", my_dict)‬

‭del my_dict["city"]‬
33

‭print("After delete:", my_dict)‬


‭23

‭Output:‬

‭Keys: dict_keys(['name', 'age', 'city'])‬

‭Values: dict_values(['Alice', 25, 'New York'])‬

‭Items: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])‬

‭After pop: {'name': 'Alice', 'city': 'New York'}‬

‭After delete: {'name': 'Alice'}‬


I‭nference:‬‭Dictionaries provide various methods for handling key-value pairs effectively. The‬
keys()‬‭method returns all keys in the dictionary,‬‭while‬‭
‭ values()‬‭provides the associated‬
items()‬‭function returns key-value pairs‬‭as tuples, making iteration easier. The‬
‭values. The‬‭
pop()‬‭method removes a key from the dictionary and returns its value, which is useful when‬

‭ eeding to extract and delete an item simultaneously. In contrast,‬‭
n del‬‭permanently removes a‬
‭key-value pair but does not return the value. Understanding these differences is crucial when‬
del‬‭could lead to unintended data loss.‬
‭working with dictionaries, as improper use of‬‭


E7
‭Program 5: Reverse Dictionary Lookup‬
‭Aim:‬‭To perform a reverse lookup in a dictionary,‬‭finding keys based on values.‬

‭ escription:‬‭Reverse lookup in dictionaries is useful‬‭when we have values but need to find‬


D
‭corresponding keys.‬

‭Program:‬

‭def reverse_lookup(d, value):‬ 05


1A
‭return [key for key, val in d.items() if val == value]‬

‭data = {"a": 10, "b": 20, "c": 10, "d": 30}‬

‭value_to_find = 10‬
33

‭keys = reverse_lookup(data, value_to_find)‬

‭print("Keys with value 10:", keys)‬


‭23

‭Output:‬

‭Keys with value 10: ['a', 'c']‬

I‭nference:‬‭Python dictionaries do not have built-in‬‭reverse lookup functionality, so iterating‬


‭through‬‭items()‬‭to find keys matching a value is necessary.‬‭This approach is useful in cases‬
‭where values are not unique and multiple keys may share the same value. If values are‬
‭guaranteed to be unique, a dictionary can be reversed using‬‭{v: k for k, v in‬
‭ict.items()}‬
d ‭, but this method fails when values are repeated. Reverse lookups are‬
‭valuable in applications like bidirectional mappings and searching datasets efficiently.‬
‭23
33
1A
05
E7

You might also like