Final CS Practical
Final CS Practical
or not
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 ##
>>>
def is_perfect(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n
Sample Input:
Enter a number: 6
Output:
6 is perfect: True
Program 3: To check whether the given number is armstrong or not
if num == sum_of_powers:
print(str(num) + " is an Armstrong number.")
else:
print(str(num) + " is not an Armstrong number.")
OUTPUT
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))
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]
OUTPUT
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.
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")
OUTPUT
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 =
pickle.dump(student, file)
try:
while True:
student = pickle.load(file)
if student['rollno'] == rollno:
student['marks'] = new_marks
except EOFError:
pickle.dump(student, file)
if updated:
else:
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)
OUTPUT
Sample Input:
Output:
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)
Sample Input:
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:
Output:
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))
def search_password(filename):
except FileNotFoundError :
print(f"{filename} not found.")
return found_flag,password
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
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 :
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
Page : 18
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :4
(Top) 20 <== 10 <==
Page : 19
Program 19: SQL Queries
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
connection.cursor()
cursor.execute("SELECT * FROM
connection.close()
OUTPUT
import mysql.connector
mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password
"
, database="your_database"
connection.cursor()
result = cursor.fetchone()
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"