0% found this document useful (0 votes)
14 views53 pages

Wa0022.

The document contains a series of Python programming exercises from Mar Ivanios Bethany School, covering various topics such as Fibonacci series, quadratic equations, palindrome checks, file operations, and data storage. Each program includes an aim, source code, and sample output. The exercises are designed to enhance programming skills and understanding of Python functions and file handling.

Uploaded by

bijujerin68
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)
14 views53 pages

Wa0022.

The document contains a series of Python programming exercises from Mar Ivanios Bethany School, covering various topics such as Fibonacci series, quadratic equations, palindrome checks, file operations, and data storage. Each program includes an aim, source code, and sample output. The exercises are designed to enhance programming skills and understanding of Python functions and file handling.

Uploaded by

bijujerin68
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/ 53

Python Programming

Mar Ivanios Bethany School,Kalayapuram Page 1


Python Programming

TERM-1

Mar Ivanios Bethany School,Kalayapuram Page 2


Python Programming

PROGRAM -1
Q. Write a program to print the Fibonacci Series using Function.

AIM:
Program to print the Fibonacci Series using Function.

SOURCE CODE
def fibonacci(n):

first =0

second=1

print(first,end=" ")

print(second,end=" ")

for a in range(1,n-1):

third=first+second

print(third,end =" ")

first,second=second,third

n= int(input("Enter the Limit:"))

print("Fibonacci Series")

print("*****************")

fibonacci(n)

Mar Ivanios Bethany School,Kalayapuram Page 3


Python Programming

OUTPUT
Enter the Limit:20

Fibonacci Series

*****************

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584


4181

Mar Ivanios Bethany School,Kalayapuram Page 4


Python Programming

PROGRAM 2:
Q. Write a program to calculate and print roots of a quadratic equation using
function

AIM:
program to calculate and print roots of a quadratic equation using function

SOURCE CODE
import math

def quadratic(a,b,c):

if a==0:

print("Value of", a,"should not be zero")

print("\n Aborting")

else:

delta = b*b-4 *a * c

if delta >0:

root1=(-b + math.sqrt(delta))/(2*a)

root2=(-b - math.sqrt(delta))/(2*a)

print("Roots are Real and UnEqual")

print("Root1=",root1,"Root2=",root2)

elif delta==0:

root1=-b/(2*a)

print("Roots are Real and Equal")

print("Root1=",root1,"Root2=",root1)

else:

Mar Ivanios Bethany School,Kalayapuram Page 5


Python Programming

print("Roots are Complex and Imaginary")

print("Enter the coefficients below")

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

b=int(input("Enter b :"))

c=int(input("Enter c :"))

quadratic(a,b,c)

Mar Ivanios Bethany School,Kalayapuram Page 6


Python Programming

OUTPUT 1
Enter the coefficients below
Enter a :3
Enter b :5
Enter c :2
Roots are Real and UnEqual
Root1= -0.6666666666666666 Root2= -1.0
OUTPUT 2
Enter the coefficients below
Enter a :2
Enter b :3
Enter c :4
Roots are Complex and Imaginary

Mar Ivanios Bethany School,Kalayapuram Page 7


Python Programming

PROGRAM 3
Q. Write a program to check whether a number is palindrome or Armstrong or not
using function

AIM:
Program to check whether a number is palindrome or Armstrong or not using
function

SOURCE CODE
def calc(n):
s=0
rev=0
while n>0:
dig=n%10
rev=(rev*10)+dig
s=s+(dig*dig*dig)
n=n//10
return s,rev
#main
n=int(input(" Enter a number "))
num=n
x,y=calc(n)
if(num==1):
print( " ARMSTRONG & PALINDROME ")
elif(num==x):
print( " ARMSTRONG Number ")
elif(y==num):
print(" Number is PALINDROME ")

Mar Ivanios Bethany School,Kalayapuram Page 8


Python Programming

else:
print(" SORRY , Not a Palindrome or Not an Armstrong number")

OUTPUT

Enter a number 1221

Number is PALINDROME

Enter a number 153

ARMSTRONG Number

Mar Ivanios Bethany School,Kalayapuram Page 9


Python Programming

PROGRAM 4:
Write a program to read a text file and display the number of alphabets ,vowels
consonants, digits and special characters in the file.
AIM:
Program to read a text file and display the number of alphabets ,vowels
consonants, digits and special characters in the file.

SOURCE CODE

x=open("sample.txt","r+")

a=v=c=d=sp=0

s=x.read()

print("Content of the file is ",s)

for i in s:

