0% found this document useful (0 votes)
12 views25 pages

Final CS Practical

The document contains multiple Python programs that perform various tasks, including checking if a number is prime, perfect, Armstrong, or a palindrome, calculating factorials, generating Fibonacci series, and reading/writing to files in different formats. It also includes programs for managing employee records, item records, and user credentials in binary and CSV files, as well as implementing a stack data structure. Each program is accompanied by example inputs and outputs to demonstrate functionality.

Uploaded by

rishikareer394
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)
12 views25 pages

Final CS Practical

The document contains multiple Python programs that perform various tasks, including checking if a number is prime, perfect, Armstrong, or a palindrome, calculating factorials, generating Fibonacci series, and reading/writing to files in different formats. It also includes programs for managing employee records, item records, and user credentials in binary and CSV files, as well as implementing a stack data structure. Each program is accompanied by example inputs and outputs to demonstrate functionality.

Uploaded by

rishikareer394
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/ 25

Program 1: Input any number from user and check it is Prime no.

or not

#Program to input any number from user


#Check it is Prime number of not
import math
num = int(input("Enter any number :"))
isPrime=True
for i in range(2,int(math.sqrt(num))+1):
if num % i == 0:
isPrime=False

if isPrime:
print("## Number is Prime ##")
else:
print("## Number is not Prime ##")

OUTPUT
Enter any number :117
## Number is not Prime ##
>>>
Enter any number :119
## Number is not Prime ##
>>>
Enter any number :113 ##
Number is Prime ##
>>>
Enter any number :7 ##
Number is Prime ##
>>>

Enter any number :19


## Number is Prime
##
Program 2: To check whether the given number is perfect or not.

