Program
Program
if n == 1:
return n
else:
return n*recur_factorial(n-1)
if num < 0:
elif num == 0:
else:
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.
>>>
1
PROGRAM 2
READ A FILE LINE BY LINE AND PRINT IT.
filepath ='Iliad.txt'
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
>>>
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')
outfile.write(infile.read())
print'Files merged.'
final_output = open('FinalMergedOutput.txt','r+b')
final_output.write(line)
final_output.write(line)
4
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32
>>>'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;
i=i +1;
break;
print(round(sinx));
cal_sin(n);
6
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32
>>> 90
1
7
PROGRAM 5
while True:
outcome = randint(1,6)
dice_faces=[1,2,3,4,5,6]
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
8
PROGRAM 6
list = [11,5,17,18,23]
def sumOfList(list,size):
if (size == 0):
return 0
else:
total = sumOfList(list1,len(list1))
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32
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
>>>21
10
PROGRAM 8
Stack = ["Amar","Akbar","Anthony"]
Stack.append("Ram")
Stack.append("Iqbal")
Print(stack)
Print(stack.pop())
Print(stack)
Print(stack.pop())
Print(stack)
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
>>>
['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:
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32
String is a palindrome!
>>>Enter string:hello
13
PROGRAM 10
WRITE A PYTHON PROGRAM TO PLOT THE FUNCTION Y=X
USING THE PYPLOT OR MATPLOT LIBRARIES.
# 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)
Plt.show()
14
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
on win32
>>>
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.
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.grid(columnspan=4,ipadx=70)
button1.grid(row=2,column=0)
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
>>>
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
>>>
20
PROGRAM 13
COMPUTE EMI FOR A LOAN USING THE NUMPY OR SCIPY
LIBRARIES.
def_init_(self):
window=Tk()
window.title(“Loan Calculator”)
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()
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)
window.mainloop()
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
>>>
23
PROGRAM 14
TAKE A SAMPLE OF 10 PHISHING E-MAILS AND FIND THE
MOST COMMON WORDS.
import collections
import pandas as pd
file=open('PrideandPrejudice.txt',encoding="utf8")
a=file.read()
stopwords = stopwords.union(set(['mr','mrs','one','two','said']))
wordcount = {}
word=word.replace(".","")
word=word.replace(",","")
word=word.replace(":","")
word=word.replace("\"","")
word=word.replace("!","")
word=word.replace("*","")
wordcount[word] = 1
else:
24
wordcount[word] += 1
word_counter = collections.Counter(wordcount)
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
>>>
25
1:Find the min, max, sum, and average of the marks in
a student marks table.
Table : student
SQL Queries
Command-
26
2. Find the total no of customers from each country in the table
(customer ID, customer name, country) using group by.
Table: Customer
FROM Customer
GROUP BY Country
27
3. Write a SQL query to order the (student ID, marks)
table in descending order of the marks.
Table:Student_marks
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
28
SELECT name, science, 'science' FROM student_marks
) as t
ORDER BY name, mark DESC
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
import csv
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
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