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

Comp File - Practical File

The document contains details of Python practical programs done by a student. It includes programs on recursion, file handling, random number generation, data structures, plotting graphs, SQL queries and more. Each program is explained with input, output and code snippets.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Comp File - Practical File

The document contains details of Python practical programs done by a student. It includes programs on recursion, file handling, random number generation, data structures, plotting graphs, SQL queries and more. Each program is explained with input, output and code snippets.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

SCHOOL OF EXCELLENCE

Dwarka Sector-22, Delhi-110075

Class XII
Python Practical File

Name – Anshul
Class – XIIth
Roll No. –
INDEX
S.No. Topic Teacher’s
Siganture
1. Recursively find the factorial of a
natural number
2. Read a file line by line and print it.
3. Remove all the lines that contain the
character `a' in a file and write it to
another file.
4. Write a Python function sin(x, n) to
calculate the value of sin(x) using its
Taylor series expansion up to n terms.
Compare the values of sin(x) for
different values of n with the correct
value.
5. Write a random number generator that
generates random numbers between 1
and 6 (simulates a dice).
6. Write a recursive code to find the sum
of all elements of a list.
7. Write a recursive code to compute the
nth Fibonacci number.
8. Write a Python program to implement
a stack and queue using a list data-
structure
9. Write a recursive Python program to
test if a string is a palindrome or not.
10. Write a Python program to plot the
function y = x2 using the pyplot or
matplotlib libraries.
11. Compute EMIs for a loan using the
numpy or scipy libraries.
12. Create a graphical application that
accepts user inputs, performs some
operation on them, and then writes the
output on the screen. For example,
write a small calculator. Use the tkinter
library.
13. Open a webpage using the urllib
library.
14. Take a sample of 10 phishing e-mails
and find the most common words.
15. Find the min, max, sum, and average of
the marks in a student marks table.
16. Find the total number of customers
from each country in the table
(customer ID, customer name, country)
using group by.
17. Write a SQL query to order the
(student ID, marks) table in descending
order of the marks.
18. Integrate SQL with Python by importing
the MySQL module.
19. Write a Django based web server to
parse a user request(POST), and write
it to a CSV file.
PRACTICAL-1
1) Recursively find the factorial of a natural number
# Python program to find the factorial of a number using recursion

def recur_factorial(n):
"""Function to return the factorial
of a number using recursion"""
if n == 1:
return n
else:
return n*recur_factorial(n-1)

# Change this value for a different result


num = int(input("Enter the No.: "))
# 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))
PRACTICAL-2
2) Read a file line by line and print it.

fh = open('my_text_file.txt')
while True:
# read line
line = fh.readline()
# in python 2, print line
# in python 3
print(line)
# check if line is not empty
if not line:
break
fh.close()
PRACTICAL-3
3) Remove all the lines that contain the character `a' in a file
and write it to another file.
f1=open("test1.txt", "r")
f2=open("test2.txt", "w")
while True:
test=f1.readline()
if len(test)==0:
break
if test[0]=="a":
continue
f2.write(test)
f1.close()
f2.close()
PRACTICAL-4
4) Write a Python function sin(x, n) to calculate the value of
sin(x) using its Taylor series expansion up to n terms.
Compare the values of sin(x) for different values of n with the
correct value.

import math
x=float( input(' Enter value of x: '))
n =int(input(‘Enter Value of n:’))
b=0
for i in range (n):
a=(((((-1)**i))*(x**((2*i)+1)))/(math.factorial((2*i)+1)))
b+=a
print (b)
PRACTICAL-5
5) Write a random number generator that generates random
numbers between 1 and 6 (simulates a dice).
import random
print(random.randint(1,6)
PRACTICAL-6
6) Write a recursive code to find the sum of all elements of a
list.

def sumOfList(list, size):


if (size == 0):
return 0
else:
return list[size - 1] + sumOfList(list, size - 1)

l=eval(input(“Enter a list:”))
total = sumOfList(l, len(l))

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


PRACTICAL-7
7) Write a recursive code to compute the nth Fibonacci
number.
def Fibonacci(n):
if n<0:
print("Incorrect input")
# First Fibonacci number is 0
elif n==0:
return 0
# Second Fibonacci number is 1
elif n==1:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)

n=int(input(“Enter a no.:”))
print(Fibonacci(n))
PRACTICAL-8
8) Write a Python program to implement a stack and queue
using a list data-structure.

=>Implementing a stack 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)

=>Implementing a queue using a list data-structure


fruits = []

fruits.append('banana')

fruits.append('grapes')

fruits.append('mango')

fruits.append('orange')

first_item = fruits.pop(0)

print(first_item)

first_item = fruits.pop(0)

print(first_item)

print(fruits)
PRACTICAL-9
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!")


PRACTICAL-10
10) Write a Python program to plot the function y = x2 using
the pyplot or matplotlib libraries.

import matplotlib.pyplot as plt

x = [1,2,3,4,5]
y = [1,4,9,16,25]

plt.plot(x, y)

plt.xlabel('x - axis')

plt.ylabel('y - axis')

# function to show the plot

