Complete python programs
Complete python programs
print("Hello_World")
Output:-
Output:-
Q5-Program for obtain length and breadth of a rectangle and its
area.
#Asking length and breadth from user
l = float(input("Enter Length of the rectangle:"))
b = float(input("Enter Breadth of the rectangle:"))
#Calculate the area
area = l*b
#Print the area
print("The area of rectangle Length=",l,"Breadth=",b,"is",area)
Output:-
Q6-'''Program to input number and print its square and cube'''
#Asking number from user
n = int(input("Enter the value:"))
#square of number
s = n*n
#Cube of number
c = n*n*n
#Print the square and cube of no.
print("Square of number",n,"is",s,"and Cube is",c)
Output:-
Q7-'''Program to swap the 3 values eachother'''
#Asking the values form user
a = int(input("Enter the value1:"))
b = int(input("Enter the value2:"))
c = int(input("Enter the value3:"))
#Print original value
print("The original values are",a,b,c,)
#Print swap values
a,b,c = b,c,a
print("After swapping :",a,b,c)
Output:-
Q8-'''Program for calculate the area and volume of sphere '''
'''With math module'''
#First import math module
import math
#Asking for radius of sphere
r = float(input("Enter the value in meter:"))
#Area of sphere
a = math.pi*r*r
#Volume of sphere
v = 4*math.pi*math.pow(r,3)
#Print Area and Volume
print("The radius of sphere is",r,"meter")
print("The area of sphere is",a,"meter square")
print("The volume of sphere is",v,"meter cube")
Output:-
Q9-'''Program to Calculate and display the area of triangle
Using Heron's formula'''
#Import math module
import math
#Asking values from user
a = int(input("Enter the side1 of triangle:"))
b = int(input("Enter the side2 of triangle:"))
c = int(input("Enter the side3 of triangle:"))
#Heron's formula
s = a+b+c/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
#Print sides and area
print("Sides of triangle are",a,b,c)
print("Area of triangle is",area,"units square")
Output:-
Q10-'''Program to check given number is even or odd'''
#Asking the value from user
n = int(input("Enter the value:"))
#if statement for check the number is even or odd
if n%2==0:
print(n,"is Even number")
#else statement for false condition
else:
print(n,"is Odd number")
Output:-
Q11-'''Program to check largest number'''
#Asking for values from user
a = float(input("Enter First number:"))
b = float(input("Enter second number:"))
c = float(input("Enter Third number:"))
#Making another variable for check
m=a
if b > m:
m=b
if c > m:
m=c
print("Largest number is",m)
Output:-
Q12-'''Program to check given character is uppercase or
lowercase or digit'''.
#Asking the value from user
n = input("Enter the single char only:")
#Giving conditional statement
if n >= 'A' and n <= 'Z':
print("Character in uppercase")
elif n >= 'a' and n <= 'z':
print("Character in lowercase")
elif n >= '0' and n <= '9':
print("You entered a digit")
else:
print("You entered special character")
Output:-
Q13-'''Program to check Armstrong Number'''
num = int(input("Enter the number:"))
#Initialize sum
sum = 0
#Find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //=10
if num == sum:
print(num,"is Armstrong number")
else:
print(num,"is not Armstrong number")
Output:-
Q14-'''Program to find factorial of number'''
n = int(input("Enter the range:"))
fact = 1
if n < 0:
print("Please Enter posiitve number")
elif n == 0:
print("Factorial of 0! is 1")
else:
for i in range(1,n+1):
fact = fact * i
print("Factorial of",i,"is",fact)
Output:-
Q15-'''Program to print tables using for loop'''
#Asking the value from user
n = int(input("Enter the value:"))
for i in range(1,11):
print(n,"x",i,"=",n*i)
Output:-
Q16-'''Program to print sum of numbers.
Program ends with saying no in the program, Using while loop'''
sum = 0
ans = "y"
while ans == "y":
n = int(input("Enter the value:"))
if n < 0:
print("Entered no. is negative. Aborting!")
#jump statement for cancel next step
break
sum = sum + n
ans = input("Wants to enter more values? (y/n)...")
print("The sum of numbers are",sum)
Output:-
Q17-'''Program to create star pattern
using double loop'''
n = int(input("Enter the value:"))
for i in range(1,n+1):
for j in range(1,i+1):
print("*",end=" ")
print()
Output:-
Q18-'''Program to print Fibonacci series'''
n = int(input("Enter the value:"))
n1 = 0
n2 = 1
count = 0
print(n1,end=" ")
print(n2,end=" ")
while count < n:
r = n1 + n2
print(r,end=" ")
n1 = n2
n2 = r
count = count+1
Output:-
Q19-'''Progarm to make simple calculator'''
o = input("What operation u want:")
print("OK now enter two no.")
n1 = int(input("Enter the value 1:"))
n2 = int(input("Enter the value 2:"))
if o == "+":
n = n1 + n2
print(n)
elif o == "-":
n = n1 - n2
print(n)
elif o == "*":
n = n1 * n2
print(n)
elif o == "/":
n = n1 / n2
print(n)
Output:-
Q20-Program to check prime number
n = int(input("Enter the value:"))
if n == 1:
print(n,"is not a prime number")
if n == 2:
print(n,"is prime number")
if n > 1:
for i in range(2,n):
if n % 2 == 0:
print(n,"is not a prime number")
break
else:
print(n,"is a prime number")
break
Output:-
Q21-'''Program to solve Quadratic equation'''
a = int(input("Enter the coefficient of x^2:"))
b = int(input("Enter the coefficient of x:"))
c = int(input("Enter the constant term:"))
d = (b**2)-(4*a*c)
if d > 0:
print("Equation has two real and distinct roots.")
if d == 0:
print("Equation has two real and equal roots.")
if d < 0:
print("Equation has no real roots and roots are imagenary.")
r1 = (-b+(d)**(1/2))/(2*a)
r2 = (-b-(d)**(1/2))/(2*a)
print("Roots are",r1,r2)
Output:-
Q22-'''Program to sum of series 1+x+x^2+...+x^n'''
x = float(input("Enter value of x:"))
n = int(input("Enter value of n:"))
s=1
for i in range(n+1):
s += x**i
print("Sum of first",n,"terms",s)
Output:-
Q23-'''Program to print ssum of series 1-x+x^2-...x^n'''
x = int(input("Enter value of x:"))
n = int(input("Enter value of n:"))
s=1
sign = +1
for i in range(0,n+1):
t = (x**i)*sign
s += t
sign *= -1
print("Sum of first",n,"terms:",s)
Output:-
Q24-'''Program to check number is palindrome'''
n = int(input("Enter the value:"))
r=0
temp = n
while temp > 0:
r = r * 10 + (temp % 10)
temp = temp//10
if n == r:
print(n,"is a palindrome")
else:
print(n,"is not palindrome")
Output:-
Q25-'''Program to design a dice throw'''
#Importing random module
import random
n = int(input("Ho many dice throw?:"))
for i in range(1,n+1):
print("Throw",i,":",random.randint(1,6))
Output:-
Q26-'''Program to check leap year'''
n = int(input("Enter a 4-digit year:"))
if n%100==0:
if n%400==0:
l = True
else:
l = False
elif n%4==0:
l = True
else:
l = False
if l == True:
print(n,"is a leap year")
else:
print(n,"is not a leap year")
Output:-
Q27-'''Program to find location of character in given string'''
s = input("Enter the text:")
c = input("Enter a character:")
for i in range(len(s)):
if s[i]==c:
print(i,end=" ")
Q28-'''Program to count words in string'''
s = input("Enter the line text:")
count = 0
for i in s.split():
print(i)
count += 1
print("Total words:",count)
Output:-
Q29-'''Program to print number of upper case
and lower case letter in it'''
str1 = input("Enter a string:")
count1,count2 = 0,0
for i in str1:
if i >= "A" and i <= "Z":
count1 += 1
if i >= "a" and i <= "z":
count2 += 1
print("NO. of uppercase:",count1)
print("NO. of lowercase:",count2)
Output:-
Q30-'''Program to capital first letter of string and lower other
letters'''
s=input("Enter a string:")
print(s.capitalize())
Output:-
Output:-
Q34-'''Prorgram to append list and int'''
l = [1,2,3]
print("Existing list is:",l)
n = eval(input("Enter a no. or list:"))
if type(n) == type([]):
l.extend(n)
elif type(n) == type(1):
l.append(n)
else:
print("Pls enter no. or list")
print("Appended list is:",l)
Output:-
Q35-'''Program to ascend & descend a list'''
val = eval(input("Enter a list:"))
val.sort()
print("Sorted in ascending order:",val)
val.sort(reverse = True)
print("Sorted in descending order:",val)
Output:-
Q36-'''Program to calculate mean of list'''
lst = eval(input("Enter a list:"))
l = len(lst)
m=s=0
for i in range(0,l):
s += lst[i]
m = s/l
print("Given list is:",lst)
print("The mean of given list is:",m)
Output:-
Q37-'''Program to reverse a list'''
l1 = eval(input("Enter a list:"))
l2 = []
s = len(l1)
for i in range(s-1,-1,-1):
l2.append(l1[i])
print("Reversed list is:",l2)
Output:-
Q38-'''Program to search an element in list'''
l1 = eval(input("Enter a list:"))
l = len(l1)
e = int(input("Enter for search no."))
for i in range(0,l):
if e == l1[i]:
print(e,"at index",i)
break
else:
print(e,"not found")
Output:-
Q39-'''Program to print element of tuple'''
t = ("Pyhton","is","fun.","Isn't","it")
l = len(t)
for i in range(l):
print("At index",i,"&",(i-l),"element:",t[i])
Output:-
Q40-'''Program to input tuple and all element are same'''
tup = eval(input("Enter a tuple:"))
ln = len(tup)
n = tup.count(tup[0])
if n == ln:
print(tup,"same element.")
else:
print(tup,"different element.")
Output:-
Q41-'''Program to read students IDs and seperate user and
domain name'''
lst = []
n = int(input("How many students:"))
for i in range(1,n+1):
email = input("Enter email of student"+str(i)+":")
lst.append(email)
etup = tuple(lst)
lst1 = []
lst2 = []
for i in range(n):
email = etup[i].split("@")
lst1.append(email[0])
lst2.append(email[1])
unametup = tuple(lst1)
dnametup = tuple(lst2)
print("Student email IDs:",etup)
print("User name tuple:",unametup)
print("Domain name tuple:",dnametup)
Output:-
Q42-'''Program to input students and store in a tuple, and
search name in tuple'''
lst=[]
n = int(input("How many students?"))
for i in range(1,n+1):
name = input("Enter name of students"+str(i)+":")
lst.append(name)
ntuple = tuple(lst)
m = input("Enter name to be search:")
if m in ntuple:
print(m,"exists in tuple")
else:
print(m,"doesn't exists in tuple")
Output:-
W
Q43-'''Program to store marks of students in 5 subjects and
grade them'''
m = eval(input("Enter marks tuple:"))
total = sum(m)
avg = total/5
if avg >= 75:
grade = "A"
elif avg >= 60:
grade = "B"
elif avg >= 50:
grade = "C"
else:
grade = "D"
print("Total Marks:",total,"Grade:",grade)
Output:-
Q44-'''Program to read roll no. and marks of n student and
create dictionary from it'''
n = int(input("How many students?"))
d = {}
for i in range(n):
r,m = eval(input("Enter Roll no. ,Marks:"))
d[r] = m
print(d)
Output:-
Q45-'''Program to make dictionary form list'''
k = [1,2,3]
v = ["One","Two","Three"]
n = dict(zip(k,v))
print("Given lists are:",k,v)
print("Created dictionary",n)
Output:-
Q46-'''Program to delete key and value in dic'''
d = {}
n = int(input("How many students?"))
for i in range(n):
r,m = eval(input("Enter Roll no. ,Marks:"))
d[r] = m
print(d)
rno = int(input("Roll no. to be deleted:"))
if rno in d:
del d[rno]
print("Roll no.",rno,"deleted.")
else:
print("Roll no.",rno,"doesn't exist.")
print("Final dictionary",d)
Output:-
Q47-'''Program to read sentence and find frequency of letters'''
s = input("Enter a sentence:")
s = s.lower()
ad = "abcdefghijklmnopqrstuvwxyz0123456789"
count = {}
print("Total char in sentence",len(s))
for i in s:
if i in ad:
if i in count:
count[i] += 1
else:
count[i] = 1
print(count)
Output:-
Q48-'''Program to print max, min, sum of dic'''
n = {1:111,2:222,3:333,4:444}
print("Given dic is:",n)
mx = max(n)
mn = min(n)
print("Max and Min keys:",mx,mn)
mxv = max(n.values())
mnv = min(n.values())
print("Max and Min values:",mxv,mnv)
ks = sum(n)
vs = sum(n.values())
print("Sum of dic's keys:",ks)
print("Sum of dic's values:",vs)
Output:-
Q49-'''Program to sort a list using Bubble sort'''
l = [15,6,13,22,3,2]
n = len(l)
for i in range(n):
for j in range(0,n-i-1):
if l[j] > l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
print("List after sorting",l)
Output:-
Q50-'''Program to sort list using insertion sort'''
l = [7,25,1,2,13,5]
for i in range(1,len(l)):
key = l[i]
j = i-1
while j>=0 and key<l[j]:
l[j+1]=l[j]
j -= 1
else:
l[j+1]=key
print("List after sort",l)
Output:-
Q51-'''First program to using function'''
#Creating funtion
def calsum(x,y):
s=x+y
return s
Output:-
Q52-'''Program to calculate simple interest using function'''
def interest(p,t=2,r=0.1):
c = p*t*r
return c
#__main__
p = float(input("Enter principal value:"))
print("SI with default ROI and time:")
si1 = interest(p)
print("Rs.",si1)
r = float(input("Enter Rate of interest ROI:"))
t = int(input("Enter time in years:"))
print("SI with given ROI and Time:")
si2 = interest(p,t,r/100)
print("Rs.",si2)
Output:-
Q53-'''Program to perform all opertion of two no.'''
#Function
def arcal(x,y):
return x+y,x-y,x*y,x/y
#__main__
n1 = int(input("Enter number 1:"))
n2 = int(input("Enter number 2:"))
add,sub,mult,div = arcal(n1,n2)
print("Sum of given no.",add)
print("Subtract of given no.",sub)
print("Product of given no.",mult)
print("Division of given no.",div)
Output:-
Q54-'''Program to open text file in python'''
#First open file in read mode
f = open("Poem.txt","r")
#File is open now
str = f.read() #To read data from file
size = len(str)
print(str)
print("size of file is:",size,"bytes")
f.close()
#Closing file to clean environment
Output:-
Q55-'''Program to insert students details in file'''
c = int(input("How many students?"))
f = open("Marks.txt","w")
for i in range(c):
print("Enter detail for student",(i+1),"below:")
r = int(input("Enter Rollno."))
n = input("Enter Name:")
m = float(input("Enter marks:"))
rec = str(r)+","+n+","+str(m)+'\n'
f.write(rec)
f.close()
Output:-
Q56-'''Program on inserting data in binary file'''
#First import binary file Library
import pickle
stu = {}
stufile = open("Stu.bin","wb") #opne file
#Getting data to write onto file
ans = "y"
while ans =="y":
r = int(input("Enter Roll no."))
n = input("Enter name:")
m = float(input("Enter Marks:"))
#Add read data to dic
stu["Roll no."] = r
stu["Name"] = n
stu["Marks"] = m
#dump is used to write in bin file
pickle.dump(stu,stufile)
ans=input("Want to enter more records?(y/n):")
print("Data Entered Successfully!")
stufile.close() #Close file
Output:-
Q57-'''Program to display bin file content'''
import pickle
stu = {}
stufile = open("Stu.bin","rb")
#read from the file
try:
while True:
stu = pickle.load(stufile)
print(stu)
except EOFError:
stufile.close()
Output:-
Q58-'''Program to search for records in bin file'''
import pickle
stu = {}
found = False
f = open("Stu.bin","rb")
skey = eval(input("Enter roll no. to search:"))
try:
while True:
stu = pickle.load(f)
if stu["Roll no."] in skey:
print(stu)
found = True
except EOFError:
if found == False:
print("NO records found.")
else:
print("search successful!")
f.close()
Output:-
Q59-'''Program to write data in CSV file'''
#Importing csv library
import csv
f = open("Student.csv","a+") #open file
n = int(input("How many students?"))
stuwriter = csv.writer(f)
stuwriter.writerow(['Roll no.','Name','Marks'])
for i in range(1,n+1):
print("Student record",i)
r = int(input("Enter Roll no."))
n = input("Enter Name:")
m = float(input("Enter Marks:"))
sturec = [r,n,m]
stuwriter.writerow(sturec)
f.close()
Output:-
Q60-'''Program to read data from CSV file'''
import csv
f = open("Student.csv","r",newline='\r\n')
cr = csv.reader(f)
for rec in cr:
print(rec)
Output:-
Q61-'''Stack Implementation'''
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 empty")
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])
#__main__
Stack = []
top = None
while True:
print("Stack Operations")
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.Display")
print("5.Exit")
ch=int(input("Enter ur choice:"))
if ch == 1:
item=int(input("Enter item:"))
Push(Stack,item)
elif ch == 2:
item = Pop(Stack)
if item == "Underfow":
print("Underflow! Stack is Empty!")
else:
print("Popped item is:",item)
elif ch == 3:
item = Peek(Stack)
if item == "Underfow":
print("Underflow! Stack is Empty!")
else:
print("Topmost item is:",item)
elif ch == 4:
Display(Stack)
elif ch == 5:
break
else:
print("Invalid Choice!")
Output:-
Q62-'''Queue Implementation'''
def cls():
print("\n"*100)
def isEmpty(qu):
if qu == []:
return True
else:
return False
def Enqueue(qu,item):
qu.append(item)
if len(qu) == 1:
front = rear = 0
else:
rear = len(qu)-1
def Dequeue(qu):
if isEmpty(qu):
return "Underflow"
else:
item = qu.pop(0)
if len(qu) == 0:
front = rear = None
return item
def Peek(qu):
if isEmpty(qu):
return "Underflow"
else:
front = 0
return qu[front]
def Display(qu):
if isEmpty(qu):
print("Queue Empty!")
elif len(qu) == 1:
print(qu[0],"<==front,rear")
else:
front = 0
rear = len(qu)-1
print(qu[front],"<-front")
for i in range(1,rear):
print(qu[i])
print(qu[rear],"<-rear")
#__main__
queue = []
front = None
while True:
cls()
print("QUEUE OPERATIONS")
print("1.Enqueue")
print("2.Dequeue")
print("3.Peek")
print("4.Display Queue")
print("5.Exit")
ch=int(input("Enter ur Choioce:"))
if ch == 1:
item = int(input("Enter item:"))
Enqueue(queue,item)
input("Press Enter to continue...")
elif ch == 2:
item = Dequeue(queue)
if item == "Underflow":
print("Underflow! Queue is Empty!")
else:
print("Dequeue-ed item is:",item)
input("Press Enter to continue...")
elif ch == 3:
item = Peek(queue)
if item == "Underflow":
print("Queue is Empty!")
else:
print("Frontmost item is:",item)
input("Press Enter to continue...")
elif ch == 4:
Display(queue)
input("Press Enter to continue...")
elif ch == 5:
break
else:
print("Invalid choice!")
input("Press Enter to continue...")
Output:-
Q63-'''Program to connect Mysql and python'''
#Making connectivity b/w mysql and python
import mysql.connector
mycon=mysql.connector.connect(host="localhost",\
user="root",\
passwd="5555")
mycur=mycon.cursor()
if mycon.is_connected():
print("Connected Successfully!")
mycur.execute("Show Databases")
for i in mycur:
print(i)
Output:-
Q64-'''Program to create table in mysql using python'''
import mysql.connector
mycon=mysql.connector.connect(host="localhost",\
user="root",\
passwd="5555",\
database="school")
if mycon.is_connected():
print("Successfully Connected!")
mycur=mycon.cursor()
q="CREATE TABLE Teacher\
(ID int(3) Primary key,\
Name varchar(20),\
Class int(2),\
Age int(2),\
Subject varchar(25))"
mycur.execute(q)
print("Created Table Successfully!")
Output:-
Tables in Sql:-
Structure of Table:-
Q65-'''Program to show tables in Database'''
import mysql.connector
mycon=mysql.connector.connect(host="localhost",\
user="root",\
passwd="5555",\
database="school")
mycur=mycon.cursor()
q="SHOW TABLES"
mycur.execute(q)
for i in mycur:
print(i)
Output:-
Q66-'''Program to show Table stucture'''
import mysql.connector
mycon=mysql.connector.connect(host="localhost",\
user="root",\
passwd="5555",\
database="school")
mycur=mycon.cursor()
q="desc student"
mycur.execute(q)
for i in mycur:
print(i)
Output:-
Q67-'''Program to insert data in Table'''
import mysql.connector
mycon=mysql.connector.connect(host="localhost",\
user="root",\
passwd="5555",\
database="school")
mycur=mycon.cursor()
c='y'
while c=='y':
rno=int(input("Enter Roll_no.:"))
name=input("Enter Name:")
cls=int(input("Enter Class:"))
sec=input("Enter Section:")
sub=input("Enter Subject:")
fee=float(input("Enter Fees:"))
q="insert into student values('{0}','{1}','{2}','{3}','{4}','{5}')"\
.format(rno,name,cls,sec,sub,fee)
mycur.execute(q)
mycon.commit()
print("'Added Record Successfully!'")
c=input("Do u want Continue y/n:")
Output:-
Q68-'''Program to show data in existing table'''
import mysql.connector
mycon=mysql.connector.connect(host="localhost",\
user="root",\
passwd="5555",\
database="school")
mycur=mycon.cursor()
q="select * from student"
mycur.execute(q)
myrec=mycur.fetchall()
for i in myrec:
print(i)
Output:-
Q-Query to see all existing Databases in SQL.
mysql> show databases;
mysql> select * from student where name not like ' % i % ' ;
Q-Query using not condition
mysql> select * from student where Subject not in ('PCB') ;