0% found this document useful (0 votes)
26 views

Xii Cs Practicals

The document contains 14 Python programs related to various operations on databases and files. Program 1 calculates arithmetic operations on inputted numbers. Program 2 checks if a number is a perfect square. Program 3 checks if a number is Armstrong. Program 4 calculates the factorial of a number. Program 5 prints the Fibonacci series for a given number of terms. Program 6 checks if a string is a palindrome. Program 9 demonstrates file handling functions in Python. Program 10 appends lines of text to a file. Program 11 counts the occurrences of a word in a file. Program 12 appends lines starting with 'T' to a list. Program 13 demonstrates MySQL database connectivity in Python. Program 14 implements stack operations using lists.

Uploaded by

Keshav Rana
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)
26 views

Xii Cs Practicals

The document contains 14 Python programs related to various operations on databases and files. Program 1 calculates arithmetic operations on inputted numbers. Program 2 checks if a number is a perfect square. Program 3 checks if a number is Armstrong. Program 4 calculates the factorial of a number. Program 5 prints the Fibonacci series for a given number of terms. Program 6 checks if a string is a palindrome. Program 9 demonstrates file handling functions in Python. Program 10 appends lines of text to a file. Program 11 counts the occurrences of a word in a file. Program 12 appends lines starting with 'T' to a list. Program 13 demonstrates MySQL database connectivity in Python. Program 14 implements stack operations using lists.

Uploaded by

Keshav Rana
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
You are on page 1/ 21

Practical File

Class XII - Computer Science with Python(083)


Program 1: Program to enter two numbers and print the arithmetic operations like +,-,*,
/, // and %.

Solution:

#Program for Arithmetic Calculator

result = 0

val1 = float(input("Enter the first value :"))

val2 = float(input("Enter the second value :"))

op = input("Enter any one of the operator (+,-,*,/,//,%)")

if op == "+":

result = val1 + val2

elif op == "-":

result = val1 - val2

elif op == "*":

result = val1 * val2

elif op == "/":

if val2 == 0:

print("Please enter a value other than 0")

else:

result = val1 / val2

elif op == "//":

result = val1 // val2

else:

result = val1 % val2


print(‘The result is: ’, result)
Program 2: Write a program to find whether an inputted number is perfect square or not.

Solution:

# To find whether a number is perfect square or not

def pernum(num):

divsum=0

for i in range(1,num):

if num%i == 0:

divsum+=i

if divsum==num:

print('Perfect square')

else:

print('Not a perfect number')

pernum(9)

pernum(15)
Program 3: Write a Program to check if the entered number is Armstrong or not.

Solution:

# Program to check if the entered number is Armstrong or not.

#An Armstrong number has sum of the cubes of its digits is equal to the number itself

no=int(input("Enter any number to check : "))

no1 = no

sum = 0

while(no>0):

ans = no % 10;

sum = sum + (ans * ans * ans)

no = int (no / 10)

if sum == no1:

print("Armstrong Number")

else:

print("Not an Armstrong Number")


Program 4: Write a Program to find factorial of the entered number.

Solution:

#Program to calculate the factorial of an inputted number (using while loop)

num = int(input("Enter the number for calculating its factorial : "))

fact = 1

i=1

while i<=num:

fact = fact*i

i=i+1

print("The factorial of ",num,"=",fact)


Program 5: Write a Program to enter the number of terms and to print the Fibonacci
Series.

Solution:

#fibonacci

i =int(input("enter the limit:"))

x=0

y=1

z=1

print("Fibonacci series \n")

print(x, y,end= " ")

while(z<= i):

print(z, end=" ")

x=y

y=z

z=x+y
Program 6: Write a Program to enter the string and to check if it’s palindrome or not using loop.

Solution:

# Program to enter the string and check if it’s palindrome or not using ‘for’ loop.

msg=input("Enter any string : ")

newlist=[]

newlist[:0]=msg

l=len(newlist)

ed=l-1

for i in range(0,l):
if newlist[i]!=newlist[ed]:

print ("Given String is not a palindrome")

break

if i>=ed:

print ("Given String is a palindrome")

break

l=l-1

ed = ed - 1
Program9: Write a Program to read data from data file and show Data File Handling related functions
utility in python.

Solution:

f=open("test.txt",'r')

print(f.name)

f_contents=f.read()

print(f_contents)

f_contents=f.readlines()

print(f_contents)

f_contents=f.readline()

print(f_contents)

for line in f:

print(line, end='')

