0% found this document useful (0 votes)
3 views15 pages

Python Practical File

The document outlines a Python practical file for the 2024-2025 session, detailing various assignments focused on functions, text file handling, and binary file handling. Each assignment includes an aim, algorithm, and Python source code, demonstrating tasks such as removing elements from a list, counting characters, and reading/writing files. The document serves as a guide for students to practice and implement Python programming 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)
3 views15 pages

Python Practical File

The document outlines a Python practical file for the 2024-2025 session, detailing various assignments focused on functions, text file handling, and binary file handling. Each assignment includes an aim, algorithm, and Python source code, demonstrating tasks such as removing elements from a list, counting characters, and reading/writing files. The document serves as a guide for students to practice and implement Python programming 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

COMPUTER SCIENCE (083)

PYTHON PRACTICAL FILE


2024 - 2025 SESSION

FUNCTIONS

Assignment 1

AIM

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

ALGORITHM

• Define function remove_element taking a list L and element n.


• Check if n is present in L using the 'in' operator.
• If present, use the remove() method to delete the first occurrence of n.
• Return the modified list.
• Print the list before and after calling the function to verify.

PYTHON SOURCE CODE

"kw">def remove_element(L, n):


"kw">if n "kw">in L:
[Link](n)
"kw">return L

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

TERMINAL OUTPUT

>>> Console Output


Original: [10, 20, 30, 40, 50] After removing 30: [10, 20, 40, 50]
FUNCTIONS

Assignment 2

AIM

Write a function increment() that uses the global keyword to increase the value of a
variable num by 1.

ALGORITHM

• Initialize a global variable num with an initial value.


• Define the function increment().
• Use the 'global' keyword inside the function to reference the outer variable.
• Increment the value of num by 1.
• Call the function and print the updated value.

PYTHON SOURCE CODE

num = 10

"kw">def increment():
"kw">global num
num += 1

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

TERMINAL OUTPUT

>>> Console Output


Before: 10 After increment: 11
FUNCTIONS

Assignment 3

AIM

Write a function CALC(x, y) that returns the product of two numbers.

ALGORITHM

• Define function CALC with parameters x and y.


• Calculate the product using the * operator.
• Return the calculated value to the caller.
• Test the function with user input or sample constants.

PYTHON SOURCE CODE

"kw">def CALC(x, y):


"kw">return x * y

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

TERMINAL OUTPUT

>>> Console Output


Product of 5 and 4 is: 20
FUNCTIONS

Assignment 4

AIM

Write a function COUNTLOWER(s) that takes a string as a parameter and returns the
number of lowercase characters.

ALGORITHM

• Define function COUNTLOWER(s) and initialize a counter to 0.


• Iterate through each character in the string s using a for loop.
• Check if the character is lowercase using the islower() method.
• If true, increment the counter.
• Return the final count.

PYTHON SOURCE CODE

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

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

TERMINAL OUTPUT

>>> Console Output


Lowercase count: 16
FUNCTIONS

Assignment 5

AIM

Write a function FINDMAX(L) that takes a list of numbers as an argument and returns
the largest value.

ALGORITHM

• Define function FINDMAX(L).


• Return the maximum value using the built-in max() function (or iterate manually).
• Alternatively: Initialize max_val with L[0] and compare with all elements.
• Return the largest found value.
• Test with a list of varying numbers.

PYTHON SOURCE CODE

"kw">def FINDMAX(L):
"kw">if "kw">not L:
"kw">return None
"kw">return max(L)

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

TERMINAL OUTPUT

>>> Console Output


Maximum value is: 89
FUNCTIONS

Assignment 6

AIM

Write a function DISPLAY(n) that takes a number as a parameter and prints its
square.

ALGORITHM

• Define function DISPLAY(n).


• Calculate the square of n using n**2 or n*n.
• Print the result with an appropriate label.
• Call the function with a sample integer.

PYTHON SOURCE CODE

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

# Driver Code
DISPLAY(7)

TERMINAL OUTPUT

>>> Console Output


The square of 7 is: 49
T E XT F IL E HANDL ING

Assignment 7

AIM

Write a program to read a text file and display its contents using read(), readline(),
and readlines().

ALGORITHM

• Create/Open a file in read mode.


• Demonstrate read(): reads the entire content as one string.
• Demonstrate readline(): reads one line at a time.
• Demonstrate readlines(): reads all lines into a list of strings.
• Ensure the file is closed after each operation.

PYTHON SOURCE CODE

# Assuming [Link] exists "kw">with some content


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

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

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

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

TERMINAL OUTPUT

