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

Xii Practical File

The document contains 12 programs with their aims, code, and outputs. The programs demonstrate various Python concepts like functions, loops, files, dictionaries, CSV files etc. and solve problems like calculating electricity bill, checking prime numbers, Armstrong numbers, factorials, string operations, file handling and more.

Uploaded by

Ekta Bajaj
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 views28 pages

Xii Practical File

The document contains 12 programs with their aims, code, and outputs. The programs demonstrate various Python concepts like functions, loops, files, dictionaries, CSV files etc. and solve problems like calculating electricity bill, checking prime numbers, Armstrong numbers, factorials, string operations, file handling and more.

Uploaded by

Ekta Bajaj
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/ 28

Program – 1

Aim: Program to calculate the electricity bill

The table for charges is given as under:

Code:

# Program to calculate the electricity bill

power=int(input('enter the power of metre(in kwh)'))


units=int(input('enter the units consumed'))

fixed_charge=power*110
unit_charge=0
if units<=150:
unit_charge=units*5.5
elif units<=300:
unit_charge=units*6
elif units<=500:
unit_charge=units*6.5
else:
unit_charge=units*7
total=fixed_charge+unit_charge
print('the electricity bill charges Rs.',total)

Output:

enter the power of metre(in kwh)3


enter the units consumed512
the electricity bill charges Rs. 3914
Program – 2

Aim: Program to check whether the given number is prime or not

Code:

# Program to check whether the number is prime or not

n=int(input('enter the number'))