plt.show()
PRACTICAL-11
11) Compute EMIs for a loan using the numpy or scipy
libraries.
import numpy as np
# assume annual interest of 7.5%
interest = 7.5
annual_rate = interest/100.0
monthly_rate = annual_rate/12
# assume payment over 15 years
years = 15
number_month = years * 12
# assume a loan value of RS 200,000
loan_value = 200000
monthly_payment = abs(np.pmt(monthly_rate, number_month, loan_value))
sf1 = "Paying off a loan of RS {:,} over {} years at"
sf2 = "{}% interest, your monthly payment will be RS {:,.2f}"
print(sf1.format(loan_value, years))
print(sf2.format(interest, monthly_payment))
PRACTICAL-12
12) Create a graphical application that accepts user inputs,
performs some operation on them, and then writes the
output on the screen. For example, write a small calculator.
Use the tkinter library.
from tkinter import *
expression = ""
def press(num):
global expression
expression = expression + str(num)
equation.set(expression)
def equalpress():
try:
global expression
total = str(eval(expression))
equation.set(total)
expression = ""
except:
equation.set(" error ")
expression = ""
def clear():
global expression
expression = ""
equation.set("")
if __name__ == "__main__":
gui = Tk()
gui.configure(background="light green")
gui.title("Simple Calculator")
gui.geometry("265x125")
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='orange',
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=0)
button2 = Button(gui, text=' 2 ', fg='black', bg='orange',
command=lambda: press(2), height=1, width=7)
button2.grid(row=2, column=1)
button3 = Button(gui, text=' 3 ', fg='black', bg='orange',
command=lambda: press(3), height=1, width=7)
button3.grid(row=2, column=2)
button4 = Button(gui, text=' 4 ', fg='black', bg='orange',
command=lambda: press(4), height=1, width=7)
button4.grid(row=3, column=0)
button5 = Button(gui, text=' 5 ', fg='black', bg='orange',
command=lambda: press(5), height=1, width=7)
button5.grid(row=3, column=1)
button6 = Button(gui, text=' 6 ', fg='black', bg='orange',
command=lambda: press(6), height=1, width=7)
button6.grid(row=3, column=2)
button7 = Button(gui, text=' 7 ', fg='black', bg='orange',
command=lambda: press(7), height=1, width=7)
button7.grid(row=4, column=0)
button8 = Button(gui, text=' 8 ', fg='black', bg='orange',
command=lambda: press(8), height=1, width=7)
button8.grid(row=4, column=1)
button9 = Button(gui, text=' 9 ', fg='black', bg='orange',
command=lambda: press(9), height=1, width=7)
button9.grid(row=4, column=2)
button0 = Button(gui, text=' 0 ', fg='black', bg='orange',
command=lambda: press(0), height=1, width=7)
button0.grid(row=5, column=0)
plus = Button(gui, text=' + ', fg='black', bg='orange',
command=lambda: press("+"), height=1, width=7)
plus.grid(row=2, column=3)
minus = Button(gui, text=' - ', fg='black', bg='orange',
command=lambda: press("-"), height=1, width=7)
minus.grid(row=3, column=3)
multiply = Button(gui, text=' * ', fg='black', bg='orange',
command=lambda: press("*"), height=1,
width=7)
multiply.grid(row=4, column=3)
divide = Button(gui, text=' / ', fg='black', bg='orange',
command=lambda: press("/"), height=1,
width=7)
divide.grid(row=5, column=3)
equal = Button(gui, text=' = ', fg='black', bg='orange',
command=equalpress, height=1, width=7)
equal.grid(row=5, column=2)
clear = Button(gui, text='Clear', fg='black', bg='orange',
command=clear, height=1, width=7)
clear.grid(row=5, column='1')
gui.mainloop()
PRACTICAL-13
13) Open a webpage using the urllib library.
import urllib.request

x = urllib.request.urlopen('https://www.google.com/')
print(x.read())
PRACTICAL-14
14) Take a sample of 10 phishing e-mails and find the most
common words.

Phishing email
Most common words:
1) Free
2) Click here
3) Congratulations
4) Lottery
5) Voucher
6) Gift
7) Prize
8) Submit your details
9) Demo

Hyperlinks and always present in a phishing email


PRACTICAL-15
15) Find the min, max, sum, and average of the marks in a
student marks table.
SELECT min(TOTAL),max(TOTAL),sum(TOTAL),avg(TOTAL) FROM STUDENT;
PRACTICAL-16
16) Find the total number of customers from each country
in the table (customer ID, customer name, country) using
group by.
SELECT Country,count(*) FROM CUSTOMERS GROUP BY COUNTRY;
PRACTICAL-17
17) Write a SQL query to order the (student ID, marks) table
in descending order of the marks.
SELECT STUDENT_ID,MARKS FROM STUDENT ORDER BY MARKS DESC;
PRACTICAL-18
18) Integrate SQL with Python by importing the MySQL
module

import mysql.connector

mydb = mysql.connector.connect(host="localhost", user="root",


password="123456", database="school")

print(mydb)
PRACTICAL-19
19) Write a Django based web server to parse a user request
(POST), and write it to a CSV file.

You might also like