0% found this document useful (0 votes)
48 views

Program

The programs cover topics like recursion, file handling, random number generation, data structures, plotting graphs and GUI programming using Tkinter. The programs demonstrate various Python programming concepts like functions, loops, conditional statements, lists, dictionaries etc.

Uploaded by

TK Gyaan Sagar
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)
48 views

Program

The programs cover topics like recursion, file handling, random number generation, data structures, plotting graphs and GUI programming using Tkinter. The programs demonstrate various Python programming concepts like functions, loops, conditional statements, lists, dictionaries etc.

Uploaded by

TK Gyaan Sagar
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/ 33

PROGRAM 1.

RECURSIVELY FIND THE FACTORIAL OF A NATURAL NUMBER.


def recur_factorial(n):

if n == 1:

return n

else:

return n*recur_factorial(n-1)

# take input from the user

num = int(input(“enter the number:”))

#check is the number is negative

if num < 0:

print(“sorry, factorial does not exist for negative numbers”)

elif num == 0:

print(“the factorial of 0 is 1”)

else:

print(“the factorial of ”,num,”is”,recur_factorial(num))

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32
Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


================================

>>>

- The factorial of 7 is 5040

1
PROGRAM 2
READ A FILE LINE BY LINE AND PRINT IT.

filepath ='Iliad.txt'

with open(filepath) as fp:

line=fp.readline()

cnt=1

while line:

print("Line{}:{}".format(cnt,line.strip()))

line=fp.readline()

cnt+=1

2
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


================================

>>>
Line 1: $ python forlinein.py
Line 2: Line 0: BOOK I
Line 3: Line 1:
Line 4: Line 2: The quarrel between Agamemnon and Achilles--Achilles
withdraws
Line 5: Line 3: from the war, and sends his mother Thetis to ask Jove to
help
Line 6: Line 4: the Trojans--Scene between Jove and Juno on Olympus.
Line 7: Line 5:
Line 8: Line 6: Sing, O goddess, the anger of Achilles son of Peleus, that
brought
Line 9: Line 7: countless ills upon the Achaeans. Many a brave soul did it
send
Line 10: Line 8: hurrying down to Hades, and many a hero did it yield a
prey to dogs and
Line 11: Line 9: vultures, for so were the counsels of Jove fulfilled from
the day on
Line 12: ...

3
PROGRAM 3
REMOVE ALL THE LINES THAT CONTAIN THE CHARACTER ‘A’
IN A FILE AND WRITE IT TO ANOTHER FILE.

import glob

read_files=glob.glob('/home/user/Results/Script_tests/TestResults/*.output')

with open('MergedOutput.txt','r+b')as outfile:

for file in read_files:

with open (file,'r+b') as infile:

outfile.write(infile.read())

print'Files merged.'

final_output = open('FinalMergedOutput.txt','r+b')

with open('MergedOutput.txt','r+b')as file:

for line in file:

if line == 0 and line.startswith('File'):

final_output.write(line)

elif line >0 and not line.startswith('File'):

final_output.write(line)

print'Headers removed except on line 1.'

4
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


================================

>>>'MergedOutput.txt
the big big fat cat
the cat who likes milk
jumped over gray rat
concat
this is catchy
rat
rational
irrational
'FinalMergedOutput.txt'concat
this is catchy
rational
irrational

5
PROGRAM 4
WRITE A PYTHON FUNCTION SIN(X,N) TO CALCULATE THE
VALUE OF SIN(X) USINGITS TAYLOR SERIES EXPANSION UPTO
N TERMS.COMPARE THE VALUES OF SIN(X) FOR DIFFERENT
VALUES OF N WITH THE CORRECT VALUE.

import math;

def cal_sin(n):

accuracy=0.0001;

n=n*(3.142/180.0);

x1=n;

sinx=n;

sinval = math.sin(n);

i=1;

while(True):

denominator = 2*i*(2*i+1):

x1=-x1*n*n/denominator;

sinx = sinx + x1;

i=i +1;

