Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

Pr No: Date:

Display Welcome Message


01

Program Code:

# Input a welcome message and display it

inp = input( )
print(inp)

Output:
Hi, Welcome to 083 - Computer Science Lab
Hi, Welcome to 083 - Computer Science Lab

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Smallest of two numbers
02

Program Code:

# Smallest of two numbers

number1 = int(input("Enter First Number:"))


number2 = int(input("Enter Second Number:"))
if (number1 < number2):
print("{} is smallest".format(number1))
else:
print("{} is smallest".format(number2))

Output:
Enter First Number:25
Enter Second Number:15
15 is smallest

Enter First Number:15


Enter Second Number:20
15 is smallest

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Biggest of three numbers
03

Program Code:

# Biggest of three numbers

number1 = int(input("Enter First Number:"))


number2 = int(input("Enter Second Number:"))
number3 = int(input("Enter Third Number:"))
if (number1 > number2):
if (number1 > number3):
print("{} is Biggest".format(number1))
else:
print("{} is Biggest".format(number3))
else:
if (number2 > number3):
print("{} is Biggest".format(number2))
else:
print("{} is Biggest".format(number3))

Output:
Enter First Number:10
Enter Second Number:20
Enter Third Number:30
30 is Biggest

Enter First Number:30


Enter Second Number:10
Enter Third Number:20
30 is Biggest

Enter First Number:20


Enter Second Number:30
Enter Third Number:10
30 is Biggest

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Half pyramid pattern with stars(*)
04(a)

Program Code:

# Half pyramid pattern with stars(*)

rows = 5
for i in range(rows):
for j in range(i+1):
print("*", end=' ')
print("\n")

Output:
*

* *

* * *

* * * *

* * * * *

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Inverted half pyramid using numbers
04(b)

Program Code:

# Inverted half pyramid using numbers

rows = 5
for i in range(rows, 0, -1):
for j in range(1, i+1):
print(j, end=" ")
print("\n")

Output:
1 2 3 4 5

1 2 3 4

1 2 3

1 2

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Alphabetic Pattern
04(c)

Program Code:

# Alphabetic Pattern

for i in range (65,70):


for j in range(65,i+1):
print(chr(j),end="")
print()

Output:
A
AB
ABC
ABCD
ABCDE

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Sum of Series of 1 + x^2 + x^3 + ....+ x^n
05(a)

Program Code:

# To find sum of series of 1 + x^2 + x^3 + ....+ x^n

x = int(input("Enter Which Series:"))


n = int(input("Enter the Terms:"))
total = 1.0
multi = x
print(1, end = " ")
for i in range(1, n):
total = total + multi
print('%.1f' % multi, end = " ")
multi = multi * x
print('\n')
print(total)

Output:
Enter Which Series:2
Enter the Terms:5
1 2.0 4.0 8.0 16.0

31.0

Result:
The above program was successfully executed and displays
the result
Pr No: Check Perfect number, an Amstrong Date:
06 number or a Palindrome number

Program Code:

#To Check Perfect number, an Amstrong number or a Palindrome number


n = int(input("Enter any number to check whether it is perfect ,armstrong or
palindrome : "))
sum = 0
# Check for perfect number
for i in range(1,n):
if n%i==0:
sum = sum + i
if sum == n :
print( n,"is perfect number")
else :
print( n, "is not perfect number")
#check for armstrong number
temp = n
total = 0
while temp > 0 :
digit = temp %10
total = total + (digit**3)
temp = temp//10
if n == total:
print( n,"is an armstrong number")
else :
print( n, "is not armstrong number")
#check for palindrome number
temp = n
rev = 0
while n > 0:
d = n % 10
rev = rev *10 + d
n = n//10
if temp == rev :
print( temp,"is palindrome number")
else :
print( temp, "is not palindrome number")
Output:
Enter any number to check whether it is perfect ,armstrong or palindrome :
28
28 is perfect number
28 is not armstrong number
28 is not palindrome number

Enter any number to check whether it is perfect ,armstrong or palindrome :


153
153 is not perfect number
153 is an armstrong number
153 is not palindrome number

Enter any number to check whether it is perfect ,armstrong or palindrome :


121
121 is not perfect number
121 is not armstrong number
121 is palindrome number

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Check the number is a prime or composite number
07

Program Code:

#Input a number and check if the number is prime or composite number


n= int(input("Enter any number:"))
if(n ==0 or n == 1):
printf(n,"Number is neither prime nor composite")
elif n>1 :
for i in range(2,n):
if(n%i == 0):
print(n,"is not prime but composite number")
break
else:
print(n,"number is prime but not composite number")
else :
print("Please enter positive number only ")

Output:
Enter any number:19
19 number is prime but not composite number

Enter any number:1


1 Number is neither prime nor composite

Enter any number:4


4 is not prime but composite number

Enter any number:-10


Please enter positive number only

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Display the terms of a Fibonacci series
08

Program Code:

#Display the terms of a Fibonacci series

firstterm = 0
secondterm = 1
counter = 0
totalterms = int(input("Please enter how many terms: "))
if totalterms <= 0:
print("Please enter only positive integers")
elif totalterms==1:
print(firstterm)
else:
print("Fibonacci Series: ")
while counter<totalterms:
print(firstterm)
sum = firstterm+secondterm
firstterm = secondterm
secondterm = sum
counter=counter+1

Output:
Please enter how many terms: 8
Fibonacci Series:
0
1
1
2
3
5
8
13

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Display the terms of a Fibonacci series
09

Program Code:

# Compute GCD and LCM of two numbers


n1 = int(input("Enter First number :"))
n2 = int(input("Enter Second number :"))
x = n1
y = n2
while(n2!=0):
t = n2
n2 = n1 % n2
n1 = t
gcd = n1
print("GCD of {0} and {1} = {2}".format(x,y,gcd))
lcm = (x*y)/gcd
print("LCM of {0} and {1} = {2}".format(x,y,lcm))

Output:
Enter First number :57
Enter Second number :18
GCD of 57 and 18 = 3
LCM of 57 and 18 = 342.0

Result:
The above program was successfully executed and displays
the result
Pr No: Count and display the number of vowels, consonants, Date:
10 uppercase, lowercase characters in string

Program Code:

#Count and display the number of vowels, consonants,uppercase, lowercase


#characters in string
s = input("Enter any string :")
vowel = consonent = uppercase = lowercase= 0
for i in s:
if(i in ('AEIOUaeiou')):
vowel = vowel +1
else:
consonent = consonent + 1
if i.isupper() :
uppercase = uppercase + 1
if i.islower():
lowercase = lowercase + 1
print("Total number of vowel:",vowel)
print("Total number of consonent:",consonent)
print("Total number of uppercase letter:",uppercase)
print("Total number of lowercase letter:",lowercase)

Output:
Enter any string :083 Computer Science
Total number of vowel: 6
Total number of consonent: 14
Total number of uppercase letter: 2
Total number of lowercase letter: 13

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Palindrome String
11

Program Code:

#Palindrome String
string=input(("Enter a letter:"))
if(string==string[::-1]):
print("The letter is a palindrome")
else:
print("The letter is not a palindrome")

Output:
Enter a letter:malayalam
The letter is a palindrome

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Largest or Smallest number in a list
12

Program Code:

#Largest or Smallest number in a list


Numlist = [ ]
n = int(input('List Size: '))
for n in range(n):
numbers = int(input('Enter number '))
Numlist.append (numbers)
print("Largest element in the list is ",max(Numlist))
print("Smallest element in the list is ",min(Numlist))

Output:
List Size: 6
Enter number 50
Enter number 12
Enter number 75
Enter number 24
Enter number 25
Enter number 36
Largest element in the list is 75
Smallest element in the list is 12

Result:
The above program was successfully executed and displays
the result
Pr No: Swapping elements at the even location with the Date:
13 elements at the odd location

Program Code:

# Swapping elements at the even location with the elements at the odd location
mylist = []
n = int(input("Enter elements for the list: "))
for i in range(n):
value = int(input("Enter the Values:"))
mylist.append(value)
print("The original list : " + str(mylist))
odd_i = []
even_i = []
for i in range(0, len(mylist)):
if i % 2:
even_i.append(mylist[i])
else :
odd_i.append(mylist[i])
result = odd_i + even_i
print("Separated odd and even index list: " + str(result))

Output:
Enter elements for the list: 6
Enter the Values:12
Enter the Values:24
Enter the Values:36
Enter the Values:48
Enter the Values:60
Enter the Values:72
The original list : [12, 24, 36, 48, 60, 72]
Separated odd and even index list: [12, 36, 60, 24, 48, 72]

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Search an Element in a List
14

Program Code:

# Search an Element in a List


mylist = []
n = int(input("Enter the elements for the list: "))
for i in range(n):
val = int(input("Enter the Value:"))
mylist.append(val)
print("Enter an element to be search: ")
elem = int(input())
for i in range(n):
if elem == mylist[i]:
print("Element found at Index:", i)
print("Element found at Position:", i+1)

Output:
Enter the elements for the list: 6
Enter the Value:25
Enter the Value:50
Enter the Value:75
Enter the Value:100
Enter the Value:125
Enter the Value:150
Enter an element to be search:
125
Element found at Index: 4
Element found at Position: 5

Result:
The above program was successfully executed and displays
the result
Pr No: Create a dictionary with the roll number, name and Date:
15 marks of n students in a class and display the names
of students who have marks above 75

Program Code:

# dictionary with the roll number, name and marks of n students


#in a class and display the names of students who have scored marks above 75

no_of_std = int(input("Enter number of students: "))


result = {}
for i in range(no_of_std):
print("Enter Details of student No.", i+1)
roll_no = int(input("Roll No: "))
std_name = input("Student Name: ")
marks = int(input("Marks: "))
result[roll_no] = [std_name, marks]
print(result)
for student in result:
if result[student][1] > 75:
print("Student's name who get more than 75 marks is/are",
(result[student][0]))

Output:
Enter number of students: 5
Enter Details of student No. 1
Roll No: 499
Student Name: Bharath
Marks: 85
Enter Details of student No. 2
Roll No: 599
Student Name: Babu
Marks: 74
Enter Details of student No. 3
Roll No: 699
Student Name: Barani
Marks: 89
Enter Details of student No. 4
Roll No: 799
Student Name: Baskar
Marks: 70
Enter Details of student No. 5
Roll No: 899
Student Name: Bala
Marks: 76
{499: ['Bharath', 85], 599: ['Babu', 74], 699: ['Barani', 89], 799: ['Baskar',
70], 899: ['Bala', 76]}
Student's name who get more than 75 marks is/are Bharath
Student's name who get more than 75 marks is/are Barani
Student's name who get more than 75 marks is/are Bala

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Simple Calculator using user defined function
16

Program Code:

#Simple Calculator using user defined function


def simcal(num1,op,num2):
if op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '*':
print(num1 * num2)
elif op == '//':
print(num1 // num2)
elif op == '/':
print(num1 / num2)
elif op == '%':
print(num1 % num2)
elif op == '**':
print(num1 ** num2)
else:
print("Error")

num1 = int(input())
op = input()
num2 = int(input())
simcal(num1,op,num2)

Output:
25
*
8
200

Result:
The above program was successfully executed and displays
the result
Pr No: Read a text file line by line and Date:
17 display each word separated by # symbol

smartwatch.txt
A smartwatch is a wearable computer in the form of a watch;
modern smartwatches provide a local touchscreen interface for daily use,
while an associated smartphone app provides for management and
telemetry (such as long-term biomonitoring)

Program Code:
#Read a text file line by line and display each word separated by # symbol
file = open("smartwatch.txt","r")
lines = file.readlines()
for line in lines:
words = line.split()
for word in words:
print(word + "#",end = "")
print(" ")

Output:
A#smartwatch#is#a#wearable#computer#in#the#form#of#a#watch;#
modern#smartwatches#provide#a#local#touchscreen#interface#for#daily#use,#
while#an#associated#smartphone#app#provides#for#management#and#
telemetry#(such#as#long-term#biomonitoring)#

Result:
The above program was successfully executed and displays
the result
Pr No: Read a text file and display the number of vowels/ Date:
18 consonants/uppercase/lowercase characters in the file

smartwatch.txt
A smartwatch is a wearable computer in the form of a watch;
modern smartwatches provide a local touchscreen interface for daily use,
while an associated smartphone app provides for management and
telemetry (such as long-term biomonitoring)

Program Code:
#Read a text file and display the number of vowels / consonants / uppercase
#/lowercase characters in the file
myfile = open("smartwatch.txt","r")
vowel = consonent = uppercase = lowercase= 0
s = myfile.read()
for i in s:
if i.isalpha():
if(i in ('AEIOUaeiou')):
vowel = vowel +1
else:
consonent = consonent + 1
if i.isupper() :
uppercase = uppercase + 1
if i.islower():
lowercase = lowercase + 1
print("Total number of vowel:",vowel)
print("Total number of consonent:",consonent)
print("Total number of uppercase letter:",uppercase)
print("Total number of lowercase letter:",lowercase)

Output:
Total number of vowel: 76
Total number of consonent: 123
Total number of uppercase letter: 1
Total number of lowercase letter: 198

Result:
The above program was successfully executed and displays
the result
Pr No: Remove all the lines that contain the character `a' Date:
19 in a file and write it to another file

smartwatch.txt
A smartwatch is a wearable computer in the form of a watch;
modern smartwatches provide a local touchscreen interface for daily use,
while an associated smartphone app provides for management and
telemetry (such as long-term biomonitoring)
hello
computer
modern
biomonitoring
telemetry

Program Code:
#Remove all the lines that contain the character `a' in a file and write it
#to another file
f1 = open("smartwatch.txt")
f2 = open("newfile.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()
f2 = open("newfile.txt","r")

Output:
## File Copied Successfully! ##

newfile.txt
hello
computer
modern
biomonitoring
telemetry

Result:
The above program was successfully executed and displays
the result
Pr No: Create a binary file with name and roll number. Date:
20 Search for a given roll number and display the
name, if not found display appropriate message

Program Code:
#Create a binary file with name and roll number. Search for a given roll number
#and display the name, if not found display appropriate message

import pickle
def Writerecord(sroll,sname):
with open ('StudentRecord1.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname}
pickle.dump(srecord,Myfile)

def Readrecord():
with open ('StudentRecord1.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print()
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
Writerecord(sroll,sname)

def SearchRecord(roll):
with open ('StudentRecord1.dat','rb') as Myfile:
while True:
try:
rec=pickle.load(Myfile)
if rec['SROLL']==roll:
print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])
break

except EOFError:
print("Record not find..............")
print("Try Again..............")
break

def main():

while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Search Records (By Roll No)')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r=int(input("Enter a Rollno to be Search: "))
SearchRecord(r)
else:
break
main()

Output:

Your Choices are:


1.Insert Records
2.Dispaly Records
3.Search Records (By Roll No)
0.Exit (Enter 0 to exit)
Enter Your Choice: 1
How many records you want to create :2
Enter Roll No: 299
Enter Name: Suresh
Enter Roll No: 399
Enter Name: Rajesh
Your Choices are:
1.Insert Records
2.Dispaly Records
3.Search Records (By Roll No)
0.Exit (Enter 0 to exit)
Enter Your Choice: 2

-------DISPALY STUDENTS DETAILS--------

Roll No. Name


499 Bharath
515 Tharun
699 Barani
799 Babu
299 Suresh
399 Rajesh

Your Choices are:


1.Insert Records
2.Dispaly Records
3.Search Records (By Roll No)
0.Exit (Enter 0 to exit)
Enter Your Choice: 3
Enter a Rollno to be Search: 399
Roll NO: 399
Name: Rajesh

Your Choices are:


1.Insert Records
2.Dispaly Records
3.Search Records (By Roll No)
0.Exit (Enter 0 to exit)
Enter Your Choice: 3
Enter a Rollno to be Search: 825
Record not find..............
Try Again..............

Your Choices are:


1.Insert Records
2.Dispaly Records
3.Search Records (By Roll No)
0.Exit (Enter 0 to exit)
Enter Your Choice: 0
>>>

Result:
The above program was successfully executed and displays
the result
Pr No: Create a binary file with roll number, name and Date:
21 marks.Input a roll number and update details.

Program Code:

#Create a binary file with roll number, name and marks.


#Input a roll number and update details.

import pickle
def Writerecord(sroll,sname,sperc,sremark):
with open ('StudentRecord.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,
"SREMARKS":sremark}
pickle.dump(srecord,Myfile)

def Readrecord():
with open ('StudentRecord.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'],'\t ',end='')
print(rec['SPERC'],'\t ',rec['SREMARKS'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
Writerecord(sroll,sname,sperc,sremark)

def Modify(roll):
with open ('StudentRecord.dat','rb') as Myfile:
newRecord=[]
while True:
try:
rec=pickle.load(Myfile)
newRecord.append(rec)
except EOFError:
break
found=1
for i in range(len(newRecord)):
if newRecord[i]['SROLL']==roll:
name=input("Enter Name: ")
perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ")

newRecord[i]['SNAME']=name
newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark
found =1
else:
found=0

if found==0:

print("Record not found")


with open ('StudentRecord.dat','wb') as Myfile:
for j in newRecord:
pickle.dump(j,Myfile)

def main():

while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Update Records')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r =int(input("Enter a Rollno to be update: "))
Modify(r)
else:
break
main()

Output:

Your Choices are:


1.Insert Records
2.Dispaly Records
3.Update Records
0.Exit (Enter 0 to exit)
Enter Your Choice: 1
How many records you want to create :2
Enter Roll No: 125
Enter Name: Muthu
Enter Percentage: 85
Enter Remark: Good
Enter Roll No: 225
Enter Name: Mahalakshmi
Enter Percentage: 74
Enter Remark: Need Improvement

Your Choices are:


1.Insert Records
2.Dispaly Records
3.Update Records
0.Exit (Enter 0 to exit)
Enter Your Choice: 2

-------DISPALY STUDENTS DETAILS--------

Roll No. Name Percetage Remarks


125 Muthu 85.0 Good
225 Mahalakshmi 74.0 Need Improvement

Your Choices are:


1.Insert Records
2.Dispaly Records
3.Update Records
0.Exit (Enter 0 to exit)
Enter Your Choice: 3
Enter a Rollno to be update: 225
Enter Name: Mahalakshmi
Enter Percentage: 78
Enter Remark: Need Improvement

Your Choices are:


1.Insert Records
2.Dispaly Records
3.Update Records
0.Exit (Enter 0 to exit)
Enter Your Choice: 2

-------DISPALY STUDENTS DETAILS--------

Roll No. Name Percetage Remarks


125 Muthu 85.0 Good
225 Mahalakshmi 78.0 Need Improvement

Your Choices are:


1.Insert Records
2.Dispaly Records
3.Update Records
0.Exit (Enter 0 to exit)
Enter Your Choice: 0
>>>

Result:
The above program was successfully executed and displays
the result
Pr No: Write a random number generator that generates Date:
22 random numbers between 1 and 6 (simulates a dice)

Program Code:
#Write a random number generator that generates random numbers between 1 and
#6 (simulates a dice)

import random

def roll_dice():
print (random.randint(1, 6))
print("""Welcome to my python random dice program!
To start press enter! Whenever you are over, type quit.""")
flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()

Output:
Welcome to my python random dice program!
To start press enter! Whenever you are over, type quit.
>1
Rolling dice...
Your number is:
5
>2
Rolling dice...
Your number is:
6
>3
Rolling dice...
Your number is:
2
>4
Rolling dice...
Your number is:
3
>5
Rolling dice...
Your number is:
6
>6
Rolling dice...
Your number is:
1
>7
Rolling dice...
Your number is:
2
>quit
>>>

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
To implement a stack using list
23

Program Code:
#To implement a stack using list

def isempty(stk):
if stk==[]:
return True
else:
return False

def push(stk,item):
stk.append(item)
top=len(stk)-1

def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item

def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]

def display(stk):
if 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 main():
stk=[]
top=None
while True:
print('''stack operation
1.push
2.pop
3.peek
4.display
5.exit''')
choice=int (input('enter choice:'))
if choice==1:
item=int(input('enter item:'))
push(stk,item)
elif choice==2:
item=pop(stk)
if item=="underflow":
print('stack is underflow')
else:
print('poped')
elif choice==3:
item=peek(stk)
if item=="underflow":
print('stack is underflow')
else:
print('top most item is:',item)
elif choice==4:
display(stk)
elif choice==5:
break
else:
print('invalid')
exit()
main()
Output:
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:4
stack is empty
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:1
enter item:125
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:1
enter item:225
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:1
enter item:325
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:4
325 <-top
225
125
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:2
poped
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:4
225 <-top
125
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:3
top most item is: 225
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:5
>>>

Result:
The above program was successfully executed and displays
the result
Pr No: Create a CSV file by entering user-id and password, Date:
24 read and search the password for given user-id.

Program Code:
#Create a CSV file by entering user-id and password,
#read and search the password for given user-id.
import csv
with open("user_info.csv", "w") as obj:
fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue
with open("user_info.csv", "r") as obj2:
fileobj2 = csv.reader(obj2)
given = input("enter the user id to be searched\n")
for i in fileobj2:
next(fileobj2)
if i[0] == given:
print(i[1])
break

Output:
enter id: class12
enter password: class12B2023
press Y/y to continue and N/n to terminate the program
y
enter id: class11
enter password: class11B2024
press Y/y to continue and N/n to terminate the program
y
enter id: class10
enter password: class10B2025
press Y/y to continue and N/n to terminate the program
n
enter the user id to be searched
class11
class11B2024

Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Database Table Creation
25

Database Table Creation:

create table student(admn_no int(5) primary key, stud_name varchar(25), gender


varchar(6), class varchar (3), section varchar(2));

desc student;

# Field Type Null Key Default Extra


1 admn_no int NO PRI NULL
2 stud_name varchar(25) YES NULL
3 gender varchar(6) YES NULL
4 class varchar(3) YES NULL
5 section varchar(2) YES NULL

Inserting Values into the Table:

insert into student(admn_no, stud_name, gender, class, section) values


(125,'Raja','Male','XII','A');
insert into student(admn_no, stud_name, gender, class, section) values
(225,'Raghu','Male','XII','B');
insert into student(admn_no, stud_name, gender, class, section) values
(325,'Roja','Female','XII','C1');
insert into student(admn_no, stud_name, gender, class, section) values
(150,'Rama','Female','XII','C2');
insert into student(admn_no, stud_name, gender, class, section) values
(250,'Rajesh','Male','XII','C3');
insert into student(admn_no, stud_name, gender, class, section) values
(350,'Rajeswari','Female','XII','D');

select * from student;


# admn_no stud_name gender class section
1 125 Raja Male XII A
2 150 Rama Female XII C2
3 225 Raghu Male XII B
4 250 Rajesh Male XII C3
5 325 Roja Female XII C1
6 350 Rajeswari Female XII D

Altering Table:

ALTER table student ADD dept varchar(20);

select * from student;

# admn_no stud_name gender class section dept


1 125 Raja Male XII A NULL
2 150 Rama Female XII C2 NULL
3 225 Raghu Male XII B NULL
4 250 Rajesh Male XII C3 NULL
5 325 Roja Female XII C1 NULL
6 350 Rajeswari Female XII D NULL

ALTER table student MODIFY column admn_no varchar(5);

desc student;

# Field Type Null Key Default Extra


1 admn_no varchar(5) NO PRI NULL
2 stud_name varchar(25) YES NULL
3 gender varchar(6) YES NULL
4 class varchar(3) YES NULL
5 section varchar(2) YES NULL
6 dept varchar(20) YES NULL

ALTER table student Drop Column dept;

desc student;
# Field Type Null Key Default Extra
1 admn_no varchar(5) NO PRI NULL
2 stud_name varchar(25) YES NULL
3 gender varchar(6) YES NULL
4 class varchar(3) YES NULL
5 section varchar(2) YES NULL

Updating Table:

update student SET dept = 'Mat/Bio/NEET' where admn_no = '125';


update student SET dept = 'Mat/Bio' where admn_no = '325';
update student SET dept = 'Mat/CS' where admn_no = '150';
update student SET dept = 'Mat/CS/IIT' where admn_no = '225';
update student SET dept = 'CS/Bio' where admn_no = '250';
update student SET dept = 'CS/BS' where admn_no = '350';

select * from students;

# admn_no stud_name gender class section dept


1 125 Raja Male XII A Mat/Bio/NEET
2 150 Rama Female XII C2 Mat/CS
3 225 Raghu Male XII B Mat/CS/IIT
4 250 Rajesh Male XII C3 CS/Bio
5 325 Roja Female XII C1 Mat/Bio
6 350 Rajeswari Female XII D CS/BS

ORDER By to display data:

select * from student order by admn_no ASC;

# admn_no stud_name gender class section dept


1 125 Raja Male XII A Mat/Bio/NEET
2 150 Rama Female XII C2 Mat/CS
3 225 Raghu Male XII B Mat/CS/IIT
4 250 Rajesh Male XII C3 CS/Bio
5 325 Roja Female XII C1 Mat/Bio
6 350 Rajeswari Female XII D CS/BS
select * from student order by admn_no DESC;

# admn_no stud_name gender class section dept


1 350 Rajeswari Female XII D CS/BS
2 325 Roja Female XII C1 Mat/Bio
3 250 Rajesh Male XII C3 CS/Bio
4 225 Raghu Male XII B Mat/CS/IIT
5 150 Rama Female XII C2 Mat/CS
6 125 Raja Male XII A Mat/Bio/NEET

select * from student order by section ASC;

# admn_no stud_name gender class section dept


1 125 Raja Male XII A Mat/Bio/NEET
2 225 Raghu Male XII B Mat/CS/IIT
3 325 Roja Female XII C1 Mat/Bio
4 150 Rama Female XII C2 Mat/CS
5 250 Rajesh Male XII C3 CS/Bio
6 350 Rajeswari Female XII D CS/BS

select * from student order by section DESC;

# admn_no stud_name gender class section dept


1 350 Rajeswari Female XII D CS/BS
2 250 Rajesh Male XII C3 CS/Bio
3 150 Rama Female XII C2 Mat/CS
4 325 Roja Female XII C1 Mat/Bio
5 225 Raghu Male XII B Mat/CS/IIT
6 125 Raja Male XII A Mat/Bio/NEET

select sum(admn_no) as sum, avg(admn_no) as average, count(*) as count,


min(admn_no) as minimum, max(admn_no) as maximum from student;

# sum average count minimum maximum


1 1425 237.5 6 125 350
Pr No: Date:
Database Table [SQL Joins]
25

SQL Joins:

Table 1 Creation - add_book_detail

create table add_book_detail(Book_Title varchar(100), Author_Name


varchar(30), Publisher_Name varchar(50), Book_Issue_No integer (6), Price
integer(6),PRIMARY KEY (Book_Issue_No));

Inserting Values into table:

insert into add_book_detail (Book_Title, Author_Name, Publisher_Name,


Book_Issue_No, Price) values ('Python Programming', 'Balagurusamy', 'Oxford',
1357, 299);
insert into
add_book_detail(Book_Title,Author_Name,Publisher_Name,Book_Issue_No,Price)
values ('C Programming', 'Balagurusamy','Pearson',2468,399);
insert into
add_book_detail(Book_Title,Author_Name,Publisher_Name,Book_Issue_No,Price)
values ('SQL Complete Reference', 'Illmashri','SCI-Index',1324,699);
insert into
add_book_detail(Book_Title,Author_Name,Publisher_Name,Book_Issue_No,Price)
values ('C Basics', 'Dennis Ritchie','SCI-Index',1894,499);
insert into
add_book_detail(Book_Title,Author_Name,Publisher_Name,Book_Issue_No,Price)
values ('SQL Complete Reference', 'Nandhini','Pearson',1524,399);
insert into
add_book_detail(Book_Title,Author_Name,Publisher_Name,Book_Issue_No,Price)
values ('Java Basics', 'Ramesh Babu','Lakshmi',1994,399);

select * from add_book_detail;


# Book_Title Author_Name Publisher_ Book_Issue Price
Name _No
1 SQL Complete Reference Illmashri SCI-Index 1324 699
2 Python Programming Balagurusamy Oxford 1357 299
3 SQL Complete Reference Nandhini Pearson 1524 399
4 C Basics Dennis Ritchie SCI-Index 1894 499
5 Java Basics Ramesh Babu Lakshmi 1994 399
6 C Programming Balagurusamy Pearson 2468 399

Table 2 Creation - issue_book_details

create table issue_book_details(Stud_Name varchar(30), Class varchar(4),


Card_No integer(5), Book_Issue_No integer (6), Duration_time integer(3),
Issue_Date Date, Return_Date Date, PRIMARY KEY (Card_No));
insert into
issue_book_details(Stud_Name,Class,Card_No,Book_Issue_No,Duration_time,Is
sue_Date,Return_Date) values
('Miruthula','X',5432,1894,10,'05.08.2022','19.08.2022');
insert into
issue_book_details(Stud_Name,Class,Card_No,Book_Issue_No,Duration_time,Is
sue_Date,Return_Date) values
('Ramesh','XI',5423,1357,10,'05.08.2022','19.08.2022');
insert into
issue_book_details(Stud_Name,Class,Card_No,Book_Issue_No,Duration_time,Is
sue_Date,Return_Date) values (
'Mari','XII',5420,2468,10,'06.08.2022','19.08.2022');
insert into
issue_book_details(Stud_Name,Class,Card_No,Book_Issue_No,Duration_time,Is
sue_Date,Return_Date) values
('Rakesh','IX',5440,1324,10,'06.08.2022','19.08.2022');

select * from issue_book_details;

# Stud_Name Class Card_No Book_ Duration_ Issue_ Return_


Issue_No time Date Date
1 Mari XII 5420 2468 10 06.08.2022 19.08.2022
2 Ramesh XI 5423 1357 10 05.08.2022 19.08.2022
3 Miruthula X 5432 1894 10 05.08.2022 19.08.2022
4 Rakesh IX 5440 1324 10 06.08.2022 19.08.2022
Inner Join:

select
issue_book_details.Stud_Name,issue_book_details.Class,add_book_detail.Boo
k_Title,add_book_detail.Price,issue_book_details.Issue_Date,issue_book_de
tails.Return_Date from add_book_detail inner join issue_book_details on
add_book_detail.Book_Issue_No = issue_book_details.Book_Issue_No;

# Stud_Name Class Book_Title Price Issue_ Return_


Date Date
1 Mari XII C Programming 399 06.08.2022 19.08.2022
2 Ramesh XI Python Programming 299 05.08.2022 19.08.2022
3 Miruthula X C Basics 499 05.08.2022 19.08.2022
4 Rakesh IX SQL Complete 699 06.08.2022 19.08.2022
Reference
Pr No: Date:
Integrate SQL with Python
26

Database Connection With Python

Establish Connection - One DB

import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base = "school")
print(mydb)

Output
<mysql.connector.connection_cext.CMySQLConnection object at
0x0000023EDCC672B0>

How to create cursor object and use it

import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234")
mycursor=mydb.cursor()
#mycursor.execute("create database if not exists school")
mycursor.execute("show databases")
for x in mycursor:
print(x)

Output
('12class',)
('information_schema',)
('mysql',)
('performance_schema',)
('sakila',)
('school',)
('sys',)
('testdb',)
('world',)

Create Table
import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base="school")
mycursor=mydb.cursor()
mycursor.execute("create table stud(rollno int(3) primary key,name
varchar(20),age int(2))")
print("Successfully Table Created")

Output
Successfully Table Created

insert data into Table

import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base="school")
mycursor=mydb.cursor()
while 1==1:
ch=int(input("enter 100 to exit any other no to insert record into student
table"))
if ch==100:
break
rollno=int(input("Enter rollno"))
name=input("Enter name")
age=int(input("Enter Age"))
mycursor.execute("insert into student
values('"+str(rollno)+"','"+name+"','"+str(age)+"')")

mydb.commit()

Output
enter 100 to exit any other no to insert record into student table10
Enter rollno565
Enter nameTharun
Enter Age18
enter 100 to exit any other no to insert record into student table100
Search Records

import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base="school")
mycursor=mydb.cursor()
rollno=int(input("enter rollno"))
mycursor.execute("select * from student where rollno='"+str(rollno)+"'")
for x in mycursor:
print(x)

Output
enter rollno565
(565, 'Tharun', 18)

Select all Records

import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base="school")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
myrecords=mycursor.fetchall()
for x in myrecords:
print (x)

Output
(565, 'Tharun', 18)

update

import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base="school")
mycursor=mydb.cursor()
mycursor.execute("update student set marks=99 where rollno=2")
mydb.commit()
delete

import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base="school")
mycursor=mydb.cursor()
mycursor.execute("delete from student where rollno=1")
mydb.commit()

You might also like