0% found this document useful (0 votes)
1 views12 pages

Python Practical File

The document is a practical file for a Python course covering functions and file handling. It includes various Python functions with algorithms and sample code for tasks such as removing elements from a list, counting characters, reading and writing text files, and handling binary files. Each section provides clear examples and expected outputs for better understanding of the concepts.

Uploaded by

Vaibhav Baghel
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)
1 views12 pages

Python Practical File

The document is a practical file for a Python course covering functions and file handling. It includes various Python functions with algorithms and sample code for tasks such as removing elements from a list, counting characters, reading and writing text files, and handling binary files. Each section provides clear examples and expected outputs for better understanding of the concepts.

Uploaded by

Vaibhav Baghel
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

PYTHON PRACTICAL FILE

COMPUTER SCIENCE (CODE: 083)


Comprehensive Study on Functions and File Handling
FUNCTIONS

Aim: Write a Python function remove_element(L, n) that removes the element n from
the list L if it exists.
Algorithm:
Python Source Code

def remove_element(L, n):


if n in L:
[Link](n)
return L

# Driver Code
my_list = [10, 20, 30, 40, 50]
print("Original:", my_list)
result = remove_element(my_list, 30)
print("After removing 30:", result)

Sample Execution Output

Original: [10, 20, 30, 40, 50]


After removing 30: [10, 20, 40, 50]
Aim: Write a function increment() that uses the global keyword to increase the value
of a variable num by 1.
Algorithm:
Python Source Code

num = 10

def increment():
global num
num += 1

print("Before:", num)
increment()
print("After increment:", num)

Sample Execution Output

Before: 10
After increment: 11

Aim: Write a function CALC(x, y) that returns the product of two numbers.
Algorithm:
Python Source Code

def CALC(x, y):


return x * y

# Driver Code
a, b = 5, 4
prod = CALC(a, b)
print(f"Product of {a} and {b} is: {prod}")

Sample Execution Output

Product of 5 and 4 is: 20


Aim: Write a function COUNTLOWER(s) that takes a string as a parameter and
returns the number of lowercase characters.
Algorithm:
Python Source Code

def COUNTLOWER(s):
count = 0
for char in s:
if [Link]():
count += 1
return count

# Driver Code
text = "Python Programming"
print("Lowercase count:", COUNTLOWER(text))

Sample Execution Output

Lowercase count: 16

Aim: Write a function FINDMAX(L) that takes a list of numbers as an argument and
returns the largest value.
Algorithm:
Python Source Code

def FINDMAX(L):
if not L:
return None
return max(L)

# Driver Code
nums = [45, 22, 89, 12, 67]
print("Maximum value is:", FINDMAX(nums))

Sample Execution Output

Maximum value is: 89


Aim: Write a function DISPLAY(n) that takes a number as a parameter and prints its
square.
Algorithm:
Python Source Code

def DISPLAY(n):
print(f"The square of {n} is: {n**2}")

# Driver Code
DISPLAY(7)

Sample Execution Output

The square of 7 is: 49


TEXT FILE HANDLING

Aim: Write a program to read a text file and display its contents using read(),
readline(), and readlines().
Algorithm:
Python Source Code

# Assuming [Link] exists with some content


with open('[Link]', 'w') as f:
[Link]("Line 1\nLine 2\nLine 3")

print("Using read():")
with open('[Link]', 'r') as f:
print([Link]())

print("\nUsing readline():")
with open('[Link]', 'r') as f:
print([Link]().strip())

print("\nUsing readlines():")
with open('[Link]', 'r') as f:
print([Link]())

Sample Execution Output

Using read():
Line 1
Line 2
Line 3

Using readline():
Line 1

Using readlines():
['Line 1\n', 'Line 2\n', 'Line 3']
Aim: Display lines with >5 words and define count_A() to count lines starting with 'A'.
Algorithm:
Python Source Code

def count_A():
count = 0
with open('[Link]', 'r') as f:
for line in f:
if [Link]().startswith('A'):
count += 1
return count

# Writing dummy data