if(accuracy <= abs(sinval-sinx)):

break;

print(round(sinx));

n=90; # Driver code

cal_sin(n);

6
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


================================

>>> 90
1

7
PROGRAM 5

WRITE A RANDOM NUMBER GENERATOR THAT GENERATES


RANDOM NUMBERS BETWEEN 1 AND 6(SIMULATES A DICE).

From random import randint

while True:

outcome = randint(1,6)

print("you rolled the dice and it returned:",outcome)

input("press any key to continue the game.")

from random import seed,choice

dice_faces=[1,2,3,4,5,6]

print("rolling a dice using python random functions…")

for iter in range(3):

seed(10)

print(choice(dice_faces))

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


================================

>>> Rolling a dice using Python random functions...


>>>5
>>>5
>>>5

8
PROGRAM 6

WRITE A RECURSIVE CODE TO FIND THE SUM OF ALL


ELEMENTS OF A LIST.

list = [11,5,17,18,23]

def sumOfList(list,size):

if (size == 0):

return 0

else:

return list[size – 1] + sumOfList(list,size-1)

total = sumOfList(list1,len(list1))

print(“Sum of all elements in given list: ,total”)

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


================================

>>> Sum of all elements in given list: 74

9
PROGRAM 7
WRITE A RECURSIVE CODE TO COMPUTE THE n FIBONACCI
NUMBER.

def Fibonacci(n):

if n<0:

print(“incorrect input”)

elif n==1:

return 0

elif n==2:

return 1

else;

return Fibonacci(n-1)+Fibonacci(n-2)

print(Fibonacci(9))

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


================================

>>>21

10
PROGRAM 8

WRITE A PYTHON PROGRAM TO IMPLEMENT TO A STACK AND


QUEUE USING A LIST DATA-STRUCTURE.

Stack = ["Amar","Akbar","Anthony"]

Stack.append("Ram")

Stack.append("Iqbal")

Print(stack)

Print(stack.pop())

Print(stack)

Print(stack.pop())

Print(stack)

# Queue using deque and list


From collection import deque

Queue =deque(["Ram","Tarun","Asif","John"])

Print(queue)

Queue.append("Akbar")

Print(queue)

Queue.append("Birbal")

Print(queue)

Print(queue.popleft())

Print(queue.popleft())

Print(queue)

11
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


================================

>>>
['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']
Iqbal
['Amar', 'Akbar', 'Anthony', 'Ram']
Ram
['Amar', 'Akbar', 'Anthony']
>>>
deque(['Ram', 'Tarun', 'Asif', 'John'])
deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar'])
deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar', 'Birbal'])
Ram
Tarun
deque(['Asif', 'John', 'Akbar', 'Birbal'])

12
PROGRAM 9
WRITE A RECURSIVE PYTHON PROGRAM TO TEST IF A STRING
IS A PALINDROME OR NOT.

def is_palindrome(s):

if len(s) <1:

return True

else:

if s[0] == s[-1]:

return is_palindrome(s[1:-1])

else:

return False

a=str(input("enter string:"))

if (is_palindrome(a) == True):

print("string is a palindrome!")

else:

print("string isn't a palindrome!")

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


================================

>>> Enter string:mom

String is a palindrome!

>>>Enter string:hello

String isn't a palindrome!

13
PROGRAM 10
WRITE A PYTHON PROGRAM TO PLOT THE FUNCTION Y=X
USING THE PYPLOT OR MATPLOT LIBRARIES.

# importing matplotlib module from matplotlib

import pyplot as plt

# X-axis values

X = [5,2,9,4,7]

#Y-axis values

Y = [10,5,8,4,2]

#function to plot

Plt.plot(x,y)

#function to show the plot

Plt.show()

14
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


==============================

>>>

15
PROGRAM 11
CREATE A GRAPHICAL APPLICATION THAT ACCEPTS USER
INPUT, PERFORM SOME OPERATION ON THEM,AND THEN
WRITE THE OUTPUT ON THE SCREEN. FOR EXAMPLE WRITE A
SMALL CALCULATER USE THE TKINTER LIBRARY.