def is_perfect(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n

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


print(f"{n} is perfect: {is_perfect(n)}")

Sample Input:

Enter a number: 6

Output:

6 is perfect: True
Program 3: To check whether the given number is armstrong or not

num = int(input("Enter a number to check if it is an Armstrong number: "))


sum_of_powers = 0
temp = num
num_digits = len(str(num)) # Count the number of digits

while temp > 0:


digit = temp % 10
sum_of_powers += digit ** num_digits # Sum of digits raised to the power of num_digits
temp //= 10

if num == sum_of_powers:
print(str(num) + " is an Armstrong number.")
else:
print(str(num) + " is not an Armstrong number.")

OUTPUT

EXAMPLE: Example input: 153


OUTPUT: 153 is an Armstrong number
Program 4: To check whether the given number is in palindrome or not.

num = int(input("Enter a number to check if it is a palindrome: ")) # Example input


def is_palindrome(n):
return str(n) == str(n)[::-1]

result = is_palindrome(num)
if result:
print(str(num) + " is a palindrome.")
else:
print(str(num) + " is not a palindrome.")

.
OUTPUT
EXAMPLE: Example input: 121
OUTPUT: 121 is a palindrome
Program 5: Write a function for the factorial of a number.

def factorial(n):
if n == 0:
return 1 else:

return n * factorial(n - 1)

result = factorial(n)
print("Factorial of " + str(n) + " is " + str(result))

EXAMPLE: Example input:


5 OUTPUT: Factorial of 5 is
120

OUTPUT
Enter the 'n' term to find in fibonacci :10 10 th
term of fibonacci series is : 55
Program 6: Write a function for the fibonacci series

def fibonacci(n):
fib_series = [0, 1]
while len(fib_series) < n:
fib_series.append(fib_series[-1] + fib_series[-2]) return

fib_series[:n]

n = int(input("enter the number:"))

print(f"First {n} terms of the Fibonacci series: {fibonacci(n)}")

OUTPUT

enter the number: 8


First 8 terms of the Fibonacci series: [0, 1, 1, 2,
3, 5, 8, 13]
Program 7: Write a function to read a text file line by line and display each word separated
by a #

#Program to read content of file line by line #and


display each word separated by '#'
f = open("file1.txt")
for line in f:
words =
line.split() for
w in words:
print(w+'#',end='')
print()
f.close()

NOTE : if the original content of file is:


India is my country I
love python
Python learning is fun

OUTPUT
India#is#my#country#
I#love#python#
Python#learning#is#fun#
Program 8: Program to read the content of file and display the total number of consonants,
uppercase, vowels and lower case characters‟

f = open("file1.txt")
v=0
c=0
u=0
l=0
o=0
data = f.read()
vowels=['a','e','i','o','u'] for
ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1

if ch.isupper():
u+=1

elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
print("Total Vowels in file:",v)
print("Total Consonants in file:",c)
print("Total Capital letters in file:",u)
print("Total Small letters in file:",l)
print("Total Other than letters:",o)
f.close()
NOTE : if the original content of file is:
India is my country
I love python
Python learning is fun 123@

OUTPUT
Total Vowels in file 16
Total Consonants in file 30
Total Capital letters in file 2
Total Small letters in file Total Other than letters : 44
:4
Program 9: Program to count the number of words in a file.

file_name = input("Enter the filename to count words (e.g., sample.txt): ")


def count_words(file_name):
try:
with open(file_name, 'r') as file:
text = file.read()
words =
text.split() return
len(words)
except FileNotFoundError:
print("File not found.")
return None

word_count = count_words(file_name)
if word_count is not None:
print("Number of words: " + str(word_count))

OUTPUT
EXAMPLE: Example input: sample.txt
OUTPUT:Assuming 'sample.txt' contains "Hello World! Welcome to Python.": Number of words: 6
f1 = open("file2.txt")
f2 = open("file2copy.txt","w")

for line in f1:


if 'a' not in line:
f2.write(line) print(“## File ”)
Copied Successfully! ## f1.close()
f2.close()

NOTE: Content of file2.txt a quick


brown fox one two three four
five six seven
India is my country eight nine ten
bye!

OUTPUT

## File Copied Successfully! ##

NOTE: After copy content of


file2copy.txt

one two three four five six


seven eight nine ten bye!

Page : 12
Program 11: Program to create binary file to store Rollno,Name and Marks and update
marks of entered Rollno

import pickle
def create_initial_binary_file(filename): students =

[{'rollno': 1, 'name': 'Alice', 'marks': 85},{'rollno': 2,

'name': 'Bob', 'marks': 90},{'rollno': 3, 'name':

'Charlie', 'marks': 78}]

with open(filename, 'wb') as file:

for student in students:

pickle.dump(student, file)

print(f"Initial data written to {filename}")

def update_marks(filename, rollno, new_marks):

updated = False students = []

with open(filename, 'rb') as file:

try:

while True:

student = pickle.load(file)

if student['rollno'] == rollno:

student['marks'] = new_marks

updated = True students.append(student)

except EOFError:

pass with open(filename, 'wb') as file:

for student in students:

pickle.dump(student, file)

if updated:

print(f"Updated marks for roll number {rollno}")

else:

print(f"Roll number {rollno} not found")

create_initial_binary_file('students.dat')

update_marks('students.dat', 2, 95)
OUTPUT

Initial data
written to
students.dat

Updated marks
for roll number 2
Program 12: a program to read and write employee records in a binary file

import pickle

filename =
'employees.dat'
employee_records = []

while True:
emp_id = input("Enter employee ID (or type 'exit' to finish): ")
if emp_id.lower() == 'exit':
break
name = input("Enter employee name: ")
salary = float(input("Enter salary: "))
employee_records.append((emp_id, name, salary))

with open(filename,'wb') as f:
pickle.dump(employee_records, f)

print(f"Employee records saved to {filename}.")

OUTPUT
Sample Input:

Enter employee ID (or type


'exit' to finish): 101
Enter employee name: John Doe
Enter salary: 50000
Enter employee ID (or type
'exit' to finish): 102
Enter employee name: Jane Smith
Enter salary: 60000
Enter employee ID (or type
'exit' to finish): exit

Output:

Employee records saved to


employees.dat
Program 13: Write a program to enter the following records in a binary file: Item No
(integer), Item Name (string), Quantity (integer), Price (float)

import pickle

filename = 'employees.dat'
employee_records = []

while True:
emp_id = input("Enter employee ID (or type 'exit' to finish): ")
if emp_id.lower() == 'exit':
break
name = input("Enter employee name: ")
salary = float(input("Enter salary: "))
employee_records.append((emp_id, name, salary))

with open(filename,'wb') as f:
pickle.dump(employee_records, f)

print(f"Employee records saved to {filename}.")

Sample Input:

Number of items to enter: 2


Item No: 1
Item Name: Book
Quantity: 10
Price per item: 100.0
Item No: 2
Item Name: Pen
Quantity: 20
Price per item: 50.0

Output:
Items saved to
items.dat. Items:
Item No:1, Item Name:Book, Quantity:10, Price per item:100.0, Amount:1000.0
Item No:2, Item Name:Pen, Quantity:20, Price per item:50.0, Amount:1000.0
Program 14: Program to delete a specified record from a binary file

import pickle

filename='items.dat'

def delete_item_record(filename):
item_no_to_delete=int(input("Enter Item No to delete :"))
try :
with open(filename,'rb') as f :
items=pickle.load(f)
items=[item for item in items if item!=item_no_to_delete]
with open(filename,'wb') as f :
pickle.dump(items,f)
print(f"Item No {item_no_to_delete} deleted successfully.")
except FileNotFoundError :
print(f"{filename} not found.")

delete_item_record(filename)

Sample Input:

Enter Item No to delete: 1

Output:

Item No 1 deleted successfully.


Program 15: Program to create a CSV file by entering user ID and password and search the
password for the given user ID.

import csv

def create_csv_file(filename):
user_data=[]
while True :
user_id=input("Enter user ID (or type 'exit' to finish): ")
if user_id.lower()=='exit':
break
password=input("Enter password :")
user_data.append((user_id,password))

with open(filename , mode='w',newline='') as f :


writer=csv.writer(f)
writer.writerow(["User ID","Password"])
writer.writerows(user_data)
print(f"Data saved to {filename}.")

def search_password(filename):

user_id_to_search=input("Enter User ID to search password :")


try :
with open(filename) as f :
reader=csv.reader(f)
next(reader)
found_flag=False
password=None

for row in reader :


if row==user_id_to_search :
found_flag=True
password=row[1]
break

except FileNotFoundError :
print(f"{filename} not found.")

return found_flag,password

found_flag,password=search_password('users.csv') if found_flag : print("Password for " + user_id_to_search + ": " + password)


else : print(user_id_to_search + " User ID not found.")
Program 16: To perform read and write operations in a csv

import csv

def read_write_csv(source_file,dest_file):
try :
with open(source_file) as src_f :
reader=csv.reader(src_f)
with open(dest_file , mode='w', newline='') as dest_f :
writer=csv.writer(dest_f)
for row in reader :
writer.writerow(row)
print(f"Data copied from {source_file} to {dest_file}.")

except FileNotFoundError :
print(f"{source_file} or {dest_file} not found.")

OUTPUT
EXAMPLE : Example input : Source file:user.csv Destination file:create_users.csv

OUTPUT:data copied from users.csv to create_users.csv.


Program 17: Write a program to generate random numbers between to 6 and Check
whether a user has won the lottery or not.

import random

def lottery_game():
winning_numbers=random.sample(range(1,7),k=3)
user_numbers_input=input("Enter your three lottery numbers (separated by space): ")
user_numbers=list(map(int,user_numbers_input.split()))

return winning_numbers==set(user_numbers),winning_numbers

won_flag,winner_numbers_result=lottery_game()

if won_flag :
print ("Congratulations! You've won!")
else :
print ("You lost! Winning numbers were:" +str(winning_numbers_result))

EXAMPLE :

Example input : Enter your three lottery numbers (separated by space): `1 2 3`

OUTPUT : If the user's numbers match:`Congratulations! You've won!` Otherwise:`You lost! Winning
numbers were:` followed by the winning numbers
Program 18 : Program to implement Stack in Python using List

def isEmpty(S):
if len(S)==0:
return True
else:
return False

def Push(S,item):
S.append(item)
top=len(S)-1

def Pop(S):
if isEmpty(S):
return "Underflow"
else:
val = S.pop()
if len(S)==0:
top=None
else:
top=len(S)-1
return val

def Peek(S):
if isEmpty(S):
return "Underflow"
else:
top=len(S)-1
return S[top]

def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()
# main begins here
S=[] #Stack
top=None
while True:
print("**** STACK DEMONSTRATION ******")
print("1. PUSH ")
print("2. POP")
print("3. PEEK")
print("4. SHOW STACK ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Push :"))
Push(S,val)
elif ch==2:
val = Pop(S)
if val=="Underflow":
print("Stack is Empty")
else:
print("\nDeleted Item was :",val)
elif ch==3:
val = Peek(S)
if val=="Underflow":
print("Stack Empty")
else:
print("Top Item :",val)
elif ch==4:
Show(S)
elif ch==0:
print("Bye")
break

OUTPUT
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :10

Cont…
Page : 17
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :20

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :30

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :4
(Top) 30 <== 20 <== 10 <==

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :3
Top Item : 30

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :2

Deleted Item was : 30

Page : 18
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :4
(Top) 20 <== 10 <==

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :0
Bye

Page : 19
Program 19: SQL Queries

import mysql.connector

# Establish a connection to the database

connection = mysql.connector.connect(

host="localhost",

user="your_username",

password="your_password",

database="your_database"

# Create a cursor object cursor =

connection.cursor()

# Execute a SQL query

cursor.execute("SELECT * FROM

employees") # Fetch all the rows rows =

cursor.fetchall() # Print each row for

row in rows: print(row) # Close the

cursor and connection cursor.close()

connection.close()

OUTPUT

(1, 'John Doe', 'Sales')


(2, 'Jane Smith', 'Marketing')
Program 20: Aggregate function in SQL

import mysql.connector

# Establish a connection to the database connection =

mysql.connector.connect(

host="localhost",

user="your_username",

password="your_password

"

, database="your_database"

# Create a cursor object cursor =

connection.cursor()

# Execute a SQL query with aggregate functions

cursor.execute("SELECT AVG(salary) AS average_salary, COUNT(*) AS num_employees FROM employees")

# Fetch the result

result = cursor.fetchone()

# Print the result

print("Average salary:", result[0])


print("Number of employees:", result[1])

# Close the cursor and connection cursor.close()

connection.close()
Program 21: Connect to python with MySQL using database connectivity

import mysql.connector

def connect_to_db():
# Connect to the MySQL database

connection = mysql.connector.connect(

host="localhost",

user="your_username",

password="your_password",

database="your_database"

You might also like