with open('[Link]', 'w') as f:
[Link]("Apple is red\nAn ant is small\nThis line has many many words inside it\nBananas

print("Lines with > 5 words:")


with open('[Link]', 'r') as f:
for line in f:
if len([Link]()) > 5:
print([Link]())

print("Count of lines starting with 'A':", count_A())

Sample Execution Output

Lines with > 5 words:


This line has many many words inside it
Count of lines starting with 'A': 2
Aim: Write a function word_count() to count the occurrence of the word 'is' in a text
file.
Algorithm:
Python Source Code

def word_count():
count = 0
with open('[Link]', 'r') as f:
words = [Link]().split()
for w in words:
if [Link]() == 'is':
count += 1
return count

# Driver Code
with open('[Link]', 'w') as f:
[Link]("This is a test. Logic is important.")
print("Occurrence of 'is':", word_count())

Sample Execution Output

Occurrence of 'is': 2

Aim: Write a function longest_line() to display the longest line from a text file.
Algorithm:
Python Source Code

def longest_line():
max_line = ""
with open('[Link]', 'r') as f:
lines = [Link]()
for line in lines:
if len(line) > len(max_line):
max_line = line
print("Longest line:", max_line.strip())

# Creating sample file


with open('[Link]', 'w') as f:
[Link]("Short line\nThe longest line is definitely this one.\nMedium line")
longest_line()

Sample Execution Output

Longest line: The longest line is definitely this one.


Aim: Write a function to display lines starting with a vowel from a file [Link].
Algorithm:
Python Source Code

def display_vowel_lines():
vowels = "AEIOUaeiou"
with open('[Link]', 'r') as f:
for line in f:
if line and line[0] in vowels:
print([Link]())

# Creating sample file


with open('[Link]', 'w') as f:
[Link]("Once upon a time\nThere lived a king\nIn a deep forest\nEnd of story")
display_vowel_lines()

Sample Execution Output

Once upon a time


In a deep forest
End of story

Aim: Write a function count_upper() to count the number of uppercase characters in


a text file.
Algorithm:
Python Source Code

def count_upper():
count = 0
with open('[Link]', 'r') as f:
content = [Link]()
for char in content:
if [Link]():
count += 1
return count

# Sample file
with open('[Link]', 'w') as f:
[Link]("Python Programming is FUN!")
print("Uppercase count:", count_upper())

Sample Execution Output

Uppercase count: 5
BINARY FILE HANDLING

Aim: Records in [Link] [Emp_id, Name, Salary]. Display employees having salary <
25000.
Algorithm:
Python Source Code

import pickle

def disp_Detail():
try:
with open('[Link]', 'rb') as f:
while True:
rec = [Link](f)
if rec[2] < 25000:
print(rec)
except EOFError:
pass

# Creating sample binary data


with open('[Link]', 'wb') as f:
[Link]([1, "Alice", 30000], f)
[Link]([2, "Bob", 22000], f)
[Link]([3, "Charlie", 15000], f)

print("Employees with Salary < 25000:")


disp_Detail()

Sample Execution Output

Employees with Salary < 25000:


[2, 'Bob', 22000]
[3, 'Charlie', 15000]
Aim: Copy dictionary records with 'amount' > 1000 from one binary file to another.
Algorithm:
Python Source Code

import pickle

def copy_expensive():
try:
f1 = open('[Link]', 'rb')
f2 = open('[Link]', 'wb')
while True:
rec = [Link](f1)
if rec['amount'] > 1000:
[Link](rec, f2)
except EOFError:
[Link]()
[Link]()

# Setup data
with open('[Link]', 'wb') as f:
[Link]({'id':1, 'amount': 1500}, f)
[Link]({'id':2, 'amount': 500}, f)

copy_expensive()
print("Records copied successfully.")

Sample Execution Output

Records copied successfully.


Aim: Write a program using pickle to store and display records from a binary file.
Algorithm:
Python Source Code

import pickle

# Storing records
def store():
recs = [{"id": 101, "name": "Amit"}, {"id": 102, "name": "Saira"}]
with open('[Link]', 'wb') as f:
[Link](recs, f)
print("Records stored.")

# Displaying records
def display():
with open('[Link]', 'rb') as f:
data = [Link](f)
for r in data:
print(r)

store()
print("Displaying records:")
display()

Sample Execution Output

Records stored.
Displaying records:
{'id': 101, 'name': 'Amit'}
{'id': 102, 'name': 'Saira'}

You might also like