f_contents=f.read(50)

print(f_contents)

size_to_read=10

f_contents=f.read(size_to_read)
while len(f_contents)>0:

print(f_contents)

print(f.tell())

f_contents=f.read(size_to_read)

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

Solution:
#Program to read data from data file in append mode

af=open("test.txt",'a')

lines_of_text = ("One line of text here”,\ “and another line here”,\

“and yet another here”, “and so on and so forth")

af.writelines('\n' + lines_of_text)

af.close()
Program 11: Write a Program to read data from data file in read mode and count the particular word occurrences in
given string, number of times in python.

Solution:

#Program to read data from data file in read mode and #count the particular word occurrences in given

string, #number of times in python.

f=open("test.txt",'r')

read=f.readlines() f.close()

times=0

#the variable has been created to show the number of times the loop runs times2=0 #the variable

has been created to show the number of times the loop runs

chk=input("Enter String to search : ")

count=0

for sentence in read:

line=sentence.split() times+=1

for each in line: line2=each

times2+=1

if chk==line2: count+=1
print("The search String ", chk, "is present : ", count, "times") print(times)

print(times2)

Program 12: 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.

Solution:
#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("test.txt",'r')

read=f.readlines() f.close()

id=[]

for ln in read:

if ln.startswith("T"):

id.append(ln)

print(id)
Program 13: Write a Program to show MySQL database connectivity in python.

Solution:

import mysql.connector

con=mysql.connector.connect(host='localhost',user='root',password='',db='school')

stmt=con.cursor()

query='select * from student;'

stmt.execute(query)

data=stmt.fetchone()

print(data)
Program 14: Write a Python program to implement all basic operations of a stack, such as
adding element (PUSH operation), removing element (POP operation) and displaying the
stack elements (Traversal operation) using lists.

Solution:

#Implementation of List as stack

s=[]

c="y"

while (c=="y"):

print ("1. PUSH")


print ("2. POP ")

print ("3. Display")

choice=int(input("Enter your choice: "))

if (choice==1):

a=input("Enter any number :")

s.append(a)

elif (choice==2):

if (s==[]):

print ("Stack Empty")

else:

print ("Deleted element is : ",s.pop())

elif (choice==3):

l=len(s)

for i in range(l-1,-1,-1): #To display elements from last element to first

print (s[i])

else:

print("Wrong Input")

c=input("Do you want to continue or not? ")


Program 20: Perform all the operations with reference to table ‘Employee’ through
MySQL-Python connectivity.

Solution:

import MySQLdb

# Using connect method to connect database

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

# using cursor() method for preparing cursor

cursor = db1.cursor()

# Preparing SQL statement to create EMP table

sql = "CREATE TABLE EMP(empno integer primary key,ename varchar(25) not null,salary float);"

cursor.execute(sql)

# disconnect from server db1.close()


Inserting a record in ‘emp’

import MySQLdb

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

cursor = db1.cursor()

# Prepareing SQL statement to insert one record with the given values

sql = "INSERT INTO EMP VALUES (1,'ANIL KUMAR',86000);"

try:

cursor.execute(sql)

db1.commit()
except:

db1.rollback()

db1.close()

Fetching all the records from EMP table having salary more than 70000.

import MySQLdb

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

cursor = db1.cursor()

sql = "SELECT * FROM EMP WHERE SALARY > 70000;"

try:

cursor.execute(sql)

#using fetchall() function to fetch all records from the table EMP and store in
resultset

resultset = cursor.fetchall()

for row in resultset:

print (row)

except:

print ("Error: unable to fetch data")

db1.close()
Updating record(s) of the table using UPDATE

import MySQLdb

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

cursor = db1.cursor()

#Preparing SQL statement to increase salary of all employees whose salary is less than
80000

sql = "UPDATE EMP SET salary = salary +1000 WHERE salary<80000;"

try:

cursor.execute(sql)

db1.commit()

except:

db1.rollback()

db1.close()
Deleting record(s) from table using DELETE

import MySQLdb

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

cursor = db1.cursor()

sal=int(input("Enter salary whose record to be deleted : "))

#Preparing SQL statement to delete records as per given condition

sql = "DELETE FROM EMP WHERE salary =sal”

try:

cursor.execute(sql)

print(cursor.rowcount, end=" record(s) deleted ")

db1.commit()

except:

db1.rollback()

db1.close()

Output:

>>> Enter salary whose record to be deleted: 80000

1 record(s) deleted

>>>

You might also like