#import everything from tkinter module from tkinter import*.

Expression =""

def press(num):

expression=expression + str(num)

equation.set(expression)

def equalpress():

try:

total = str(eval(expression))

equation.set(total)

expression = ""

except:

equation.set("error")

expression = ""

def clear():

expression = ""

equation.set("")

if_name_=="_main_":

gui = Tk()

gui.configure(background="light green")

gui.title("simple Calculator")

16
gui.geometry("265*125")

equation = StringVar()

expression_field = Entry(gui,textvariable = equation)

expression_field.grid(columnspan=4,ipadx=70)

equation.set(‘enter your expression’)

button1 = Button(gui,text='1', fg='black',


bg='red',command=lamda:press(1),height=1,width=7)

button1.grid(row=2,column=0)

button2 = Button(gui,text='2', fg='black', bg='red',command =


lamda:press(2),height=1,width=7)

button.grid(row=2,column=1)

button3 = Button(gui.text='3',fg='black',bg='red',command =
lamda:press(3),height=1,width=7 )

button.grid(row=2,column=2)

button4 = Button(gui.text='4',fg='black',bg='red',command =
lamda:press(4),height=1,width=7)

button.grid(row=3,column=0)

button5 = Button(gui.text='5',fg='black',bg='red',command =
lamda:press(5),height=1,width=7 )

button.grid(row=3,column=1)

button6 = Button(gui.text='6',fg='black',bg='red',command =
lamda:press(6),height=1,width=7 )

button.grid(row=3,column=2)

button7 = Button(gui.text='7',fg='black',bg='red',command =
lamda:press(7),height=1,width=7 )

button.grid(row=4,column=0)

17
button8 = Button(gui.text='8',fg='black',bg='red',command =
lamda:press(8),height=1,width=7 )

button.grid(row=4,column=1)

button9 = Button(gui.text='9',fg='black',bg='red',command =
lamda:press(9),height=1,width=7 )

button.grid(row=4,column=2)

button0 = Button(gui.text='0',fg='black',bg='red',command =
lamda:press(0),height=1,width=7 )

button.grid(row=5,column=0)

plus=Button(gui,text='+',fg='black',bg='red',command =
lamda:press("+"),height=1,width=7)

plus.grid(row=2,column=3)

minus=Button(gui,text='-',fg='black',bg='red',command =
lamda:press("-"),height=1,width=7)

minus.grid(row=3,column=3)

multiply=Button(gui,text='*',fg='black',bg='red',command =
lamda:press("*"),height=1,width=7)

multiply.grid(row=4,column=3)

divide=Button(gui,text='/',fg='black',bg='red',command =
lamda:press("/"),height=1,width=7)

divide.grid(row=5,column=3)

equal=Button(gui,text='=',fg='black',bg='red',command =
equalpress,height=1,width=7)

equal.grid(row=5,column=3)

clear=Button(gui,text='Clear',fg='black',bg='red',command
=clear,height=1,width=7)

clear.grid(row=5,column=1)

18
gui.mainloop()

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


============================

>>>

19
PROGRAM 12
OPEN A WEBPAGE USING THE URLLIB LIBRARIES.

import urllib.request

request_url=urllib.request.urlopen(‘http://www.amazon.in/’)

print(request_url.read())

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


================================

>>>

20
PROGRAM 13
COMPUTE EMI FOR A LOAN USING THE NUMPY OR SCIPY
LIBRARIES.

#import tkinter from tkinter import *

Class Loan Calculator:

def_init_(self):

window=Tk()

window.title(“Loan Calculator”)

label(window,text=”Annual Interest Rate”).grid(row=1,column =1,sticky =W)

label(window,text=”Number of Years”).grid(row=2,column =1,sticky =W)

label(window,text=”Loan Amount”).grid(row=3,column =1,sticky =W)

label(window,text=”Monthly Payment”).grid(row=4,column =1,sticky =W)

label(window,text=”Total Payment”).grid(row=5,column =1,sticky =W)

self.annualinterestrateVar = StringVar()

entry(window,textvariable = self.annualinterestrateVar,justify =
RIGHT).grid(row = 1,column = 2)

self.numberofyearsVar = StringVar()

entry(window,textvariable = self.numberofyearsVar,justify =
RIGHT).grid(row = 2,column = 2)

self.loanAmountVar = StringVar()

entry(window,textvariable = self.loanAmountVar,justify = RIGHT).grid(row


= 3,column = 2)

self.monthlyPaymentVar = StringVar()

iblMonthlyPayment = Label(window,textvariable =
self.monthlyPaymantVar).grid(row = 4,column = 2,sticky = E)

21
self.totalPaymentVar = StringVar()

iblTotalPayment = Label(window,textvariable =
self.totalPaymentVar).drid(row = 5,column = 2,sticky = E)

btComputePayment = Button(window.text = “Compute Payment”,row =


6,column = 2,sticky = E)

window.mainloop()

def compute Payment(self):

monthlyPayment = self.getMonthlyPayment(float(self.loanAmountVar.get)),

float(self.annualinterestrateVar.get()) /1200,int(self.numberofyearsVar.get())

self,monthlyPaymentVar.set(format(monthlyPayment,’10.2f))

totalPayment = float(self.monthlyPaymentVar.get())*12/

*int(self.numberofyearsVar.get())

Self.totalPaymentVar.set(format(totalPayment,’10.2f’))

Def
getMonthlyPayment(self,loanAmount,monthlyinterestrate,numberofyears):

monthlyPayment = loanAmount*monthlyinterestrate/(1-
1/(1+monthlyinterestrate)**(numberofyears*12))

return monthlyPayment;

root = Tk()

LoanCalculator()

22
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


================================

>>>

23
PROGRAM 14
TAKE A SAMPLE OF 10 PHISHING E-MAILS AND FIND THE
MOST COMMON WORDS.

import collections

import pandas as pd

import matplotlib.pyplot as plt

%matplotlib in line #Read input file, note the encoding is specified


here

file=open('PrideandPrejudice.txt',encoding="utf8")

a=file.read()

stopwords = set(line.strip() for line in open('stopwords.txt'))

stopwords = stopwords.union(set(['mr','mrs','one','two','said']))

wordcount = {}

for word in a.lower().split():

word=word.replace(".","")

word=word.replace(",","")

word=word.replace(":","")

word=word.replace("\"","")

word=word.replace("!","")

word=word.replace("*","")

if word not in stopwords:

if word not in wordcount:

wordcount[word] = 1

else:

24
wordcount[word] += 1

n_print = int(input("How may most common words to print:"))

print("\nOk.The{}most common words are as follows\n".format(n_print))

word_counter = collections.Counter(wordcount)

for word, count in word_counter.most_common(n_print):

print(word,":",count)

file.close()

lst=word_counter.most_common(n_print)

df=pd.DataFrame(lst,columns=['Word','Count'])

df.plot.bar(x='Word',y='Count')

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART


================================

>>>

25
1:Find the min, max, sum, and average of the marks in
a student marks table.
Table : student

id name Class math english


1 John Deo Four 75 55
2 Max Ruin Three 85 85
3 Arnold Three 55 72
4 Krish Star Four 60 66
5 John Mike Four 60 60
6 Alex John Four 55 75

SQL Queries

mysql> Select Sum(mark) from student;

mysql> Select Min(mark) from student;

mysql> Select Max(mark) from student;

mysql> Select Avg(mark) from student;

Command-

SELECT MIN(mark) as min_mark FROM `student`

SELECT MAX( mark ) FROM `student`

SELECT id, name, class,( math+english) AS total FROM `student`

SELECT sum(math+english) as total from student

mysql> Select AVG(mark) from student;

mysql> Select AVG(avg) from student Group By class;

26
2. Find the total no of customers from each country in the table
(customer ID, customer name, country) using group by.
Table: Customer

Cust_Id Cust_name country


1001 Jai Kumar India
1002 Max Ruin USA
1003 Ravi Kumar India
1004 Ajay Kumar India
1005 Krish Star Japan

mysql>SELECT COUNT(cust_Id), Country

FROM Customer

GROUP BY Country

ORDER BY COUNT(Id) DESC

27
3. Write a SQL query to order the (student ID, marks)
table in descending order of the marks.

Table:Student_marks

Std_id Std_name Subject marks


1 Ram Science 85
2 Ram English 80
3 Ram Math 70
4 Shayam Math 80
5 Shayam English 70
6 Shayam Science 65
7 Hari Science 90
8 Hari English 80

mysql>SELECT std_id,
subject,
CASE subject
WHEN 'english' THEN english
WHEN 'math' THEN math
WHEN 'science' THEN science
END marks
FROM student s CROSS JOIN
(
SELECT 'english' subject UNION ALL
SELECT 'math' UNION ALL
SELECT 'science'
)t

ORDER BY name, marks DESC


SELECT name, grad as subject, mark
FROM
(
SELECT name, english as mark, 'english' as grad FROM student_marks
UNION
SELECT name, math, 'math' FROM student_marks
UNION

28
SELECT name, science, 'science' FROM student_marks
) as t
ORDER BY name, mark DESC

| NAME | SUBJECT| MARKS |


|-----------|--------------|------------ |
| Hari | science | 90 |
| Hari | english | 80 |
| Hari | math | 60 |
| Ram | science | 85 |
| Ram | English | 80 |
| Ram | math | 70 |
| shyam | math | 80 |
| shyam | english | 70 |
| shyam | science | 65 |

29
4. Integrate SQL with python by importing the mysql
module.

demo_mysql_test.py
import mysql.connector

#if this page is executed with no errors, you have the "mysql.connector"
module installed.

demo_mysql_connection.py
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)