if(i.isalpha()):

a=a+1

if(i in "AEIOUaeiou"):

v=v+1

else:

c=c+1

elif(i.isdigit()):

d=d+1

elif(i!= ' ' and i!='\n'):

sp=sp+1

print("No of alphabets=",a)

print("No of vowels=",v)

print("No of consonants=",c)
Mar Ivanios Bethany School,Kalayapuram Page 10
Python Programming

print("No of digit=",d)

print("No of special characters=",sp)

x.close()

OUTPUT

Content of the file is #Hello i am 18 years old Boy#My name is Jack#

No of alphabets= 31

No of vowels= 12

No of consonants= 19

No of digit= 2

No of special characters= 3

Mar Ivanios Bethany School,Kalayapuram Page 11


Python Programming

PROGRAM : 5
Write a program to calculate simple interest using a function interest() that can
receive principal amount,time and rate and returns calculated simple interest. Do
specify default values for rate and time as 10% and 2 years respectively.

AIM:

Program to calculate simple interest with default values

SOURCE CODE:
#program to calculate simple interest with default values

def interest(principal,time=2,rate=0.10):

return principal*rate*time

#_main_

prin=float(input("Enter principal amount:"))

si1=interest(prin)

print("Simple interest with default ROI and time values is :")

print( "Rs." ,si1)

roi=float(input("Enter rate of interest(ROI):"))

time=int(input("Enter time in years:"))

print("Simple interest with your provided ROI and time values is :")

si2= interest(prin,time,roi/100)

print("Rs ",si2)

Mar Ivanios Bethany School,Kalayapuram Page 12


Python Programming

OUTPUT:
Enter principal amount:6700

Simple interest with default ROI and time values is :

Rs. 1340.0

Enter rate of interest(ROI):8

Enter time in years:3

Simple interest with your provided ROI and time values is :

Rs 1608.0

Mar Ivanios Bethany School,Kalayapuram Page 13


Python Programming

