Upload
others
View
22
Download
1
Embed Size (px)
Citation preview
2019
PYTHON PROGRAMS 1.2
DEEPAK BHINDEDEEPAK BHINDEDEEPAK BHINDEDEEPAK BHINDE
PGT COMPUTER SCIENCEPGT COMPUTER SCIENCEPGT COMPUTER SCIENCEPGT COMPUTER SCIENCE
www.dbgyan.wordpress.com
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 2
No. Program
1.
Task: Python program to convert time from 12 hour to 24 hour format
2. Task: Python program to swap two elements in a list
3. Task: Program for Selection Sort.
4. Task: Python program for implementation of Bubble Sort
5. Task: Python program for implementation of Insertion Sort
6. Task: Python program to find the factorial of a number using recursion.
7. Task: Python Program to calculate the value of sin(x) and cos(x).
8. Task: Python Program to a recursive code to find the sum of all elements of a
list.
9. Task: Write a recursive code to compute the nth Fibonacci number.
10. Task: Write Python program to convert floating to binary
11. Task: Write Python program to convert float decimal to octal number
12. Task: Write Python program Password validation.
13. Task: Python program to generate one-time password (OTP).
14. Task: Python program to generate QR Code using pyqrcode module.
15. Task: Python program to get IP Address.
16. Task: Python program to write a File.
17. Task: Python program to read from the File.
18. Task: Python program to merge Two Files.
19. Task :Python program to copy one file to another file.
20. Task:Python program to delete file.
21. Task :Python program to implement a stack.
22. Task: Python program to implement a Queue.
23. Task: Compute EMIs for a loan using the numpy or scipy libraries.
24. Task: Create a graphical application that accepts user inputs , performs some
operation on them and the writes the output on the screen . for example ,
write small calculator. Use the tkinter library.
25. Task : Program to implement to plot function y=X^2 using pyplot or matplotlib
libraries.
TASK POINTS
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 3
Program: 01 Date:
Task: Python program to convert time from 12 hour to 24 hour format
Note: Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is
12:00:00 PM on 12-hour clock and 12:00:00 on 24-hour clock.
Code:
# Function to convert the date format
def convert24(str1):
# checking if last two elements of time is AM and first two elements are 12
if str1[-2:] == "AM" and str1[:2] == "12":
return "00" + str1[2:-2]
# remove the AM
elif str1[-2:] == "AM":
return str1[:-2]
# Checking if last two elements of time is PM and first two elements are 12
elif str1[-2:] == "PM" and str1[:2] == "12":
return str1[:-2]
else:
# add 12 to hours and remove PM
return str(int(str1[:2]) + 12) + str1[2:8]
# Driver Code: passing value & function call
print(convert24("08:05:45 PM"))
Output:
20:05:45
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 4
Program: 02 Date:
Task: Python program to swap two elements in a list
Given a list in Python and provided the positions of the elements, write a program to swap
the two elements in the list.
Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3
Output : [19, 65, 23, 90]
Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5
Output : [1, 5, 3, 4, 2]
Approach #1: Simple swap.
# program to swap elements at given positions
# Swap function
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
# Driver function
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
output :
[19, 65, 23, 90]
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 5
Approach #2 : Using Inbuilt list.pop() function
Pop the element at pos1 and store it in a variable. Similarly, pop the element at pos2 and
store it in another variable. Now insert the two popped element at each other’s original
position.
# program to swap elements at given positions
# Swap function
def swapPositions(list, pos1, pos2):
# popping both the elements from list
first_ele = list.pop(pos1)
second_ele = list.pop(pos2-1)
# inserting in each others positions
list.insert(pos1, second_ele)
list.insert(pos2, first_ele)
return list
# Driver function
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
Output :
[19, 65, 23, 90]
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 6
Approach #3: Using tuple variable
Store the element at pos1 and pos2 as a pair in a tuple variable, say get. Unpack those
elements with pos2 and pos1 positions in that list. Now, both the positions in that list are
swapped.
# program to swap elements at given positions
# Swap function
def swapPositions(list, pos1, pos2):
# Storing the two elements
# as a pair in a tuple variable get
get = list[pos1], list[pos2]
# unpacking those elements
list[pos2], list[pos1] = get
return list
# Driver function
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
Output :
[19, 65, 23, 90]
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 7
Program: 03 Date:
Task: Program for Selection Sort
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The
algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order)
from the unsorted subarray is picked and moved to the sorted subarray.
Code :
# Python program for implementation of Selection Sort
import sys
A = [64, 25, 12, 22, 11]
# Traverse through all array elements
for i in range(len(A)):
# Find the minimum element in remaining unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
# Swap the found minimum element with the first element
A[i], A[min_idx] = A[min_idx], A[i]
# Driver code to test above
print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i]),
Output:
Sorted array
11
12
22
25
64
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 8
Program: 04 Date:
Task: Python program for implementation of Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order.
Code :
# Python program for implementation of Bubble Sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]),
Output:
Sorted array is:
11
12
22
25
34
64
90
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 9
Program: 05 Date:
Task: Python program for implementation of Insertion Sort
Code : # Python program for implementation of Insertion Sort
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])
Output:
Sorted array is:
5
6
11
12
13
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 10
Program: 06 Date:
Task: Python program to find the factorial of a number using recursion.
Code: # 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 = 8
# uncomment to take input from the user
#num = int(input("Enter a 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))
Output:
The factorial of 8 is 40320
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 11
Program: 07 Date:
Task: Python Program to calculate the value of sin(x) and cos(x).
For Sin x function
Code :
# Python3 code for implementing sin function
import math;
# Function for calculating sin value
def cal_sin(n):
accuracy = 0.0001;
# Converting degrees to radian
n = n * (3.142 / 180.0);
x1 = n;
# maps the sum along the series
sinx = n;
# holds the actual value of sin(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;
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 12
print(sinx);
# Driver Code
n = 45;
cal_sin(n);
Output :
0.7047230747708333
For cos function
# Python 3 code for implementing cos function
from math import fabs, cos
# Function for calculation
def cal_cos(n):
accuracy = 0.0001
# Converting degrees to radian
n = n * (3.142 / 180.0)
x1 = 1
# maps the sum along the series
cosx = x1
# holds the actual value of sin(n)
cosval = cos(n)
i = 1
denominator = 2 * i * (2 * i - 1)
x1 = -x1 * n * n / denominator
cosx = cosx + x1
i = i + 1
while (accuracy <= fabs(cosval - cosx)):
denominator = 2 * i * (2 * i - 1)
x1 = -x1 * n * n / denominator
cosx = cosx + x1
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 13
i = i + 1
print('{0:.6}'.format(cosx))
# Driver Code
if __name__ == '__main__':
n = 30
cal_cos(n)
output :
0.86602
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 14
Program: 08 Date:
Task: Python Program to a recursive code to find the sum of all elements of a list.
Given an array of integers, find sum of array elements using recursion.
Examples:
Input : A[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6
Input : A[] = {15, 12, 13, 10}
Output : 50
Code :
# Python program to find sum of array elements using recursion.
# Return sum of elements in A[0..N-1] using recursion.
def _findSum(arr, N):
if len(arr)== 1:
return arr[0]
else:
return arr[0]+_findSum(arr[1:], N)
# driver code
arr =[]
# input values to list
arr = [1, 2, 8, 4, 5,6]
# calculating length of array
N = len(arr)
ans =_findSum(arr,N)
print (ans)
Output :
26
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 15
Program: 09 Date:
Task: Write a recursive code to compute the nth
Fibonacci number.
The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence
relation Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1.
Given a number n, print n-th Fibonacci Number.
Examples:
Input : n = 2
Output : 1
Input : n = 11
Output : 89
Code :
# Function for 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)
# Driver Program
print(Fibonacci(11))
Output:
89
fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2) fib(1)
/ \ / \ / \
fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)
/ \
fib(1) fib(0)
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 16
Approach :
To convert a floating point decimal number into binary, first convert the integer part
into binary form and then fractional part into binary form and finally combine both
results to get the final answer.
For Integer Part, keep dividing the number by 2 and noting down the remainder until
and unless the dividend is less than 2. If so, stop and copy all the remainders
together.
For Decimal Part, keep multiplying the decimal part with 2 until and unless 0 left as
fractional part. After multiplying the first time, note down integral part and again
multiply decimal part of the new value by 2. Keep doing this until reached a perfect
number.
Program: 10 Date:
Task: Write Python program to convert floating to binary
Code -
# Function returns octal representation
def float_bin(number, places = 3):
# split() seperates whole number and decimal part and stores it in two separate
#variables
whole, dec = str(number).split(".")
# Convert both whole number and decimal part from string type to integer type
whole = int(whole)
dec = int (dec)
# Convert the whole number part to it's respective binary form and remove the
# "0b" from it.
res = bin(whole).lstrip("0b") + "."
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 17
# Iterate the number of times, we want the number of decimal places to be
for x in range(places):
# Multiply the decimal value by 2 and seperate the whole number part
# and decimal part
whole, dec = str((decimal_converter(dec)) * 2).split(".")
# Convert the decimal part to integer again
dec = int(dec)
# Keep adding the integer parts receive to the result variable
res += whole
return res
# Function converts the value passed as parameter to it's decimal representation
def decimal_converter(num):
while num > 1:
num /= 10
return num
# Driver Code
# Take the user input for the floating point number
n = input("Enter your floating point value : \n")
# Take user input for the number of decimal places user want result as
p = int(input("Enter the number of decimal places of the result : \n"))
print(float_bin(n, places = p))
Output:
Enter your floating point value :
123.89
Enter the number of decimal places of the result :
4
1111011.1110
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 18
Program: 11 Date:
Task: Write Python program to convert float decimal to octal number
Approach :
To convert a decimal number having fractional part into octal, first convert the
integer part into octal form and then fractional part into octal form and finally
combine the two results to get the final answer.
For Integer Part, Keep dividing the number by 8 and noting down the remainder until
and unless the dividend is less than 8 and copy all the remainders together.
For the Decimal Part, Keep multiplying the decimal part with 8 until and unless we get
0 left as fractional part. After multiplying the first time, note down an integral part
and then again multiply the decimal part of new value by 8 and keep doing this until
perfect number is reached.
Code :
# Function returns the octal representation of the value passed as parameters. 'number'
# is floating point decimal number and 'places' is the number of decimal places
def float_octal(number, places = 3):
# split() seperates whole number and decimal part and stores it in two seperate
#variables
whole, dec = str(number).split(".")
# Convert both whole number and decimal part from string type to integer type
whole = int(whole)
dec = int (dec)
# Convert the whole number part to it's respective octal form and remove the
# "0o" from it.
res = oct(whole).lstrip("0o") + "."
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 19
Out put : Enter your floating point value :
129.45
Enter the number of decimal places of the result :
4
201.3463
# Iterate the number of times we want the number of decimal places to be
for x in range(places):
# Multiply the decimal value by 8 and seperate the whole number part and
#decimal part
whole, dec = str((decimal_converter(dec)) * 8).split(".")
# Convert the decimal part to integer again
dec = int(dec)
# keep adding the integer parts received to the result variable
res += whole
return res
# Function converts the value passed as parameter to it's respective decimal
# representation
def decimal_converter(num):
while num > 1:
num /= 10
return num
# Driver Code
# Take the user input for the floating point number
n = input("Enter your floating point value : \n")
# Take user input for the number of decimal places user would like the result as
p = int(input("Enter the number of decimal places of the result : \n"))
print(float_octal(n, places = p))
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 20
Program: 12 Date:
Approach: Conditions for a valid password are:
1. Should have at least one number.
2. Should have at least one uppercase and one lowercase character.
3. Should have at least one special symbol.
4. Should be between 6 to 20 characters long.
Task: Write Python program Password validation.
Code :
# Password validation in Python using naive method
# Function to validate the password
def password_check(passwd):
SpecialSym =['$', '@', '#', '%']
val = True
#for length should be at least 6
if len(passwd) < 6:
print('length should be at least 6')
val = False
#for length should be not be greater than 20
if len(passwd) > 20:
print('length should be not be greater than 20')
val = False
#for Password should have at least one numeral
if not any(char.isdigit() for char in passwd):
print('Password should have at least one numeral')
val = False
#for Password should have at least one uppercase letter
if not any(char.isupper() for char in passwd):
print('Password should have at least one uppercase letter')
val = False
#for Password should have at least one lowercase letter
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 21
Out put :
enter password for validation :Dbgyan@1234
Password is valid
enter password for validation :db@12
length should be at least 6
Password should have at least one uppercase letter
Invalid Password !!
if not any(char.islower() for char in passwd):
print('Password should have at least one lowercase letter')
val = False
#for checking Password should have at least one of the symbols $@#
if not any(char in SpecialSym for char in passwd):
print('Password should have at least one of the symbols $@#')
val = False
if val:
return val
# Main method
def main():
#user input for entering password
passwd = input("enter password for validation :")
#passwd='Dbgyan@1234'
if (password_check(passwd)):
print("Password is valid")
else:
print("Invalid Password !!")
# Driver Code
if __name__ == '__main__':
main()
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 22
Program: 13 Date:
Approach: One-time Passwords (OTP) is a password that is valid for only one login session or
transaction in a computer or a digital device. Now a days OTP’s are used in almost
every service like Internet Banking, online transactions etc. They are generally
combination of 4 or 6 numeric digits or a 6-digit alphanumeric.
Used Function:
random.random(): This function returns any random number between 0 to 1.
math.floor(): It returns floor of any floating number to a integer value.
Using the above function pick random index of string array which contains all the
possible candidates of a particular digit of the OTP.
Output :
OTP of 4 digits: 5471
OTP of 4 digits: 2077
Task: Python program to generate one-time password (OTP).
Code :
Method 1: Generate 4 digit Numeric OTP
# import library import math, random
# function to generate OTP
def generateOTP() :
# Declare a digits variable which stores all digits
digits = "0123456789"
OTP = ""
# length of password can be changed
# by changing value in range
for i in range(4) :
OTP += digits[math.floor(random.random() * 10)]
return OTP
# Driver code
if __name__ == "__main__" :
print("OTP of 4 digits:", generateOTP())
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 23
Output :
OTP of length 6: jMV3aj
OTP of length 6: 58GEeD
Method 1: Generate alphanumeric OTP of length 6.
# import library
import math, random
# function to generate OTP
def generateOTP() :
# Declare a string variable which stores all string
string = 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
OTP = ""
length = len(string)
for i in range(6) :
OTP += string[math.floor(random.random() * length)]
return OTP
# Driver code
if __name__ == "__main__" :
print("OTP of length 6:", generateOTP())
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 24
Program: 14 Date:
Approach: pyqrcode module is a QR code generator. The module automates most of the building
process for creating QR codes. The terminology and the encodings used
in pyqrcode come directly from the standard.
Installation
$ pip install pyqrcode
Output :
#open file ‘dbgyanqr.svg’
Task: Python program to generate QR Code using pyqrcode module.
Code :
# Import QRCode from pyqrcode
import pyqrcode
from pyqrcode import QRCode
# String which represent the QR code
s = "www.dbgyan.wordpress.com"
# Generate QR code
url = pyqrcode.create(s)
# Create and save the svg
#file naming "dbgyanqr.svg"
url.svg("dbgyanqr.svg", scale = 12)
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 25
Program: 15 Date:
Approach: To get IP address of your computer in python, you have to first import socket library
and then use socket.gethostbyname(socket.gethostname()) code inside the print()
statement to print your IP address as output.
Output :
Want to get IP Address ? (y/n):
y
Your IP Address is: 192.168.1.101
Task: Python program to get IP Address.
Code :
# Python Program - Get IP Address
#import socket package.
import socket;
print("Want to get IP Address ? (y/n): ");
check = input();
if check == 'n':
exit();
else:
print("\nYour IP Address is: ",end="");
print(socket.gethostbyname(socket.gethostname()));
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 26
Program: 16 Date:
Approach: Python program ask from the user to enter the file name to open/create a file and again
ask to enter three lines of sentence to put those sentences in the file as the content of
the file.
Task: Python program to write a File.
Code :
# Python Program - Write to File
print("Enter 'x' for exit.");
#user input for file name.
filename = input("Enter file name to create and write content: ");
# if filename is 'x' then exit.
if filename == 'x':
exit();
else:
#opening /creating file for writing
c = open(filename, "w");
print("\nThe file,",filename,"created successfully!");
print("Enter 3 sentences to write on the file: ");
#user input for first sentences
sent1 = input("enter first sentences:");
#user input for second sentences
sent2 = input("enter second sentences:");
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 27
Output :
Enter 'x' for exit.
Enter file name to create and write content: data.txt
The file, data.txt created successfully!
Enter 3 sentences to write on the file:
enter first sentences:my name is Deepak Bhinde
enter second sentences:my blog is www.dbgyan.wordpress.com
enter third sentences:I am a computer professional.
Content successfully placed inside the file.!!
# data.txt
my name is Deepak Bhinde
my blog is www.dbgyan.wordpress.com
I am a computer professional.
#user input for third sentences
sent3 = input("enter third sentences:");
#write the sentences to entered file
c.write(sent1);
c.write("\n");
c.write(sent2);
c.write("\n");
c.write(sent3);
#closing file
c.close();
print("\nContent successfully placed inside the file.!!");
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 28
Program: 17 Date:
Approach: Python program ask from the user to enter name of a file along with their extension to
open and read all the content present inside that file and display the content of the
same file on the output screen.
Output : Enter 'x' for exit.
Enter file name (with extension) to read: data.txt
The file, data.txt opened successfully!
The file data.txt contains:
my name is Deepak Bhinde
my blog is www.dbgyan.wordpress.com
I am a computer professional.
Task: Python program to read from the File.
Code :
# Python Program - Read a File
print("Enter 'x' for exit.");
#user input for file name.
filename = input("Enter file name (with extension) to read: ");
# if filename is 'x' then exit.
if filename == 'x':
exit();
else:
#opening a file for reading
c = open(filename, "r");
print("\nThe file,",filename,"opened successfully!");
print("The file",filename,"contains:\n");
#read the file
print(c.read())
#closing of file
c.close()
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 29
Program: 18 Date:
Approach: Enter name of the first and second file, and then ask a file name to create a file to place
the merged content of the two file into this newly created file.
To merge the content of first and second file and put all the merged content from first
and second file into the third file, then open the first and second file to read content of
both the file, and then finally store the merged content of both files into another third
file to successfully perform the merging of two files into another file
Task: Python program to merge Two Files.
Code :
# Python Program - Merge Two Files
#import shutil
import shutil;
print("Enter 'x' for exit.");
#user input for first file name.
filename1 = input("Enter first file name to merge: ");
# if filename is 'x' then exit.
if filename1 == 'x':
exit();
else:
#user input for second file name.
filename2 = input("Enter second file name to merge: ");
#user input for Create a new file to merge content.
filename3 = input("Create a new file to merge content of two file inside this file: ");
print();
print("Merging the content of two file in",filename3);
#open new file for merge
with open(filename3, "wb") as wfd:
for f in [filename1, filename2]:
with open(f, "rb") as fd:
shutil.copyfileobj(fd, wfd, 1024*1024*10);
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 30
Output :
Enter 'x' for exit.
Enter first file name to merge: data.txt
Enter second file name to merge: data1.txt
Create a new file to merge content of two file inside this file: merge.txt
Merging the content of two file in merge.txt
Content merged successfully.!
Want to see ? (y/n):
y
#merge.txt
my name is Deepak Bhinde
my blog is www.dbgyan.wordpress.com
I am a computer professional. Python is an interpreted, high-level, general-
purpose programming language.
Created by Guido van Rossum and first released in 1991.
print("\nContent merged successfully.!");
print("Want to see ? (y/n): ");
#user input for y/n
check = input();
if check == 'n':
exit();
else:
print();
c = open(filename3, "r");
print(c.read());
#closing file
c.close();
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 31
Program: 19 Date:
Approach:
Enter name of source and destination file to copy the content of source file into
destination file. After performing copy file operation, ask from the user, whether
he/she want to display the content of the destination file or not. If he/she want to show
the content, then just open the destination file and print all the content present inside
it which is the content of the source file.
Output :
Enter 'x' for exit.
Enter source file name (copy from): data.txt
Enter destination file name (copy to): new.txt
File copied successfully!
Want to display the content ? (y/n):
y
my name is Deepak Bhinde
my blog is www.dbgyan.wordpress.com
I am a computer professional.
Task :Python program to copy one file to another file.
Code :
# Python Program - Copy Files
from shutil import copyfile;
print("Enter 'x' for exit.");
sourcefile = input("Enter source file name (copy from): ");
if sourcefile == 'x':
exit();
else:
destinationfile = input("Enter destination file name (copy to): ");
copyfile(sourcefile, destinationfile);
print("File copied successfully!");
print("Want to display the content ? (y/n): ");
check = input();
if check == 'n':
exit();
else:
c = open(destinationfile, "r");
print(c.read());
c.close();
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 32
Program: 20 Date:
Approach:
To delete file in python, you have to import os library and use os.remove() function to
remove the desired file given by the user.
Output :
Enter 'x' for exit.
Enter name of file to delete: data1.txt
Removing the file....
File, data1.txt successfully deleted!!
Task:Python program to delete file.
Code :
# Python Program - Delete File
import os;
print("Enter 'x' for exit.");
filename = input("Enter name of file to delete: ");
if filename == 'x':
exit();
else:
print("\nRemoving the file....");
os.remove(filename);
print("\nFile,",filename,"successfully deleted!!");
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 33
Program: 21 Date:
Task :Python program to implement a stack.
Approach:
1. Create a class Stack with instance variable items initialized to an empty list.
2. Define methods push, pop and is_empty inside the class Stack.
3. The method push appends data to items.
4. The method pop pops the first element in items.
5. The method is_empty returns True only if items is empty.
6. Create an instance of Stack and present a menu to the user to perform operations
on the stack.
Code :
#Create a class Stack
class Stack:
def __init__(self):
self.items = []
# Method is_empty returns True only if items is empty
def is_empty(self):
return self.items == []
# Push method inserted elements items
def push(self, data):
self.items.append(data)
# Pop method returns popped/deleted elements from items
def pop(self):
return self.items.pop()
# show method returns showed/display elements of items.
def show(self):
return self.items
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 34
Output: push <value>
pop
show
quit
Enter choose your operation ? push 67
push <value>
pop
show
quit
Enter choose your operation ? push 89
push <value>
pop
show
quit
Enter choose your operation ? push 78
push <value>
pop
show
quit
Enter choose your operation ? pop
Enter choose your operation ? show
[67, 89]
push <value>
pop
show
quit
Enter choose your operation ? pop
Popped value: 89
push <value>
pop
show
quit
Enter choose your operation ? pop
Popped value: 67
push <value>
pop
show
quit
push <value>
# create
s = Stack()
while True:
print('push <value>')
print('pop')
print('show')
print('quit')
do = input('Enter choose your operation ? ').split()
operation = do[0].strip().lower()
if operation == 'push':
s.push(int(do[1]))
elif operation == 'pop':
if s.is_empty():
print('Stack is empty.')
else:
print('Popped value: ', s.pop())
elif operation == 'quit':
break
elif operation == 'show':
print(s.show())
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 35
Program: 22 Date:
Task: Python program to implement a Queue.
Approach:
1. Create a class Queue with instance variable items initialized to an empty list.
2. Define methods enqueue, dequeue and is_empty inside the class Queue.
3. The method enqueue appends data to items.
4. The method dequeue dequeues the first element in items.
5. The method is_empty returns True only if items is empty.
6. Create an instance of Queue and present a menu to the user to perform operations
on the queue.
Code :
# create a class as Queue
class Queue:
def __init__(self):
self.items = []
# define method is_empty for empty values.
def is_empty(self):
return self.items == []
# define method enqueue for enter value in queue
def enqueue(self, data):
self.items.append(data)
# define method enqueue for deleting value in queue
def dequeue(self):
return self.items.pop(0)
# define method show for display value
def show(self):
return self.items
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 36
Output: insert <value>
pop
show
quit
What would you like to do? insert 34
insert <value>
pop
show
quit
What would you like to do? insert 70
insert <value>
pop
show
quit
What would you like to do? insert 50
insert <value>
pop
show
quit
What would you like to do? show
[34, 70, 50]
insert <value>
pop
show
quit
What would you like to do? pop
poped value: 34
insert <value>
pop
show
quit
What would you like to do? show
[70, 50]
insert <value>
pop
show
quit
What would you like to do?
q = Queue()
while True:
print('insert <value>')
print('pop')
print('show')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
q.enqueue(int(do[1]))
elif operation == 'pop':
if q.is_empty():
print('Queue is empty.')
else:
print('poped value: ', q.dequeue())
elif operation == 'quit':
break
elif operation == 'show':
print(q.show())
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 37
Program: 23 Date:
Task: Compute EMIs for a loan using the numpy or scipy libraries.
.
Approach:
1. import the numpy and scipy libararies.
2. Take the input from interest , years and loan_value .
3. calculate monthly_rate , number_month and monthly_payment.
4. print the output.
Code :
# import numpy pakage
import numpy as np
# take the user input as rate of interest
interest = float(input("enter rate of Interest ->"))
annual_rate = interest/100.0
monthly_rate = annual_rate/12
# take the user input as years
years = float(input("enter the years:"))
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 38
Output:
enter rate of Interest ->8.3
enter the years:25
enter Loan Amount Rs:3840000
Paying off a loan of Rs3,840,000.0 over 25.0 years at
8.3% interest, your monthly payment will be Rs.30,404.90
number_month = years * 12
# take the user input as loan amount
loan_value = float(input("enter Loan Amount Rs:"))
# calculate monthly payment
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 the output
print(sf1.format(loan_value, years))
print(sf2.format(interest, monthly_payment))
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 39
Program: 24 Date:
Task: Create a graphical application that accepts user inputs , performs some
operation on them and the writes the output on the screen . for example , write
small calculator. Use the tkinter library.
Approach:
1. Importing the module – tkinter 2. Create the main window (container) 3. Add any number of widgets to the main window 4. Apply the event Trigger on the widgets
Code :
# import everything from tkinter module
from tkinter import *
# globally declare the expression variable
expression = ""
# Function to update expressiom in the text entry box
def press(num):
# point out the global expression variable global expression
# concatenation of string
expression = expression + str(num)
# update the expression by using set method
equation.set(expression)
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 40
# Function to evaluate the final expression
def equalpress():
# Try and except statement is used for handling the errors like zero division error
# etc. Put that code inside the try block which may generate the error
try:
global expression
# eval function evaluate the expression and str function convert the result
# into string
total = str(eval(expression))
equation.set(total)
# initialze the expression variable by empty string
expression = ""
# if error is generate then handle by the except block
except:
equation.set(" error ")
expression = ""
# Function to clear the contents of text entry box
def clear():
global expression
expression = ""
equation.set("")
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 41
# Driver code
if __name__ == "__main__":
# create a GUI window
gui = Tk()
# set the background colour of GUI window
gui.configure(background="light green")
# set the title of GUI window
gui.title("Simple Calculator")
# set the configuration of GUI window
gui.geometry("265x125")
# StringVar() is the variable class we create an instance of this class
equation = StringVar()
# create the text entry box for showing the expression .
expression_field = Entry(gui, textvariable=equation)
# grid method is used for placing the widgets at respective positions
# in table like structure .
expression_field.grid(columnspan=4, ipadx=70)
equation.set('enter your expression')
# create a Buttons and place at a particular
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 42
# location inside the root window .
# when user press the button, the command or
# function affiliated to that button is executed .
button1 = Button(gui, text=' 1 ', fg='black', bg='red',
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=0)
button2 = Button(gui, text=' 2 ', fg='black', bg='red',
command=lambda: press(2), height=1, width=7)
button2.grid(row=2, column=1)
button3 = Button(gui, text=' 3 ', fg='black', bg='red',
command=lambda: press(3), height=1, width=7)
button3.grid(row=2, column=2)
button4 = Button(gui, text=' 4 ', fg='black', bg='red',
command=lambda: press(4), height=1, width=7)
button4.grid(row=3, column=0)
button5 = Button(gui, text=' 5 ', fg='black', bg='red',
command=lambda: press(5), height=1, width=7)
button5.grid(row=3, column=1)
button6 = Button(gui, text=' 6 ', fg='black', bg='red',
command=lambda: press(6), height=1, width=7)
button6.grid(row=3, column=2)
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 43
button7 = Button(gui, text=' 7 ', fg='black', bg='red',
command=lambda: press(7), height=1, width=7)
button7.grid(row=4, column=0)
button8 = Button(gui, text=' 8 ', fg='black', bg='red',
command=lambda: press(8), height=1, width=7)
button8.grid(row=4, column=1)
button9 = Button(gui, text=' 9 ', fg='black', bg='red',
command=lambda: press(9), height=1, width=7)
button9.grid(row=4, column=2)
button0 = Button(gui, text=' 0 ', fg='black', bg='red',
command=lambda: press(0), height=1, width=7)
button0.grid(row=5, column=0)
plus = Button(gui, text=' + ', fg='black', bg='red',
command=lambda: press("+"), height=1, width=7)
plus.grid(row=2, column=3)
minus = Button(gui, text=' - ', fg='black', bg='red',
command=lambda: press("-"), height=1, width=7)
minus.grid(row=3, column=3)
multiply = Button(gui, text=' * ', fg='black', bg='red',
command=lambda: press("*"), height=1, width=7)
multiply.grid(row=4, column=3)
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 44
divide = Button(gui, text=' / ', fg='black', bg='red',
command=lambda: 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=2)
clear = Button(gui, text='Clear', fg='black', bg='red',
command=clear, height=1, width=7)
clear.grid(row=5, column='1')
# start the GUI
gui.mainloop()
Output:
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 45
Approach :
1. importing the required module
2. define x and y axies values
3. plotting points corresponding x and y axies
4. define the label of x and y axies
5. display the graph
Program: 25 Date:
Task : Program to implement to plot function y=X^2 using pyplot or matplotlib
libraries.
Code :
# importing the required module
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]
# plotting the points
plt.plot(x, y)
# naming the x axis
DEEPAK BHINDE PGT COMPUTER SCIENCE PYTHON PROGRAMS 1.2 PAGE 46
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('Function y=X^2')
# function to show the plot
plt.show()
Output :