0% found this document useful (0 votes)
4 views8 pages

Python Functions for Data Operations

The document contains a series of Python programming tasks and their implementations, including functions for checking prime numbers, summing alternate list elements, printing even numbers, and performing stack operations. It also includes file handling tasks such as reading from and writing to text and binary files, as well as CSV file operations. Each task is accompanied by example outputs demonstrating the expected results.

Uploaded by

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

Python Functions for Data Operations

The document contains a series of Python programming tasks and their implementations, including functions for checking prime numbers, summing alternate list elements, printing even numbers, and performing stack operations. It also includes file handling tasks such as reading from and writing to text and binary files, as well as CSV file operations. Each task is accompanied by example outputs demonstrating the expected results.

Uploaded by

hohile9889
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Write a function to check whether the given number is prime or


not.
def is_prime(n):
if n <= 1:
return False
for i in range(2, int( n**0.5) + 1):
if n % i == 0:
return False
return True

num = int(input("Enter a number: "))


if is_prime(num):
print(num, "is a Prime Number")
else:
print(num, "is not a Prime Number")

Output:
Enter a number: 7
7 is a Prime Number

2. Write a function to add alternate elements of a list.


def add_alternate(lst):
return sum(lst[::2])

lst = [1, 2, 3, 4, 5, 6]
print("Sum of alternate elements:", add_alternate(lst))

Output:
Sum of alternate elements: 9

3. Write a function to accept a list as parameter and print all the


even numbers in the list.
def print_even(lst):
for i in lst:
if i % 2 == 0:
print(i, end=' ')

lst = [1, 2, 3, 4, 5, 6]
print("Even numbers:")
print_even(lst)

Output:
Even numbers:
2 4 6

4. Write a function to accept two numbers as parameters and find


the greater number between two.
def greater(a, b):
if a > b:
return a
else:
return b

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
print("Greater number:", greater(a, b))

Output:
Enter first number: 15
Enter second number: 20
Greater number: 20

5. Write a function to accept a list as parameter and multiply all the


odd elements by 5.
def multiply_odds(lst):
for i in range(len(lst)):
if lst[i] % 2 != 0:
lst[i] *= 5
print(lst)

lst = [1, 2, 3, 4, 5]
multiply_odds(lst)

Output:
[5, 2, 15, 4, 25]

6. Write a program to implement various stack operations without


using built-in functions.
stack = []
def push(item):
[Link](item)
def pop():
if not stack:
print("Underflow")
else:
print("Popped:", [Link]())
def display():
print("Stack:", stack)

push(10)
push(20)
display()
pop()
display()

Output:
Stack: [10, 20]
Popped: 20
Stack: [10]

7. Write a program to implement various stack operations using


built-in functions.
stack = []
[Link](10)
[Link](20)
[Link]()
print("Stack:", stack)

Output:
Stack: [10]

8. Assume a dictionary and write a function to add new element in


the stack. Add only those elements from the dictionary whose value
consists of A,E,I.
stack = []
d = {'Amit': 'A', 'Neel': 'E', 'Ritu': 'I', 'Mona': 'O'}
for k, v in [Link]():
if v in 'AEI':
[Link](k)
print("Stack:", stack)

Output:
Stack: ['Amit', 'Neel', 'Ritu']
9. Write a function to read a text file and print words starting with I
in reverse order.
def read_file():
f = open('[Link]', 'r')
for line in f:
words = [Link]()
for w in words:
if [Link]('I'):
print(w[::-1])
[Link]()
read_file()

Output:
Ishan → nahsI
India → aidnI

10. Write a function AMCount() in python, which should read each


character of a text file and count and display the occurrence of
alphabets ‘A’ and ‘M’(in both cases).
def AMCount():
f = open('[Link]', 'r')
data = [Link]().upper()
print("A:", [Link]('A'))
print("M:", [Link]('M'))
[Link]()
AMCount()

Output:
A: 12
M: 5

11. Write a function to read content and count the number of lines
starting with either ‘I’ or ‘M’ in a text file.
def count_lines():
f = open('[Link]', 'r')
count = 0
for line in f:
if [Link](('I', 'M')):
count += 1
print("Lines starting with I or M:", count)
[Link]()
count_lines()
Output:
Lines starting with I or M: 3

12. Write a function to read lines of a binary file and display words
which has less than 4 characters.
import pickle
f = open('[Link]', 'rb')
try:
while True:
line = [Link](f)
words = [Link]()
for w in words:
if len(w) < 4:
print(w)
except EOFError:
[Link]()

Output:
The
an
is

13. Write a program to read the content of a binary file ’[Link]’.


import pickle
f = open('[Link]', 'rb')
try:
while True:
print([Link](f))
except EOFError:
[Link]()

Output:
['B101', 'AI Basics', 450]
['B102', 'ML Concepts', 550]

14. Given a binary file [Link] with structure [roll no., name, marks].
Write a function createfile() to input record and add to [Link].
import pickle
def createfile():
f = open('[Link]', 'ab')
roll = int(input("Enter roll no: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
[Link]([roll, name, marks], f)
[Link]()
createfile()

Output:
Enter roll no: 101
Enter name: Asha
Enter marks: 89
Record added successfully.

15. Write a program search_rec() which takes book no. as parameter


and display its record. Structure of binary file- [ book no., book
name, price]
import pickle
def search_rec(bno):
f = open('[Link]', 'rb')
found = False
try:
while True:
rec = [Link](f)
if rec[0] == bno:
print(rec)
found = True
except EOFError:
[Link]()
if not found:
print("Record not found")
search_rec('B101')

Output:
['B101', 'AI Basics', 450]

16. Write a function countrec() to count and display the records of


binary file ‘[Link]’ where percentage is above 75.
import pickle
def countrec():
f = open('[Link]', 'rb')
count = 0
try:
while True:
rec = [Link](f)
if rec[2] > 75:
count += 1
except EOFError:
[Link]()
print("Records with >75%:", count)
countrec()

Output:
Records with >75%: 2

17. Write a program to count the number of buses whose


destination = ‘delhi’ from binary file ‘[Link]’. Structure of file=
[bus no., start point, destination]
import pickle
f = open('[Link]', 'rb')
count = 0
try:
while True:
rec = [Link](f)
if rec[2].lower() == 'delhi':
count += 1
except EOFError:
[Link]()
print("Total buses to Delhi:", count)

Output:
Total buses to Delhi: 3

18. Write a program to read a CSV file.


import csv
f = open('[Link]', 'r')
r = [Link](f)
for row in r:
print(row)
[Link]()

Output:
['101', 'Asha', '50000']
['102', 'Meera', '60000']

19. Write a program to write data in a CSV file.


import csv
f = open('[Link]', 'w', newline='')
w = [Link](f)
[Link](['EmpNo', 'Name', 'Salary'])
[Link](['101', 'Asha', '50000'])
[Link]()

Output:
Data written successfully.

20. Write a program to search any emp_no from the above program
and display name, salary and an appropriate message if not found.
import csv
emp_no = input("Enter EmpNo to search: ")
found = False
f = open('[Link]', 'r')
r = [Link](f)
for row in r:
if row[0] == emp_no:
print("Name:", row[1])
print("Salary:", row[2])
found = True
if not found:
print("Record not found.")
[Link]()

Output:
Enter EmpNo to search: 101
Name: Asha
Salary: 50000

You might also like