XII-E Practical File 23-24
XII-E Practical File 23-24
XII-E Practical File 23-24
Aim:
To write a Python program to calculate factorial of a number using function.
Algorithm:
1. Start.
2. Get input number from the user.
3. Call user defined function by passing the number as an argument.
4. Calculate factorial of the passed argument and return the value.
5. Print the result.
6. Stop.
Sample Output:
Input a number to compute the factorial: 5
Factorial of 5 is: 120
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.2. Program to find the number of upper case and lower case letters
in a string.
Aim:
To write a Python program to find the number of upper case and lower
case letters in a string which is passed as an argument to the function.
Algorithm:
1. Start.
2. Read string input from the user.
3. Call the user defined function by passing string as an argument.
4. Find the number of upper case letters and lower case letters using
built in functions.
5. Print the result
6. Stop.
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.3. Program to check if a Number is a Prime or not using function.
Aim:
To write a Python program to check if a Number is a Prime or not using
function.
Algorithm:
1. Start
2. Read the number from the user and pass it to the function.
3. Call the function to check whether the entered number is prime or not.
4. If the number is prime function returns True otherwise False.
5. Print the result.
6. Stop.
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.4. Program to find the occurrence of any word in a string.
Aim:
To write a Python program to find the occurrence of any word in a
string which is passed as an argument to function.
Algorithm:
1. Start
2. Read input string from the user.
3. Read the word to be searched in the above string.
4. Call user defined function by passing string and the word as an argument.
5. Split the passed string and count number of words.
6. Return the count value.
7. Print the result.
8. Stop.
Enter any sentence: Meena likes cake and Tina likes chocolate.
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.5. Program to generate random number between 1 – 6 to simulate the
dice.
Aim:
To write a Python program to simulate the dice using random module.
Algorithm:
1. Start.
2. Repeatedly generate random number using randint(1,6) and
display the number with equal time interval.
3. Press CTRL+C to stop generating random number.
4. Print the number.
5. Stop.
import random
import time
print("Press CTRL+C to stop the dice!!!") play='y'
while play=='y':
try:
while True:
for i in range(10):
print()
n = random.randint(1,6)
print(n)
time.sleep(0.5)
except KeyboardInterrupt:
print("\nYour Number is :",n)
ans=input("Play More? (Y) :")
if ans.lower()!='y':
play='n'
break
Sample Output:
Press CTRL+C to stop the
dice!!! 5
3
6
2
2
3
3
4
5
3
Your Number is: 3
Play More? (Y): n
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.6. Program to print Floyd's triangle.
Aim:
To write a Python Program to print Floyd’s Triangle.
Algorithm:
1. Start.
2. Using Nested For Loop we print the Triangle.
3. Stop.
#Floyd's triangle
n=int(input("Enter the number :"))
for i in range(n,0,-1):
for j in range(n,i-1,-1):
print (j,end=' ')
print('\n')
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.7. Program to count number of lines and words in a text file.
Aim:
To write a Python program to count the number of lines and words in a text
file.
Algorithm:
1. Start.
2. Create text file using notepad and save it.
3. Open the created text file in read mode.
4. Apply readlines() to read all the lines and count the number of lines.
5. Now set the file pointer to the beginning of file and read the entire file
and count the number of words using split().
6. Print the result
7. Stop.
Sample Output:
Number of Lines in a text file: 4
Number of Words in a text file: 23
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.8. Program to count number of vowels and consonants in a text file.
Aim:
To write a Python program to count number of vowels and consonants in a
text file.
Algorithm:
1. Start.
2. Create text file using notepad and save it.
3. Open the created text file in read mode.
4. Read each character from the text file and check whether it is vowel
or consonant.
5. Update the counter variable.
6. Print the result
7. Stop.
myfile=open("F:\\TextFile\\Poem.txt","r")
vowels="aeiouAEIOU"
count1=0 count2=0
data=myfile.read()
for i in data:
if i in vowels:
count1=count1+1
else:
count2=count2+1
print("Number of Vowels:",count1)
print("Number of Consonants:",count2)
Sample Output:
Number of Vowels: 38 Number
of Consonants: 78
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.9. Program to copy the content of text file.
Aim:
To write a Python program to copy the content of text file which are starting
with ‘I’ to another file.
Algorithm:
1. Start.
2. Create Source text file using notepad and save it.
3. Open source file in read mode and target file in write mode.
4. Read each line from the source text file and check whether it is
starting with ‘I’.
4. Write the line into target file.
5. Print the content of target file.
6. Stop.
f=open("F:\\textfile\\poem.txt",'r')
f1=open("CopyPoem.txt","w")
while True:
txt=f.readline()
if len(txt)==0:
break
if txt[0]=='I':
f1.write(txt)
print("File Copied!")
print("Contents of new file:")
f.close()
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.10. Program to read a text file line by line and display each word
separated by '#'.
AIM:
#Program
f=open('India.txt', 'r')
contents=f.readlines()
for line in contents:
words=line.split()
for i in words:
print(i+'#', end='')
f.close()
Sample Output:
india#is#my#country#all#indians#are#my#brothers#and#sisters#i#love#my#coun
try#
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.11. Program to create binary file.
Aim:
To write a Python program to create binary file and store the details of
a student.
Algorithm:
1. Start.
2. Import pickle module and open binary file in write mode.
3. Get student details from the user and store it in dictionary variable.
4. Write the record into the file using dump().
5. Open the same file in read mode and read its content using load()
6. Display the content of file.
7. Stop.
Sample Output:
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.12. Program to update the content of binary file.
Aim:
To write a Python program to update the content of binary file.
Algorithm:
1. Start.
2. Import pickle module and open binary file in read/write mode.
3. Get the roll number of a student to identify the record.
4. Read the file using load() and identify the record to be updated.
5. Update the mark of a student and write the updated record back into the
file using dump().
6. Now display the content of updated file.
7. Stop.
import pickle
stu={}
found=False
myfile=open('student.dat','rb+')
n=int(input("Enter Roll number of a student to update his mark:"))
try:
while True:
pos=myfile.tell()
stu=pickle.load(myfile)
if stu['RollNo']==n:
stu['Marks']+=10
myfile.seek(pos)
pickle.dump(stu,myfile)
found=True
except EOFError:
if found==False:
print("No matching record found!")
else:
print("Record Successfully Updated!")
try:
myfile.seek(0)
print("File Content after updation:")
while True:
stu=pickle.load(myfile)
print(stu)
except EOFError:
myfile.close()
myfile.close()
Sample Output:
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.13. Program to create CSV file.
Aim:
Algorithm:
1. Start.
2. Import csv module and open file in write mode.
3. Create writer object and write the product details into the file using
writerow().
4. Open the above created file in read mode using with statement.
5. Read the file using reader object.
6. Display the contents of file.
7. Stop.
Sample Output:
Product 1
Enter Product code: 104
Enter Product Name: Pen
Enter Price:200
Product 2
Enter Product code: 405 Enter
Product Name: Marker Enter
Price: 50
File created
successfully! File
Contents:
-----------------------
['CODE', 'NAME', 'PRICE']
['104', 'Pen', '200.0']
['405', 'Marker', '50.0']
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Ex.No.14. Program to create Stack.
Aim:
To write a Python program to create Stack using an element.
Algorithm:
1. Start
2. To push an item in the stack, use the list function append list.append(item)
3. To pop an item in the stack, use the list function pop list.pop()
4. To get the top most item in the stack, write list[-1]
5. Display the content of the Stack.
6. Stop.
def check_stack_isEmpty(stk):
if stk==[]:
return True
else:
return False
def push(stk,e):
stk.append(e)
top = len(stk)-1
def display(stk):
if check_stack_isEmpty(stk):
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")
for i in range(top-1,-1,-1):
print(stk[i])
def pop_stack(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e
def peek(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
s=[] # An empty list to store stack elements, initially its empty top = None
# This is top pointer for push and pop operation.
def main_menu():
while True:
print("Stack Implementation")
print("1 - Push")
print("2 - Pop")
print("3 - Peek")
print("4 - Display")
print("5 - Exit")
ch = int(input("Enter the your choice:"))
if ch==1:
el = int(input("Enter the value to push an element:"))
push(s,el)
elif ch==2:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("Element popped:",e)
elif ch==3:
e=peek(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("The element on top is:",e)
elif ch==4:
display(s)
elif ch==5:
break
else:
print("Sorry, You have entered invalid option")
main_menu()
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Output
Ex.No.15. Program to create Stack using Employee details. Aim:
Algorithm:
1. Start
2. To push an item in the stack, use the list function append list.append(item)
3. To pop an item in the stack, use the list function pop list.pop()
4. To get the top most item in the stack, write list[-1]
5. Display the content of the Stack.
6. Stop.
def main():
while True:
line()
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
ch=int(input("Enter your choice:"))
if ch==1:
push()
print("Element Pushed")
elif ch==2:
pop_ele()
elif ch==3:
display()
else:
print("Invalid Choice")
break
main()
Output
Result:
Thus, the above Python program has been executed and the output is
verified successfully.
Part B
EX.No.16
5 sets of SQL queries using one/two tables.
In this section Practical file computer science class 12, 5 sets of SQL queries are
required. These queries can be performed either on one or two tables. So here
we go!
Answers:
[4] select
concat(day(now()),concat(‘.’,month(now()),concat(‘.’,year(now()))))
“Date”;
[5] Select right(“Media”,3);
ANSWERS
[1] Create database sports.
[2] Creating table with the given specification.
create table team
-> (teamid int(1),
-> teamname varchar(10), primary key(teamid));
Showing the structure of table using SQL statement:
desc team;
Inserting data:
mqsql> insert into team values(1,'Tehlka');
Answers:
Ex.No.17. Program to fetch all the records from Student Table. Aim:
To write a Python program to fetch all the records from the Student Table.
Algorithm:
1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Fetch all the records from the table using fetchall().
6. Traverse the result set using for loop and print the records.
7. Close the connection using close().
8. Stop.
Program:
Aim:
Algorithm:
1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Execute SQL query with string formatting.
6. Fetch all the records from the table using fetchall().
7. Traverse the result set using for loop and print the records.
8. Close the connection using close().
9. Stop.
Program:
Sample Output:
Ex: No.19. Program to insert records into Table.
Aim:
Algorithm:
1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Execute insert command with string formatting and apply commit() to
save the changes permanently.
6. Execute select query and fetch all the records using fetchall().
7. Traverse the result set using for loop and print the records.
8. Close the connection using close().
9. Stop.
Program:
# Program to insert new record into table.
Sample Output:
Ex.No.20. Program to update records in a table.
Aim:
Algorithm:
1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Execute insert command with string formatting and apply commit() to
save the changes permanently.
6. Execute select query and fetch all the records using fetchall().
7. Traverse the result set using for loop and print the records.
8. Close the connection using close().
9. Stop.
Program:
Sample Output: