Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Program File Finalsr

The document provides code snippets for various Python programming tasks including checking if a number is a palindrome, solving a quadratic equation, generating terms of an arithmetic progression, converting currencies, removing letters from strings, printing the Fibonacci sequence, and multiplying matrices.

Uploaded by

slideshare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Program File Finalsr

The document provides code snippets for various Python programming tasks including checking if a number is a palindrome, solving a quadratic equation, generating terms of an arithmetic progression, converting currencies, removing letters from strings, printing the Fibonacci sequence, and multiplying matrices.

Uploaded by

slideshare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

SUNBEAM SCHOOL, VARUNA

VARANASI

Computer science (083)

Program on
Python and SQL

Session : 2020-2021

Under The Guidance of: Made By:


Class: 12-G Roll no:

1|Page
index
S.NO CONTENT Pg.NO
1) The day number in the year in the range 2 to 365 and ask the first
day of the year Sunday or Monday or Tuesday etc.

2) Reads a date as an integers in the format MMDDYYYY

3) Reads a string and checks whether it is a palindrome string or not

4) Write a Python Program to Solve a simple Quadratic Equation

5) Dictionary add three name and their phone in the dictionary after
getting input from user

6) Write a Python function that accepts a string and calculate the


number of uppercase letters and lowercase letters

7) Generates 4 terms of an AP by providing initial and step values to


a function that returns first four terms of the series

8) Takes amount-in-dollars and dollar-to-rupee conversion price

9) Take a string and a letter (as a single-character string) as


arguments returning a copy of that string

10) Write a python Program to Print the Fibonacci sequence

11) Write a Python Program to Multiply Two Matrices using nested list

12) Write a program to count the words "to" and "the" present in a
text file "Poem.txt"

13) Write a program that takes a number and checks if it is a happy


number.

14) Write a method/function DISPLAYWORDS() in python to read lines


from a text file STORY.TXT

2|Page
15) Write a program to read and display content of file from end to
beginning.

16) Write a program to read and display content of a CSV file-


(‘tras.csv’, ‘w’).

17) write a nested Python list to a csv file in one go

18) Write a program to read and display content of a CSV file-


(‘tras.csv’, ‘w’)

19) Write a program to search and row count content of a CSV file.

20) Write a program to search and row count content of a CSV file.

21) Write a program to enter records of 3 students in csv file.

22) Write a python program to read a file line by line store it into an
array.

23) Create a table named ‘GYM’ to store information about fitness


items being sold in it.

24) Queries on the table GYM.

25) Program for connectivity as Interface python with MySQL.

26) Showing Queries for Cartesian Product.

27) Showing Queries for Table Aliases.

28) Showing Queries for Equi-join and Natural- join.

29) Queries on the database School .

1: Write a program that ask the user the day number in the year in the
range 2 to 365 and ask the first day of the year Sunday or Monday or

3|Page
Tuesday etc. Then the program should display the day on the day
number that has been input.

d = {"Sunday":1,"Monday":2,"Tuesday":3,"Wednesday":4,"Thursday":5,
"Friday":6,"Saturday":7}
days = { 1 :"Sunday",2:"Monday",3:"Tuesday",4:"Wednesday",5:"Thursday",
6:"Friday",7:"Saturday"}
dic= { }
user = int(input("Enter a number between 2 to 365 = "))

day = input("Enter first day of year (Sunday, Monday,


Tuesday,Wednesday,Thursday,Friday,Saturday)")

first = d[day]
print(first)

for j in range(1,366) :
dic[ j ] = first
if first == 7 :
first = 0
first += 1

a = dic[ user ]
print(days [ a ])

2: Write a program that reads a date as an integers in the


format MMDDYYYY. The program will call a function that
prints print out the date in the format <month name > <day>,
<year>.

4|Page
mon = ["january", "february","march" , "april", "may" , "june" , "july" ,
"august ", "september ", "october ", "november" , 'december ']

a = int (input("enter the date = " ))

month = a // 1000000 date =


(a % 1000000) // 10000 year
= a % 10000

Print ( mon [month - 1 ] , date ," , ", year )


3: Write a program that reads a string and checks whether it is
a palindrome string or not.

String = input(“Enter a string ”)


length = len(string) mid =
length/2 rev=-1

for a in range(mid):
if
string[a]==string[rev
]: a +=1 rev -= 1
else:
print(string, “is not palindrome”)
break
else:
print(string, “is palindrome”)

5|Page
4:Write a Python Program to Solve a simple Quadratic
Equation.

# Solve the quadratic equation ax**2 + bx + c = 0

import cmath

a =int(input(“enter A:”))
b = int(input(“enter B:”))
c = int(input(“enter C:”))

d = (b**2) - (4*a*c)

sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))


5: Write code to create a python dictionary add three name and
their phone in the dictionary after getting input from user. The
names should act as keys and phones as their values. Then ask
the user a name and print its corresponding phone.

dic = {}

for i in range (3):

6|Page
name = input ("Enter the name :- ") phone =
input ("Enter the Phone number :- ")
dic[ name ] = phone

while True :
a = input("Enter the name from the dictionary
(For exit enter 'q'):- “)
if a == "q"or a== "Q":
break
else :
print (dic[a])
6: Write a Python function that accepts a string and calculate
the number of uppercase letters and lowercase letters.

def string_test(s):
d = {"UPPER_CASE" : 0, "LOWER_CASE" : 0}
for c in s:
if c.isupper():
d["UPPER_CASE"] += 1
elif c.islower ():
d["LOWER_CASE"] += 1
else:
pass

print ("Original String : ", s)


print ("No. of Uppercase characters : ", d["UPPER_CASE"])
print ("No. of Lowercase characters : ", d["LOWER_CASE"])
7|Page
string_test('PythonProgramminG')
7: Write a program that generates 4 terms of an AP by
providing initial and step values to a function that returns first
four terms of the series.

def retSeries(init, step ): return init, init + step, init +


2 * step, init + 3 * step

ini = int(input("Enter initial value of the AP series : "))

st = int(input("Enter step value of the AP series : "))

print("Series with initial value", ini, "& step value", st, "goes as:")

t1, t2, t3, t4 = retSeries(ini, st)

print(t1, t2, t3, t4)


8: Write a function that takes amount-in-dollars and dollar-to-
rupee conversion price; it then returns the amount converted to
rupees. Create the function in both void and non-void forms.

def rup(doll) : #void print(" (void ) rupees in ",doll


,"dollar = ",doll * 72)

def rupee(doll) : # non Void


return doll * 72

8|Page
doll = float(input("Enter dollar : "))
rup(doll) #void

print(" ( non void ) rupees in ",doll ,"dollar = ", rupee(doll) )


# non Void
9: Write a function that should take a string and a letter (as a
single-character string) as arguments returning a copy of that
string with every instance of the indicated letter removed.

def remove_letter( sentence , letter ) :

new_sentence = "" sen =


sentence.split ( letter ) for i
in sen :
new_sentence += i
return new_sentence

sentence = input("Enter a sentance = ")

letter = input("Enter a letter = ")

print ( remove_letter (sentence , letter) )


10: Write a python Program to Print the Fibonacci sequence.

nterms = int(input("How many terms? "))

9|Page
n1, n2 = 0, 1
count = 0

# check if the number of terms is valid if


nterms <= 0: print("Please enter a
positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1) nth =
n1 + n2 #
update values
n1 = n2 n2 =
nth count += 1

11: Write a Python Program to Multiply Two Matrices using


nested list.

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]] # result
10|Page
is 3x4 result =
[[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]

# iterate through rows of X


for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])): #
iterate through rows of Y for k
in range(len(Y)): result[i][j] +=
X[i][k] * Y[k][j]

for r in result:
print(r)
12: Write a program to count the words "to" and "the" present
in a text file "Poem.txt".

to_no = 0

the_no = 0

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


lst = file.readlines()

for i in lst :

11|Page
word = i.split()
for j in word :
if j == "to" :
to_no += 1
elif j == "the" or j == "The" :
the_no += 1

print("Number 'to' : " , to_no)


print("Number 'the' : " , the_no)

file.close()
13: Write a program that takes a number and checks if it is a
happy number.

def sum_sq_digits (num,n= 0):


if n == len(num) :
return 0
else : return ( int ( num [ n ] ) ) ** 2 + sum_sq_digits
(num,n+1)

def Ishappy( num ):


if sum_sq_digits (num) == 1 :
print("Happy number ")