print(mydb)

demo_mysql_connection.py
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)

print(mydb)

demo_mysql_create_db.py
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)

mycursor = mydb.cursor()

30
mycursor.execute("CREATE DATABASE mydatabase")

#If this page is executed with no error, you have successfully created a
database.

demo_mysql_show_databases.py
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")

for x in mycursor:
print(x)

Run:
C:\Users\My Name>python demo_mysql_show_databases.py
('information_scheme',)
('mydatabase',)
('performance_schema',)
('sys',)

demo_mysql_db_exist.py
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
#If this page is executed with no error, the database "mydatabase" exists in
your system

31
5. Write a Django based web server to parse a user
request (POST) , and write it to a CSV file.
Python CSV library
import csv
from django.http import HttpResponse

def some_view(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition']='attachment;
filename="somefilename.csv"'

writer = csv.writer(response)
writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

return response

Streaming large CSV files

import csv

from django.http import StreamingHttpResponse

class Echo:
"""An object that implements just the write method of the file-like
interface.
"""
def write(self, value):
"""Write the value by returning it, instead of storing in a buffer."""
return value

def some_streaming_csv_view(request):
"""A view that streams a large CSV file."""
# Generate a sequence of rows. The range is based on the maximum
number of
# rows that can be handled by a single sheet in most spreadsheet
# applications.
rows = (["Row {}".format(idx), str(idx)] for idx in range(65536))
pseudo_buffer = Echo()

32
writer = csv.writer(pseudo_buffer)
response = StreamingHttpResponse((writer.writerow(row) for row in
rows),
content_type="text/csv")
response['Content-Disposition'] = 'attachment;
filename="somefilename.csv"'
return response

Using the template system


from django.http import HttpResponse
from django.template import Context, loader

def some_view(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment;
filename="somefilename.csv"'

# The data is hard-coded here, but you could load it from a database or
# some other source.
csv_data = (
('First row', 'Foo', 'Bar', 'Baz'),
('Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"),
)

t = loader.get_template('my_template_name.txt')
c = Context({
'data': csv_data,
})
response.write(t.render(c))
return response

33

You might also like