PROGRAM :6
Q. Write a program to find a lottery winner(by generating random number
within a limit.

AIM:
Program to find a lottery winner

SOURCE CODE

import random
n=random.randint(1,6)
guess= int(input("Enter a number between 1 to 6:"))
if n== guess:
print("Congratulations ,You won the lottery")
else:
print("Sorry , Try again. The lucky number was :",n)

OUTPUT

Enter a number between 1 to 6:3

Sorry , Try again. The lucky number was : 1

Mar Ivanios Bethany School,Kalayapuram Page 14


Python
Programming
PROGRAM 7 :
Q.Write a program to read and display a text file content line by line with each
word separated by „#‟

AIM: program to read and display a text file content line by line with each word
separated by „#‟

SOURCE CODE:
f=open("file1.txt")

for line in f:

words=line.split()

for w in words:

print(w+'#',end='')

print()

f.close()

OUTPUT:

Mar Ivanios BethanySchool, Kalayapuram Page 15


Python
Programming
PROGRAM 8:
Q.Write a program to count number of words present in each line of a file

AIM : program to count number of words present in each line of a file

SOURCE CODE:

def count(x):

s=x.readlines()

c=0

for i in s:

print(" Content of line",c+1,": ",i)

w=i.split()

l=len(w)

print("No of words in line ",c+1,": ",l)

c=c+1

#_main_

x=open("document.txt","r")

count(x)

x.close()

Mar Ivanios Bethany School, Kalayapuram Page 16


Python
Programming
OUTPUT:

Mar Ivanios Bethany School, Kalayapuram Page 17


Python
Programming
PROGRAM 9:
Q.Write a program to count the number of lines in a text file „Story.txt‟ which is
starting with an alphabet „A‟ or „a‟.

AIM:
Program to count the number of lines in a text file „Story.txt‟ which is starting with
an alphabet „A‟ or „a‟.

SOURCE CODE:

file= open("Story.txt","r")

lines=file.readlines()

count=0

print("Contents of the file:")

for w in lines:

print(w)

if w[0]=="A" or w[0]=="a":

count=count+1

print("Total lines started with 'A' or 'a'is:" , count)

file.close()

Mar Ivanios Bethany School, Kalayapuram Page 18


Python
Programming

OUTPUT:

Mar Ivanios Bethany School, Kalayapuram Page 19


Python
Programming
PROGRAM 10:
Q.Write a program to get student data(rollno,name,marks) from user and write
onto a binary file “student.dat”

AIM:Program to store students details in to a binary file

import pickle

stu= {}

stufile=open('stu','wb')

ans='y'

while ans=='y':

rno=int(input("Enter the student roll no :"))

name=input("Enter the student name : ")

marks=int(input("Enter the marks obtained:"))

stu['Rollno']=rno

stu['Name']=name

stu['Marks']=marks

pickle.dump(stu,stufile)

ans=input( "Do you want to enter more record(y/n):")

print("Records added")

stufile.close()

Mar Ivanios Bethany School, Kalayapuram Page 20


Python
Programming
OUTPUT:

Mar Ivanios Bethany School, Kalayapuram Page 21


Python
Programming
PROGRAM 11:
Q.Write a program to read following details of sport‟s performance
(sports,competitions,prizes-won) of your school and store into a CSV file delimted
with tab character.

AIM:

Program to store data to a CSV file

SOURCE CODE:
# Program to store the sports details into a csv file

import csv

file=open("Sports.csv","w",newline='')

spwriter=csv.writer(file,delimiter='\t')

spwriter.writerow(['Sports','Competitions','Prizes won'])

ans='y'

while ans=='y':

sport=input("Enter the sports name:")

comp=input("Enter the number of competitions:")

prizes=input("Enter the prizes won:")

rec=[sport,comp,prizes]

spwriter.writerow(rec)

ans=input("Do you want to enter more?:(y/n)")

file.close()

Mar Ivanios Bethany School, Kalayapuram Page 22


Python
Programming
OUTPUT:

Mar Ivanios Bethany School, Kalayapuram Page 23


Python
Programming
PROGRAM 12:
Q.Write a program to perform linear search in List of items

AIM: Program to perform linear search in List of items

SOURCE CODE:
def searchList(L, item):

if item in L:

print("Element found in the List" )

else:

print("Sorry item doesn't exists in the list")

ans = 'y'

L=eval(input("Enter the elements: "))

print(list(L))

while ans == 'y':

item = int(input("Enter the item to search"))

searchList(L, item)

ans = input("Search again? (y/n)")

Mar Ivanios Bethany School, Kalayapuram Page 24


Python
Programming
OUTPUT:

Mar Ivanios Bethany School, Kalayapuram Page 25


Python
Programming
PROGRAM 13:
Q:Write a program to create a dictionary (Rno,Name,Mark) and search for records
having marks>80 from a binary file „Student.dat‟.

AIM: Program to perform search in a binary file.

SOURCE CODE:
import pickle

stu ={}

found=False

with open("Student.dat", "wb+") as f:

ans = 'y'

while ans == 'y':

roll_no = input("Enter roll no.")

name = input("Enter name")

marks = int(input("Enter the marks"))

stu["Roll_No"]=roll_no

stu["Name"]=name

stu["Marks"]=marks

pickle.dump(stu, f)

ans=input("Enter more ?(y/n)")

f=open("Student.dat", "rb")

try:

print("Records with marks > 80 are")

while True:

stu = pickle.load(f)

Mar Ivanios Bethany School, Kalayapuram Page 26


Python
Programming
if stu['Marks']>80:

print(stu)

found=True

except EOFError:

if found==False:

print("No records with mark>81")

else:

print("Search successful")

f.close()

Mar Ivanios Bethany School, Kalayapuram Page 27


Python
Programming
OUTPUT

Mar Ivanios Bethany School, Kalayapuram Page 28


Python
Programming
PROGRAM 14:
Q:Write a program to read the lines from a file „poem.txt‟ and rewrite the lines
starting with letter „B‟ to another file „temp.txt‟.

AIM: Program to read the lines from a file „poem.txt‟ and rewrite the lines
starting with letter „B‟ to another file „temp.txt‟.

SOURCE CODE:

f = open("D:\\pgm\\poem.txt", "r")

x = open("D:\\pgm\\temp.txt", "w")

line = f.readlines()

for w in line:

if w[0]=="B":

x.write(w)

f.close()

x.close()

Mar Ivanios Bethany School, Kalayapuram Page 29


Python
Programming
OUTPUT:
Contents of file „poem.txt‟ and „temp.txt‟

Mar Ivanios Bethany School, Kalayapuram Page 30


Python
Programming
PROGRAM : 15
Write a program to count the number of “Me” or “My” words present in the text
file “Story.txt”.”Story.txt”

contents are as follows:

AIM:

Program to count the number of “Me” or “My” words present in the text file
“Story.txt”

SOURCE CODE:
myfile=open("Story1.txt","r")

str=myfile.read()

word=str.split()

count=0

for i in word:

if i=="Me" or i=="My":

count+=1

print("count of Me/My in file:",count)

OUTPUT

Mar Ivanios Bethany School, Kalayapuram Page 31


Python
Programming

TERM-2

Mar Ivanios Bethany School, Kalayapuram Page 32


Python
Programming
PROGRAM :1
Q. Write a program to implement stack operation PUSH and POP.Display the
content of stack after each operation.

AIM: Program to implement Stack Operations

SOURCE CODE:
stack=[]

def PUSH():

item =eval(input("Enter the element to push"))

stack.append(item)

print("Stack after push --> ",stack)

def POP():

if stack==[]:

print("Stack is empty")

else:

stack.pop()

print("stack after pop -->",stack)

print('1.PUSH\n 2.POP')

more='y'

while more in 'Yy':

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

if choice==1:

PUSH()

elif choice==2:

POP()

Mar Ivanios Bethany School, Kalayapuram Page 33


Python
Programming
else:

print("invalid choice!!")

more=input("\n Do you want to continue(Y/N")

OUTPUT:

Mar Ivanios Bethany School, Kalayapuram Page 34


Python
Programming
PROGRAM 2:
Q. Write a program to push all even numbers in to a stack from user inputted numbers .Display
the stack if it has at least one element,otherwise display error message.

AIM: Program to implement Stack Operations

SOURCE CODE:
EVEN=[]

def PUSH(Num):

for n in Num:

if n%2==0:

EVEN.append(n)

if EVEN!=[]:

print("Stack content",EVEN)

else:

print("Stack is empty")

Num=eval(input("Enter some numbers to sepearate"))

PUSH(Num)

OUTPUT

Mar Ivanios BethanySchool, Kalayapuram Page 35


Python
Programming
PROGRAM 3:
Q.Write a program to push Employee details as given below on a stack.Display the content of
stack after push.

Employee number - Integer

Employee name – String

Age - Integer

AIM: Program to implement Stack Operations

SOURCE CODE:
EMP=[]

def PUSH():

eno=int(input("Enter the employee no:"))

ename=input("Enter the name :")

age=int(input("Enter the age:"))

E=[eno,ename,age]

EMP.append(E)

more='Y'

while more=='Y':

PUSH()

more=input("Do you want to continue?(Y/N):")

print("empolyee details:")

for i in range(len(EMP)-1,-1,-1):

print(EMP[i])

Mar Ivanios BethanySchool, Kalayapuram Page 36


Python
Programming
OUTPUT

Mar Ivanios BethanySchool, Kalayapuram Page 37


Python
Programming
PROGRAM:4
AIM:Write a program to display students whose mark is greater than 80.

Structure of the table Student. Content of the table Student

Fields Datatype constraint


Rollno int Primary Key
Name varchar(15)
Gender char(1)
Marks float

SOURCE CODE:
import mysql.connector as sqlcon

mycon=sqlcon.connect(host='localhost',user='root',password='hello',database='school')

mycur=mycon.cursor()

mycur.execute('select * from student where marks>80')

for row in mycur:

print(row)

mycon.close()

OUTPUT

Mar Ivanios BethanySchool, Kalayapuram Page 38


School
Python
Programming
PROGRAM:5
AIM:Write a program to display the details of students in ascending order of their
marks.

SOURCE CODE
import mysql.connector as sqlcon

mycon=sqlcon.connect(host='localhost',user='root',password='hello',database='sch
ool')

mycur=mycon.cursor()

mycur.execute('select * from student order by marks')

for row in mycur:

print(row)

mycon.close()

OUT PUT

Mar Ivanios BethanySchool, Kalayapuram Page 39


School
Python
Programming
PROGRAM:6

AIM: Write a program to display the details of male students.

SOURCE CODE:
import mysql.connector as sqlcon

mycon=sqlcon.connect(host='localhost',user='root',password='hello',database='sch
ool'')

mycur=mycon.cursor()

mycur.execute('select * from student where Gender="M"')

for row in mycur:

print(row)

mycon.close()

OUTPUT:

Mar Ivanios Bethany School, Kalayapuram Page 40


School
Python
Programming

MySQL

Mar Ivanios Bethany School, Kalayapuram Page 41


School
Python
Programming

SQL QUERIES
Set -1
1. Create a database School
2. Display all the databases
3. Use the database School
4. Create a table Teacher with the following structure:
Tno int Primary Key
Name varchar(15) Not Null
DOB date
Salary float
Deptno int
5. Display the structure of the table Teacher
6. Insert 5 records into Teacher table.
7. Display all the records in table Teacher.

1. Create a database School

2. Display all the databases

Mar Ivanios Bethany School, Kalayapuram Page 42


School
Python
Programming
3. Use the database School

4. Create a table Teacher with the following structure:

Tno int Primary Key


Name varchar(15) Not Null
DOB date
Salary float
Deptno int

5. Display the structure of the table Teacher

Mar Ivanios Bethany School, Kalayapuram Page 43


School
Python
Programming

6. Insert 5 records into Teacher table.

7. Display all the records in table Teacher.

Mar Ivanios Bethany School, Kalayapuram Page 44


School
Python
Programming
Set-2
Implement the following SQL commands on the Teacher table:

1. Display the name and date of birth of all the teachers


2. Display the details of teachers whose salary is between 30000 and
40000(both values included)
3. Display the names of teachers whose name starts with „A‟
4. Display the name and salary of teachers whose salary is greater than 40000
5. Display the details of teachers whose DOB is < „1980-01-01‟

1. Display the name and date of birth of all the teachers.

2. Display the details of teachers whose salary is between 30000 and 40000(both
values included)

Mar Ivanios Bethany School, Kalayapuram Page 45


School
Python
Programming
3. Display the names of teachers whose name starts with „A‟

4. Display the name and salary of teachers whose salary is greater than 40000

5. Display the details of teachers whose DOB is < „1980-01-01‟

Mar Ivanios Bethany School, Kalayapuram Page 46


School
Python
Programming
Set -3
1. Create a table Dept with the following structure:
Deptno int Primary Key
Dname varchar(15) Not Null
2. Display all the tables in database School
3. Insert 3 records into Dept table
4. Display all the records in table DEpt
5. Display the details of all the teachers whose department is „science „ from tables Teacher
and Dept.
6. Display the details of all the teachers whose department is „maths‟ from tables Teacher
and Dept(using Equi join)

1. Create a table Dept with the following structure:

Deptno int Primary Key


Dname varchar(15) Not Null

2. Display all the tables in database School

3. Insert 3 records into Dept table

Mar Ivanios Bethany School, Kalayapuram Page 47


School
Python
Programming
4. Display all the records in table Dept

5. Display the details of all the teachers whose department is „science „ from tables Teacher
and Dept.

6. Display the details of all the teachers whose department is „maths‟ from tables Teacher and
Dept(using Equi join)

Mar Ivanios Bethany School, Kalayapuram Page 48


School
Python
Programming
Set-4
Implement the following SQL commands on the Teacher Table:

1. Increase the salaries of all the teachers by 2000.


2. Display the content of the table Teacher
3. Add an attribute designation to table Teacher.
4. Display the structure of the table Teacher.
5. Update the designation of all the teachers as „PGT‟ whose salary is >=40000
6. Display the records of all the teachers whose designation column is null.
7. Delete the attribute designation
8. Delete the records of teachers whose deptno is 10
9. Display the table content after deletion
10. Delete the table Teacher.

1. Increase the salaries of all the teachers by 2000.

2. Display the content of the table Teacher

3. Add an attribute designation to table Teacher.

4. Display the records of all the teachers whose designation column is null.

Mar Ivanios Bethany School, Kalayapuram Page 49


School
Python
Programming
5. Display the structure of the table Teacher.

6. Update the designation of all the teachers as „PGT‟ whose salary is >=40000

7. Delete the attribute designation

8. Delete the records of teachers whose deptno is 10

9. Display the table content after deletion

10. Delete the table Teacher.

Mar Ivanios Bethany School, Kalayapuram Page 50


School
Python
Programming
Set-5

1. Create a table student with the following structure and insert data
Rollno int Primary Key
Name varchar(15)
Gender char(1)
Marks float
2. Display the details of all the students
3. Display the total marks of all the students
4. Display total number of students
5. Display minimum and maximum marks of students
6. Display the number of male and female students
7. Display the details of students in ascending order of their names.
8. Display the details of students in descending order if their marks,

1.Create a table student with the following structure and insert data

Rollno int Primary Key


Name varchar(15)
Gender char(1)
Marks float

2. Display the details of all the students

3. Display the total marks of all the student

ts

Mar Ivanios Bethany School, Kalayapuram Page 51


School
Python
Programming
4. Display total number of students

5. Display minimum and maximum marks of students

6. Display the number of male and female students

7. Display the details of students in ascending order of their names.

Mar Ivanios Bethany School, Kalayapuram Page 52


School
Python
Programming
8. Display the details of students in descending order if their marks.

Mar Ivanios Bethany School, Kalayapuram Page 53


School

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy