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

Computer Science Practical Programs1

The document contains a series of Python programming exercises that cover various topics such as palindrome checking, ASCII code conversion, string analysis, basic calculator functions, variable scope, file handling, and data structures like stacks. Each exercise includes code snippets demonstrating the implementation of the concepts. The document serves as a practical guide for learning and applying fundamental programming skills in Python.

Uploaded by

palakkishimoto
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)
2 views10 pages

Computer Science Practical Programs1

The document contains a series of Python programming exercises that cover various topics such as palindrome checking, ASCII code conversion, string analysis, basic calculator functions, variable scope, file handling, and data structures like stacks. Each exercise includes code snippets demonstrating the implementation of the concepts. The document serves as a practical guide for learning and applying fundamental programming skills in Python.

Uploaded by

palakkishimoto
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

Computer science practical programs

1. Write a program to check a number whether it is palindrome or not.

n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")

2. Write a program to display ASCII code of a character and vice versa.

c = input("enter a string...")
print("The ASCII value of " ,c ,"is", ord(c))
c =int( input("enter a ascii code..."))
print(chr(c))

3. Python program to count the number of vowels, consonants in a string.


str1 = input("Please Enter Your Own String : ")
vowels = 0
consonants = 0

for i in str1:
if(i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u'
or i == 'A' or i == 'E' or i == 'I' or i == 'O' or i == 'U'):
vowels = vowels + 1
else:
consonants = consonants + 1

print("Total Number of Vowels in this String = ", vowels)


print("Total Number of Consonants in this String = ", consonants)

4. Write a program to make a simple calculator with user defined function.

def add(n1, n2):


return n1 + n2

def sub(n1, n2):


return n1 - n2

def mul(n1, n2):


return n1 * n2

def div(n1, n2):


return n1 / n2

print("Please select operation -\n"


"1. Add\n"
"2. Subtract\n"
"3. Multiply\n"
"4. Divide\n")

sel = int(input("Select operation (1-4): "))

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


n2 = int(input("Enter second number: "))

if sel == 1:
print(n1, "+", n2, "=", add(n1, n2))
elif sel == 2:
print(n1, "-", n2, "=", sub(n1, n2))
elif sel == 3:
print(n1, "*", n2, "=", mul(n1, n2))
elif sel == 4:
print(n1, "/", n2, "=", div(n1, n2))
else:
print("Invalid input")

5. Write a program to explain Global and Local variables in function


global_var = 10

def my_function():
# Local variable
local_var = 5
print("Inside function:")
print("Global variable:", global_var) # Accessing global variable
print("Local variable:", local_var)

# Accessing global variable outside the function


print("Outside function:")
print("Global variable:", global_var)

my_function()
6. Python program to find factorial of a user given no by user defined fact().
def fact(n):
if n == 0:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result

num = int(input("Enter a non-negative integer: "))

if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"The factorial of {num} is {fact(num)}")

7. Write a User-Defined Function to demonstrate the use of Default, Keyword and Positional
arguments.

def example_function(a, b=2, c=3):

print(f"a: {a}, b: {b}, c: {c}")

# Calling the function with only positional arguments.


example_function(1) # Output: a: 1, b: 2, c: 3

# Calling the function with positional and a keyword argument.


example_function(1, c=5) # Output: a: 1, b: 2, c: 5

# Calling the function with all keyword arguments.


example_function(a=1, b=4, c=6) # Output: a: 1, b: 4, c: 6
# Calling the function with positional and default arguments.
example_function(1, 4) # Output: a: 1, b: 4, c: 3

8. Write Python script to show how a list is passed as an argument to a function.

def modify_list(my_list):
"""
This function takes a list as an argument and modifies it by
appending a new element.
"""
my_list.append(4)
print("List inside the function:", my_list)

# Example usage
my_list = [1, 2, 3]
print("List before function call:", my_list)

modify_list(my_list)

print("List after function call:", my_list)


9. Write a Program to read data from data file and show Data File Handling related functions utility
in python.

f=open("[Link]",'r')
print([Link])
f_contents=[Link]()
print(f_contents)
f_contents=[Link]()
print(f_contents)
f_contents=[Link]()
print(f_contents)
for line in f:
print(line, end='')
f_contents=[Link](50)
print(f_contents)
size_to_read=10
f_contents=[Link](size_to_read)
while len(f_contents)>0:
print(f_contents)
print([Link]())
f_contents=[Link](size_to_read)

10.
Write a Program to read data from data file in append mode and use writeLines function utility in
python.

#Program to read data from data file in append mode


af=open("[Link]",'a')
lines_of_text = ("One line of text here”,\ “and another line here”,\ “and yet another here”, “and
so on and so forth")
[Link]('\n' , lines_of_text)
[Link]()
11.
Create a binary file with name and roll no.
Search for a given roll number and display the
name, if not found display appropriate message.
import pickle

def create_file(name, roll_number):


with open('[Link]', 'ab') as file:
[Link]((name, roll_number), file)

def search_roll_number(roll_number):
with open('[Link]', 'rb') as file:
while True:
try:
name, number = [Link](file)
if number == roll_number:
return name
except EOFError:
break
return None

# Create some data


create_file('John Doe', 1)
create_file('Jane Doe', 2)

# Search for a roll number


name = search_roll_number(1)
if name is not None:
print(f'Name: {name}')
else:
print('Roll number not found.')
12. A binary file “[Link]” has structure [rollno, name, marks]. i. Write a user defined function
insertRec() to input data for a student and add to [Link]. ii. Write a function
searchRollNo( r ) in Python which accepts the student’s rollno as parameter and searches the
record in the file “[Link]” and shows the details of student i.e. rollno, name and marks (if
found) otherwise shows the message as ‘No record found’.

import pickle

def insertRec():
"""Inputs student data and appends it to '[Link]'."""
rollno = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
student_data = (rollno, name, marks)

try:
with open("[Link]", "ab") as file:
[Link](student_data, file)
print("Record inserted successfully.")
except Exception as e:
print(f"Error inserting record: {e}")

def searchRollNo(r):
"""Searches for a student record by roll number in
'[Link]'.

Args:
r (int): The roll number to search for.
"""
found = False
try:
with open("[Link]", "rb") as file:
while True:
try:
student = [Link](file)
if student[0] == r:
print("Record found:")
print(f"Roll Number: {student[0]}")
print(f"Name: {student[1]}")
print(f"Marks: {student[2]}")
found = True
break
except EOFError:
break
except FileNotFoundError:
print("File '[Link]' not found.")
return

if not found:
print("No record found.")

x=int(input(“enter roll no...”))


insertRec()
searchRollNo(x)

13. A csv file “[Link]” stores the following details for each student : rollno, name, marks Write a
menu-driven program using User defined functions that performs the following tasks on the csv
file “[Link]”: a. Append records to the csv file. b. Show all records stored in the csv file. c.
Search and display the student record from the csv file on the basis of the roll number passed
as an argument. d. Search and display the student record from the csv file on the basis of the
name passed as an argument.

import csv

def add_record(filename):

"""
Appends a new student record to the CSV file.
"""

rollno = input("Enter Roll Number: ")

name = input("Enter Name: ")

marks = input("Enter Marks: ")

with open(filename, "a", newline="") as csvfile:

writer = [Link](csvfile)

[Link]([rollno, name, marks])

def show_all_records(filename):

"""
Displays all student records from the CSV file.
"""

with open(filename, "r", newline="") as csvfile:

reader = [Link](csvfile)

for row in reader:

print(f"Roll No: {row[0]}, Name: {row[1]}, Marks: {row[2]}")


def search_by_rollno(filename, rollno):

"""
Searches for a student record by roll number and displays it.
"""

found = False

with open(filename, "r", newline="") as csvfile:

reader = [Link](csvfile)

for row in reader:

if row[0] == rollno:

print(f"Roll No: {row[0]}, Name: {row[1]}, Marks: {row[2]}")

found = True

if not found:

print("Student not found")

def search_by_name(filename, name):

"""
Searches for a student record by name and displays it.
"""

found = False

with open(filename, "r", newline="") as csvfile:

reader = [Link](csvfile)

for row in reader:

if row[1] == name:

print(f"Roll No: {row[0]}, Name: {row[1]}, Marks: {row[2]}")

found = True

if not found:

print("Student not found")

def main():

filename = "[Link]"

while True:

print("\nMenu:")

print("1. Add Record")


print("2. Show All Records")

print("3. Search by Roll Number")

print("4. Search by Name")

print("5. Exit")

choice = input("Enter your choice: ")

if choice == "1":

add_record(filename)

elif choice == "2":

show_all_records(filename)

elif choice == "3":

rollno = input("Enter Roll Number to search: ")

search_by_rollno(filename, rollno)

elif choice == "4":

name = input("Enter Name to search: ")

search_by_name(filename, name)

elif choice == "5":

break

else:

print("Invalid choice")

if __name__ == "__main__":

main()

14. Write a Program to read data from data file in read mode and append the words starting with
letter ‘T’ in a given file in python.

f=open("[Link]",'r')
read=[Link]()
[Link]()
id=[]
for ln in read:
if [Link]("T"):
[Link](ln)
print(id)

15. Write a program to delete a record from binary file.

import pickle
roll = input('Enter roll number whose record you want to delete:')
file = open("[Link]", "rb+")
list = [Link](file)
found = 0
lst = []
for x in list:
if roll not in x['roll']:
[Link](x)
else:
found = 1
if found == 1:
[Link](0)
[Link](lst, file)
print("Record Deleted ")
else:
print('Roll Number does not exist')
[Link]()

16. Write a program to generate random numbers between 1 to 6 and check whether a user won a
lottery or not.

17. Write a python program for linear search.

L=eval(input("Enter the elements: "))


n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break

18. Write a python program for bubble sort.

L=eval(input("Enter the elements:"))


n=len(L)
for p in range(0,n-1):
for i in range(0,n-1):
if L[i]>L[i+1]:
L[i],L[i+1]=L[i+1],L[i]

print("The sorted list is : ", L)

19. Write a python program to search an element with binary search method.

def binary_search(arr, target):

low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2

if arr[mid] == target:
return mid

elif arr[mid] < target:


low = mid + 1

else:
high = mid - 1

return -1

# Example usage:
my_list = eval(input("enter a sorted list.."))
target_value = int(input("enter searching element..."))

result = binary_search(my_list, target_value)

if result != -1:
print(f"Element found at index: {result}")
else:
print("Element not found in the list.")
20. Write a menu based program to perform the operation on stack in python.

def push(stack, item):


[Link](item)
print(f"Element {item} pushed to stack.")

def pop(stack):
if not stack:
return "Stack Underflow! The stack is empty."
return f"Popped element: {[Link]()}"

def peek(stack):
if not stack:
return "Stack is empty."
return f"Top element is: {stack[-1]}"
def display(stack):
if not stack:
print("Stack is empty.")
else:
print("Stack elements (Top to Bottom):")
# Display from the last element added to the first
for item in reversed(stack):
print(item)

def main():
stack = []
while True:
print("\n--- STACK OPERATIONS MENU ---")
print("1. Push (Add element)")
print("2. Pop (Remove element)")
print("3. Peek (View top element)")
print("4. Display entire stack")
print("5. Exit")

try:
choice = int(input("Enter your choice (1-5): "))

if choice == 1:
element = input("Enter element to push: ")
push(stack, element)
elif choice == 2:
print(pop(stack))
elif choice == 3:
print(peek(stack))
elif choice == 4:
display(stack)
elif choice == 5:
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice! Please select between 1 and 5.")
except ValueError:
print("Invalid input! Please enter a numeric choice.")

main()

21.
22.
23.
24.
25.

You might also like