flag=False
for i in range(2,n//2):
r=n%i
if r==0:
flag=True
break
if flag==True:
print('the given number is composite')
else:
print('the given number is prime')

Output:

enter the number33


the given number is composite
Program – 3

Aim: Program to check whether the number is armstrong or not

# Program to check whether the number is armstrong or not

n=int(input('enter the number'))


flag=False

# count the number of digits


count=0
temp=n
while temp>0:
temp=temp//10
count=count+1

# find the total using power


sum=0
temp2=n
while temp2>0:
r=temp2%10
sum=sum+r**count
temp2=temp2//10

if sum==n:
print('the given number is armstrong')
else:
print('the given number is not armstrong')

Output:

enter the number153


the given number is armstrong
Program – 4

Program to find the factorial of a number using function

# Program to find the factorial of a number


def fact(n):
val=1
for i in range(1,n+1,1):
val=val*i
return val

v=int(input('enter the number'))


factorial=fact(v)
print("the factorial value of",v,"is:",factorial)

Output:

enter the number5


the factorial value of 5 is: 120
Program – 5

Program to input a string having some digits and calculate the sum of digits present in the string

# Program to input a string having some digits and calculate the sum of digits present in the string

s=input('enter the string: ')


sum=0
for i in s:
if i.isdigit():
sum=sum+int(i)

print('the sum of digits present in the string is:',sum)

Output:

enter the string: Hi,1,2,3,Go


the sum of digits present in the string is: 6
Program – 6

Program to input a string and count the number of vowels and consonants in the string

# Program to input a string and count the number of vowels and consonants in the string

s=input('enter the string: ')


n_vowels=0
n_consonants=0

for i in s:
if i in 'aeiouAEIOU':
n_vowels +=1
elif i.isalpha():
n_consonants +=1

print('the number of vowels :',n_vowels)


print('the number of consonants :',n_consonants)

Output:

enter the string: Hello, I am a computer programmer


the number of vowels : 11
the number of consonants : 16
Program – 7

Program to create a dictionary of names and their marks and display those names who
have scored more than 75

# Program to create a dictionary of names and their marks and display those names who have scored more than 75

n=int(input('enter the number of students'))


dict={}
for i in range(n):
print('student no',i+1)
name=input('enter the name')
marks=int(input('enter his/her marks'))
dict[name]=marks

l=[]
for key in dict:
if dict[key]>75:
l.append(key)

print('the list of students who scored marks greater than 75 are:',l)

Output:

enter the number of students5


student no 1
enter the namemyra
enter his/her marks77
student no 2
enter the nameaman
enter his/her marks95
student no 3
enter the namepriya
enter his/her marks65
student no 4
enter the namesahil
enter his/her marks80
student no 5
enter the nameMohit
enter his/her marks45
the list of students who scored marks greater than 75 are: ['myra', 'aman', 'sahil']
Program – 8

Program to read a text file and display each word separated by a #

# Program to read a text file and display each word separated by #


fh=open('read.txt','r')
str=fh.readline()
while str:
l=str.strip().split(" ")
for i in l:
print(i,end='#')
print()
str=fh.readline()
fh.close()

Output:

Read.txt
Hello. This is a Shemford School.
We are in class XII.

Output:
Hello.#This#is#a#Shemford#School.#
We#are#in#class#XII.#
Program – 9

Program to read a text file and display the number of vowels and number of characters in
the file

# Program to read a text file and display the number of vowels

def countVowels(str):
count=0
for i in str:
if i in 'aeiouAEIOU':
count=count+1
return(count)

def countTotal(str):
count=0
for i in str:
count=count+1
return(count)

fh=open('read.txt','r')
str=fh.read()
print('the number of vowels are ',countVowels(str))
print('the number of characters are ',countTotal(str))
fh.close()

Output:

Read.txt
Hello. This is a Shemford School.
We are in class XII.

Output:
the number of vowels are 15
the number of characters are 53
Program – 10

Program to read a text file and put all the lines having character ‘a’ in one file and
remaining lines in another file

# Program to remove all the lines that contain a and write it to another file
f1=open("read.txt","r")
f2=open( “first.txt","w")
f3=open(“second.txt","w")
str=f1.readline()
while str:
if " a " in str:
f2.write(str)
else:
f3.write(str)
str=f1.readline()
f1.close()
f2.close()
f3.close()

Output:

Read.txt:
Hello. This is a School.
We are in class XII.
Its a co-ed School.
We are here to study computer.

Output:
First.txt:
Hello. This is a School.
Its a co-ed School.

Second.txt:
We are in class XII.
We are here to study computer.
Program – 11

Program to create a binary file with id and password. Search for a given id and display
the password.

import pickle

def add(fh):
id=input('enter the id:')
pswd=input('enter the password:')
row={'id':id,'password':pswd}
pickle.dump(row,fh)

def search(fh):
ide=input('enter the id to be searched for password:')
flag=False
fh.seek(0)
try:
while True:
t=pickle.load(fh)
if t.get('id')==ide:
print('the password is:',t.get('password'))
flag=True
break
except:
if flag==False:
print('not found')

fh=open("data.dat",'ab+')
print('enter 1 to add data, 2 to search and 0 to exit')
ch=int(input('enter your choice'))

while(ch!=0):
if ch==1:
add(fh)
elif ch==2:
search(fh)
elif ch==0:
break
else:
print('wrong choice')
ch=int(input('enter your choice'))

fh.close()
Output:

enter 1 to add data, 2 to search and 0 to exit


enter your choice1
enter the id:ekta
enter the password:malik
enter your choice1
enter the id:school
enter the password:shemford
enter your choice2
enter the id to be searched for password:ekta
the password is: malik
enter your choice2
enter the id to be searched for password:school
the password is: shemford
enter your choice0
Program – 12

Program to create a csv file by entering user id and password, read and search the
password for given user id

import csv

def add(fh):
id=input('enter the id')
pswd=input('enter the password')
row=(id,pswd)
wr=csv.writer(fh,delimiter=',')
wr.writerow(row)

def search(fh):
id=input('enter the id to be searched for password')
fh.seek(0)
rdr=csv.reader(fh)
for i in rdr:
if i[0]==id:
print('the password is',i[1])
break
else:
print('id not found')

fh=open("loginData.csv",'a+',newline='\r\n')
print('enter 1 to add data, 2 to search and 0 to exit')
ch=int(input('enter your choice'))

while(ch!=0):
if ch==1:
add(fh)
elif ch==2:
search(fh)
elif ch==0:
break
else:
print('wrong choice')
ch=int(input('enter your choice'))

fh.close()
Output:

enter 1 to add data, 2 to search and 0 to exit


enter your choice1
enter the idschool
enter the passwordshemford
enter your choice1
enter the idpc
enter the passwordadmin
enter your choice2
enter the id to be searched for passwordschool
the password is shemford
enter your choice2
enter the id to be searched for passwordpc
the password is admin
enter your choice0

File
school shemford

pc admin
Program – 13

Aim: program to display a number in words

dic={0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine'}

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

res=''

while n>0:

i=n%10

n=n//10

w=dic[i]

res=w+' '+res

print('the number in words is')

print(res)

Output

enter the number: 245


the number in words is
two four five
Program – 14

Aim: program to accept a list and store the index of all non zero elements in a tuple

n=eval(input("enter the list of elements:\n"))

t=[]

for i in range(len(n)):

if n[i]!=0:

t.append(i)

tup=tuple(t)

print("the tuple of indices of non zero elements is :")

print(tup)

Output

enter the list of elements:

[0,45,0,78,12,0]

the tuple of indices of non zero elements is :

(1, 3, 4)
Program – 15

Program to create a stack of jobs and apply stack operations on it.

def push(s,a):
s.append(a)
print('done')

def pop(s):
if len(s)==0:
print('underflow')
else:
e=s.pop()
print(e)

def peek(s):
if len(s)==0:
print('stack empty')
else:
print(s[-1])
def display(s):
if len(s)==0:
print("stack empty")
else:
for i in s[::-1]:
print(i)

print('enter 1 to insert an element')


print('enter 2 to pop an element')
print('enter 3 to peek')
print('enter 4 to display the all elements present in stack')
print('enter 9 to clear all elements ')
print('enter 0 to exit')
stack=[]
ch=int(input('enter your choice'))
while(ch!=0):
if ch==1:
job=input('enter the element-')
push(stack,job)

elif ch==2:
pop(stack)

elif ch==3:
peek(stack)

elif ch==4:
display(stack)

elif ch==9:
stack.clear()
print("stack emptied")
break

else:
print('wrong choice')

ch=int(input('enter your choice'))

Output:

enter 1 to insert an element


enter 2 to pop an element
enter 3 to peek
enter 4 to display the all elements present in stack
enter 9 to clear all elements
enter 0 to exit
enter your choice1
enter the element-5
done
enter your choice1
enter the element-9
done
enter your choice3
9
enter your choice4
9
5
enter your choice2
9
enter your choice2
5
enter your choice4
stack empty
enter your choice9
stack emptied
Program - 16

Program to demonstrate ddl sql queries for creating database and tables

1. To create a database with the name bank

mysql> create database bank;

Query OK, 1 row affected (0.18 sec)

2. To open the created database:


mysql> use bank;

Database changed

3. To create a table customer_profile


mysql> create table customer_profile
-> (
-> customer_id integer primary key,
-> name varchar(30),
-> father_name varchar(30),
-> gender char(1),
-> address varchar(50),
-> dob date,
-> phone_no integer);

Query OK, 0 rows affected (0.12 sec)

4. To add an attribute unique on phone_no


mysql> alter table customer_profile
-> modify phone_no integer unique;

Query OK, 0 rows affected (0.19 sec)


Records: 0 Duplicates: 0 Warnings: 0

5. To add an attribute not null on name


mysql> alter table customer_profile
-> modify name varchar(30) not null;

Query OK, 0 rows affected (0.22 sec)


Records: 0 Duplicates: 0 Warnings: 0
Program - 17

Program to demonstrate ddl sql queries for creating database and tables-2

6. To drop a column father_name


mysql> alter table customer_profile
-> drop column father_name;

Query OK, 0 rows affected (0.07 sec)


Records: 0 Duplicates: 0 Warnings: 0

7. To add a column Balance in the end


mysql> alter table customer_profile
-> add column balance integer not null;

Query OK, 0 rows affected (0.04 sec)


Records: 0 Duplicates: 0 Warnings: 0

8. To describe the table


Mysql> Desc customer_profile;

9. To create a table main_branches


create table main_branches
-> (
-> branch_id int primary key,
-> city varchar(20),
-> address varchar(50),
-> Phone_no bigint);

Query OK, 0 rows affected (0.11 sec)

10. To drop a dummy table


mysql> drop table dummy;

Query OK, 0 rows affected (0.06 sec)


Program - 18

Program to demonstrate dml sql queries

1. To insert data into table customer_profile:


insert into customer_profile(customer_id,name,address,balance) values(1004,'Mohan','Mumbai',5000);

Query OK, 1 row affected (0.06 sec)

2. To select all records of customer_profile and main_branches separately


Select * from customer_profile;
Select * from main_branches;

3. To select customer_id, name and its main_branch location

4. To modify the dob of Aanya to '1992-05-05'

5. To delete the main branch of karnal


Program - 19

Program to demonstrate different operators and functions in sql

Tables data: ( need to be mentioned in left output side)

1. To find the total customers from each city


Select address,count(*) from customer_profile group by address;

2. To find the different cities of customers

3. To find the customers of birth between 1-1-92 and 31-12-1992


4. To find the customers of delhi, saharanpur or karnal

5. To find the customers of saharanpur who have balance greater than or equal to 10000

6. To display the main branches in ascending order of their city names

7. If PM scheme deposits Rs 500 in all accounts, display their would be balance


Program - 20

Program to display the records of customers table of sql in python

# Program to display the records of customers table of sql in python

import mysql.connector as c

db=c.connect(host='localhost',passwd='12345',user='root',db='bank')

cursor=db.cursor()

statement='select * from customer_profile'

cursor.execute(statement)

records=cursor.fetchall()

for i in records:

print(i)

print('total number of records are',cursor.rowcount)

output:
(1001, 'Anuj', 'M', 'Saharanpur', datetime.date(1993, 2, 4), 9876543210, 1000)

(1002, 'Bhawna', 'f', 'Saharanpur', datetime.date(1995, 4, 4), 9878943210, 1500)

(1003, 'Aanya', 'f', 'Delhi', datetime.date(1992, 5, 5), 5467127821, 15000)

(1004, 'Mohan', None, 'Mumbai', None, None, 5000)

total number of records are 4


Program - 21

Program to demonstrate update query using sql interfacting in python( money deposited
or withdrawn from an account of customer)

import mysql.connector as c

db=c.connect(host='localhost',passwd='12345',user='root',db='bank')

cursor=db.cursor()

idl=int(input('enter the customer id'))

amt=int(input('enter the amount to be deposited/withdraw(+/-)'))

statement='update customer_profile set balance=balance+{} where customer_id={}'.format(amt,idl)

cursor.execute(statement)

print('total number of records updated are',cursor.rowcount)

db.commit()

db.close()

Output:

enter the customer id1002

enter the amount to be deposited/withdraw(+/-)+5000

total number of records updated are 1


Program - 22

Program to demonstrate insert query using sql interfacting in python( new customer
details)

import mysql.connector as c

db=c.connect(host='localhost',passwd='12345',user='root',db='bank')

cursor=db.cursor()

# getting details of new customer

print('enter the customer details')

cid=int(input('enter the customer id'))

cname=input('enter the customer name')

cgender=input('enter the customer gender')

caddress=input('enter the customer address')

cdob=input('enter the customer dob')

cphone=int(input('enter the customer phone number'))

cbalance=int(input('enter the customer amount being deposited'))

# sql query

statement='insert into customer_profile values({},"{}","{}","{}","{}",{},{})'. Format


(cid,cname,cgender,caddress,cdob,cphone,cbalance)

cursor.execute(statement)

print('total number of records inserted are',cursor.rowcount)

db.commit()

db.close()

Output:

enter the customer details


enter the customer id1005
enter the customer nameSohan
enter the customer genderM
enter the customer addressDelhi
enter the customer dob1992-3-5
enter the customer phone number65485
enter the customer amount being deposited3000
total number of records inserted are 1
Program - 23

Program to demonstrate delete query using sql interfacting in python

import mysql.connector as c

db=c.connect(host='localhost',passwd='12345',user='root',db='bank')

cursor=db.cursor()

idl=int(input('enter the customer id to be deleted'))

statement='delete from customer_profile where customer_id={}'.format(idl)

cursor.execute(statement)

print('total number of records deleted are',cursor.rowcount)

db.commit()

db.close()

Output:

enter the customer id1002

total number of records deleted are 1

You might also like