elif len(num) == 1 : print("Not


happy number ")

12|Page
else :
num = str( sum_sq_digits (num) )
Ishappy( num )

num = input("Enter a number : ")


Ishappy( num )
14: Write a method/function DISPLAYWORDS() in python to
read lines from a text file STORY.TXT, and display those
words, which are less than 4 characters.

def DISPLAYWORDS() :
file = open("story.txt",
"r") lst = file.readlines()
for i in lst :
word = i.split()
for j in word :
if len( j ) < 4 :
print( j )

file.close()

DISPLAYWORDS()
15: Write a program to read and display content of file from
end to beginning.

f1 = open("pathwala.txt",'r')

13|Page
data = f1.readlines()
content = "" for i in
data : content +=
i+"\n"

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


print(content[ i ],end = "")

f1.close()

14|Page
16. Write a program to read and display content of a CSV file-
(‘tras.csv’, ‘w’).

import csv
fh=open('tras.csv','w')
sw=csv.writer(fh)
sw.writerow(["name","class","b.no.","area"])
for I in range(5):
print('enter your info')
nm=input('name:-')
cl=int(input('class:-'))
b_no=int(input('bus number:-'))
area=input("enter your area")
stu=[nm,cl,b_no,area]
sw.writerow(stu) fh.close()

17 : Write a Python program to write a nested Python list to a


csv file in one go. After writing the CSV read the CSV file and
display the content.

import csv

file = open( "Pathwala.txt","r+" ) lst =


eval(input("Enter a nested list :-"))
path_write = csv.writer( file)
path_write.writerows( lst )
15|Page
data =
csv.reader(file) for i
in data : print(i)

file.close()
18 : Write a program to read and display content of a
CSVfile-(‘tras.csv’, ‘w’).

def push(dict):
l=list() for i
in dict :
if dict[i]>75:
l.append(i)
return l

def pop(L1):
l2=[] if
len(L1)!=0:
for i in range(0,len(L1)):
x=L1.pop()
l2.append(x)
return l2

16|Page
d1={'OM':76,'JAI':45,'BOB':89,'ALI':65,'ANU':90,'TOM':82}
l=push(d1) print(pop(l))

19: Write a program to search and row count content of a CSV


file.

import csv
ob=open('data.csv','r+'
) fb=csv.reader(ob) def
ssearch(AdmNo): for i
in fb: if i[0]==AdmNo:
print("records present :","admno name class marks ",'\n',i)
def rcount():
count=0
for i in fb:
count+=1
print('No of records=',count)
x=int(input('Enter adm no'))
ssearch(x)

20 : Write a program that depending upon user's choice, either


pushes or pops an element in a stack the elements are shifted
towards right so that top always remains at 0th (zero) index.

stack = [ ] while True : com =


input("Enter ( Push or Pop ) : ")

17|Page
if com == "push" or com == "Push" :
num = int(input("Enter a number : "))
stack.insert(0,num)

elif len(stack) == 0 :
print("Underflow")

elif com == "pop" or com == "Pop" :


stack.pop(0)

yes = input ("Enter ( Yes or no ) : ")

if yes == "No" or yes == "no":


print("Thank you !!!!")
break
21: Write a program to enter records of 3 students in csv file.

import csv
ob=open('data.csv','w+')
f=csv.writer(ob,delimiter='|')
f.writerow(['admno','name','class','marks'])
f.writerow(['10486','Ishaan','12','50'])
f.writerow(['10445','devansh','12','50'])
f.writerow(['10487','satvik','12','50'])
18|Page
22: Write a python program to read a file line by line store it
into an array.

def file_read(fname):
content_array = []
with open(fname) as
f:
#Content_list is the list that contains the read lines.
for line in f:
content_array.append(line)
print(content_array)

file_read('test.txt')

19|Page
23: Create a table named ‘GYM’ to store information about
fitness items being sold in it.

CREATE TABLE GYM(ICODE INTEGER PRIMARY KEY, INAME


CHAR(20), PRICE INTEGER , BRANDNAME CHAR(20));

#populate the table GYM with a few rows:


INSERT INTO GYM VALUES (101, 'Power Fix Exerciser', 20000,
‘Power gymea’);
INSERT INTO GYM VALUES (102, 'Aquafit Hand Grip', 1800,
‘Reliable’);
INSERT INTO GYM VALUES (103, 'Cycle Bike', 14000, ‘Ecobike’);
INSERT INTO GYM VALUES (104, 'Protoner Extreme Gym' ,30000 ,
‘Coscore’);
INSERT INTO GYM VALUES (105,’Message Belt’, 5000, ‘Message
Expert’);
INSERT INTO GYM VALUES (106, ‘Cross Trainer’, 13000, ‘GTC
Fitness’);

#query to look at table STATS in undefined order:

SELECT * FROM STATS;

24: Queries on the table GYM.

# Query To display the names of all the items whose name


starts with "A". select * from GYM Where INAME like “A%”;
20|Page
#Query to display ICODEs and INAMEs of all items, whose
Brandname is Reliable or Coscore.
select ICODE , INAME from GYM Where BRANDNAME in
(“Reliable” , “Coscore” );

#Query to change the Brandname to "Fit Trend India" of the


item, whose ICODE as "101".
update GYM Set BRANDNAME = “Fit Trend India ” Where ICODE =
“101” ;

#Query to Add a new row for new item in GYM with the details :
"G107", "Vibro exerciser", 21000, "GTCFitness" insert
into GYM values ("G107", "Vibro exerciser", 21000,
"GTCFitness") ;
25: Program for connectivity as Interface python with
MySQL.

import mysql.connector as sqtor


mycon=sqtor.connect(host='localhost', user='root',passwd='
',database='school', charset='utf-8')

if mycon.is_connected():
print('connected')
21|Page
cur=con.cursor()
cur.execute("select * from
stu") data=cur.fetchall()
print(data)

St="Select * from student where marks > %s” % 75


cur.exeute(st)

st=“insert into stu (roll_no,name,marks,grade,sec)


values({},’{}’,
{},’{}’,’{}’)”.formate(8,’fiza’,45,’B’,’D’)
cur.execute(st) con.commit()

st=“update stu set per={} where roll_no={}“.formate(85,5)


cur.execute(st) con.commit()

st=“delete from stu where roll_no={}”.formate(8)


cur.execute(st) con.commit()

22|Page
26. Showing Queries for Cartesian Product.

27. Showing Queries for Table Aliases

23|Page
28. Showing Queries for Equi-join and Natural- join.

24|Page
29. Queries on the database School .

25|Page
26|Page
27|Page

You might also like