>>> Console Output


Using read(): Line 1 Line 2 Line 3 Using readline(): Line 1 Using readlines(): ['Line
1\n', 'Line 2\n', 'Line 3']
T E XT F IL E HANDL ING

Assignment 8

AIM

Display lines with >5 words and define count_A() to count lines starting with 'A'.

ALGORITHM

• Open the text file and iterate through its lines.


• Split each line into words and check if length > 5; if so, print it.
• Define count_A(): initialize a counter.
• Loop through lines; check if current line starts with 'A' (using startswith() or index).
• Print the final count.

PYTHON SOURCE CODE

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

# Writing dummy data


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

"kw">print("Lines ">with > 5 words:")


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

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

TERMINAL OUTPUT

>>> Console Output


Lines with > 5 words: This line has many many words inside it Count of lines starting
with 'A': 2
T E XT F IL E HANDL ING

Assignment 9

AIM

Write a function word_count() to count the occurrence of the word 'is' in a text file.

ALGORITHM

• Open the file in read mode.


• Read the entire content and split it into individual words using split().
• Initialize a counter to zero.
• Iterate through the list of words and compare each with 'is'.
• Increment counter for matches and return result.

PYTHON SOURCE CODE

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

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

TERMINAL OUTPUT

>>> Console Output


Occurrence of 'is': 2
T E XT F IL E HANDL ING

Assignment 10

AIM

Write a function longest_line() to display the longest line from a text file.

ALGORITHM

• Open the file and read all lines using readlines().


• Initialize a variable max_line with an empty string.
• Loop through the list of lines.
• If a line's length is greater than max_line's length, update max_line.
• Print the longest line after the loop.

PYTHON SOURCE CODE

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

# Creating sample file


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

TERMINAL OUTPUT

>>> Console Output


Longest line: The longest line is definitely this one.
T E XT F IL E HANDL ING

Assignment 11

AIM

Write a function to display lines starting with a vowel from a file [Link].

ALGORITHM

• Create a collection of vowels (A, E, I, O, U in both cases).


• Open [Link] in read mode.
• Iterate through each line of the file.
• Check if the first character of the stripped line is in the vowel collection.
• Print the line if the condition is met.

PYTHON SOURCE CODE

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

# Creating sample file


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

TERMINAL OUTPUT

>>> Console Output


Once upon a time In a deep forest End of story
T E XT F IL E HANDL ING

Assignment 12

AIM

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


text file.

ALGORITHM

• Open the text file in read mode.


• Read the whole content of the file into a string.
• Iterate through every character in that string.
• Use the isupper() method to check if the character is uppercase.
• Maintain and return a running total.

PYTHON SOURCE CODE

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

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

TERMINAL OUTPUT

>>> Console Output


Uppercase count: 5
BINARY FILE HANDLING

Assignment 13

AIM

Records in [Link] [Emp_id, Name, Salary]. Display employees having salary <
25000.

ALGORITHM

• Import the pickle module for binary file operations.


• Open [Link] in 'rb' (read-binary) mode.
• Use a try-except block to handle End Of File (EOFError).
• Load records one by one using [Link]().
• Check index 2 (salary) and print the record if it's less than 25000.

PYTHON SOURCE CODE

"kw">import "kw">pickle

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

# Creating sample binary data


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

"kw">print("Employees ">with Salary < 25000:")


disp_Detail()

TERMINAL OUTPUT

>>> Console Output


Employees with Salary < 25000: [2, 'Bob', 22000] [3, 'Charlie', 15000]
BINARY FILE HANDLING

Assignment 14

AIM

Copy dictionary records with 'amount' > 1000 from one binary file to another.

ALGORITHM

• Open the source binary file for reading and the target file for writing.
• Use a loop to load each dictionary record from the source.
• Check if the value associated with 'amount' is greater than 1000.
• If true, [Link]() the record into the target file.
• Handle EOFError to stop reading safely.

PYTHON SOURCE CODE

"kw">import "kw">pickle

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

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

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

TERMINAL OUTPUT

>>> Console Output


Records copied successfully.
BINARY FILE HANDLING

Assignment 15

AIM

Write a program using pickle to store and display records from a binary file.

ALGORITHM

• Prompt the user for data (records) to be stored.


• Open a binary file in 'wb' mode and use [Link]() to save the list/dictionary.
• Close the file.
• Reopen the file in 'rb' mode.
• Use [Link]() to retrieve data and display it clearly.

PYTHON SOURCE CODE

"kw">import "kw">pickle

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

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

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

TERMINAL OUTPUT

>>> Console Output


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

You might also like