1.
Program to exchange the values of two variables
Program:
x=input('Enter the value of x:')
y=input('Enter the value of y:')
print('The values before swap')
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
temp=x
x=y
y=temp
print('The values after swap')
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Output
2. Program to circulate the value of n.
Program:
n = int(input("Enter number of values : "))
list1 = []
for val in range(0,n,1):
ele = int(input("Enter integer : "))
list1.append(ele)
print("Circulating the elements of list ", list1)
for val in range(0,n,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)
Output:
3. Program to find distance between two points.
Program:
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)
Output:
4. Program using conditionals.
Program:
a=int(input("Enter value of a:"))
b=int(input("Enter value of b:"))
c=int(input("Enter value of c:"))
if (a>= b) and (a >= c):
largest = a
elif (b>= a) and (b>= c):
largest = b
else:
largest = c
print("The largest number is", largest)
Output:
5. Program using loops.
Program:
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)
Output:
6. Program for Linear search.
Program:
def linear_Search(list1, n, key):
for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 4, 7, 9]
print("The list is:",list1)
key =input("Enter element to be searched:")
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Output
7. Program for Binary Search.
Program:
def binary_search(list1, n):
low = 0
high = len(list1) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if list1[mid] < n:
low = mid + 1
elif list1[mid] > n:
high = mid - 1
else:
return mid
return -1
list1 = [12, 24, 32, 39, 45, 50, 54]
print("The list is :",list1)
n=input("Enter element to be searched:")
result = binary_search(list1, n)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in list1")
Output:
8. Program for selection sort.
Program:
def selection_sort(array):
length = len(array)
for i in range(length-1):
minIndex = i
for j in range(i+1, length):
if array[j]<array[minIndex]:
minIndex = j
array[i], array[minIndex] = array[minIndex], array[i]
return array
array = [21,6,9,33,3]
print("The sorted array is: ", selection_sort(array))
Output:
9. Program for insertion sort.
Program:
def insertion_sort(list1):
for i in range(1, len(list1)):
value = list1[i]
j=i-1
while j >= 0 and value < list1[j]:
list1[j + 1] = list1[j]
j -= 1
list1[j + 1] = value
return list1
# Driver code to test above
list1 = [10, 5, 13, 8, 2]
print("The unsorted list is:", list1)
print("The sorted list1 is:", insertion_sort(list1))
Output:
10.Program for merge sort.
Program:
def merge_sort(list1, left_index, right_index):
if left_index >= right_index:
return
middle = (left_index + right_index)//2
merge_sort(list1, left_index, middle)
merge_sort(list1, middle + 1, right_index)
merge(list1, left_index, right_index, middle)
def merge(list1, left_index, right_index, middle):
left_sublist = list1[left_index:middle + 1]
right_sublist = list1[middle+1:right_index+1]
left_sublist_index = 0
right_sublist_index = 0
sorted_index = left_index
while left_sublist_index < len(left_sublist) and right_sublist_index <
len(right_sublist):
if left_sublist[left_sublist_index] <= right_sublist[right_sublist_index]:
list1[sorted_index] = left_sublist[left_sublist_index]
left_sublist_index = left_sublist_index + 1
else:
list1[sorted_index] = right_sublist[right_sublist_index]
right_sublist_index = right_sublist_index + 1
sorted_index = sorted_index + 1
while left_sublist_index < len(left_sublist):
list1[sorted_index] = left_sublist[left_sublist_index]
left_sublist_index = left_sublist_index + 1
sorted_index = sorted_index + 1
while right_sublist_index < len(right_sublist):
list1[sorted_index] = right_sublist[right_sublist_index]
right_sublist_index = right_sublist_index + 1
sorted_index = sorted_index + 1
list1 = [44, 65, 2, 3, 58, 14, 57, 23, 10, 1, 7, 74, 48]
print("The list is:",list1)
merge_sort(list1, 0, len(list1) -1)
print(list1)
Output:
11.Program for Quick search .
Program:
def partition(array, low, high):
pivot = array[high]
i = low – 1
for j in range(low, high):
if array[j] <= pivot:
i=i+1
(array[i], array[j]) = (array[j], array[i])
(array[i + 1], array[high]) = (array[high], array[i + 1])
return i + 1
def quickSort(array, low, high):
if low < high:
pi = partition(array, low, high)
quickSort(array, low, pi - 1)
quickSort(array, pi + 1, high)
data = [8, 7, 2, 1, 0, 9, 6]
print("Unsorted Array")
print(data)
size = len(data)
quickSort(data, 0, size - 1)
print('Sorted Array in Ascending Order:')
print(data)
Output:
12 . Program for list
L1=[10,30,50,20,40]
T1=(10,50,30,40,20)
print (len(L1))
print (len(T1))
print ('max of L1', max(L1))
print ('max of T1', max(T1))
print ('min of L1', min(L1))
print ('min of T1', min(T1))
print ('sum of L1', sum(L1))
print ('sum of T1', sum(T1))
print ('L1 in sorted order', sorted(L1))
print ('T1 in sorted order', sorted(T1))
output :
12.Set
//*Creating a list
a = set([1, 2, 3, 8, 4, 2])
print a
output:
set([8, 1, 2, 3, 4])
//*Adding a element
s = {1,2}
s.add(3)
print(s)
output :
set([1, 2, 3])
//* Updating a set
s = {1,2,3}
s.update([3,4,5,6])
print(s)
output :
set([1, 2, 3, 4, 5, 6])
//*Removing a element
s = {1,2,3,4,5}
s.remove(5)
print(s)
# discard function
s = {1,2,3,4,5}
s.discard(5)
print(s)
# pop function
s = {1,2,3,4,5}
s.pop()
print(s)
output :
set([1, 2, 3, 4])
set([1, 2, 3, 4])
set([2, 3, 4, 5])
//*Set union
s1 = {1,2,3}
s2 = {3,4,5}
su1 = s1 | s2
su2 = s1.union(s2)
print(su1)
print(su2)
output :
set([1, 2, 3, 4, 5])
set([1, 2, 3, 4, 5])
Set intersection
s1 = {1,2,3}
s2 = {3,4,5}
si1 = s1 & s2
si2 = s1.intersection(s2)
print(si1)
print(si2)
output :
set([3])
set([3])
Set Difference
s1 = {1,2,3}
s2 = {3,4,5}
sd1 = s1 - s2
sd2 = s1.difference(s2)
print(sd1)
print(sd2)
output :
set([1, 2])
set([1, 2])
Symmetric Differences
s1 = {1,2,3}
s2 = {3,4,5}
ssd1 = s1 ^ s2
ssd2 = s1.symmetric_difference(s2)
print(ssd1)
print(ssd2)
output
set([1, 2, 4, 5])
set([1, 2, 4, 5])
B. IMPLEMENTING APPLICATION USING DICTIONARIES
Creating a Dictionary
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'PYTHON PROGRAMMING', 2: 'For', 3: 'PYTHON PROGRAMMING'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'BOOKS', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
output :
Dictionary with the use of Integer Keys:
{1: 'PYTHON PROGRAMMING', 2: 'For', 3: 'PYTHON PROGRAMMING'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'BOOKS'}
Creating an Empty Dictionary
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'PYTHON PROGRAMMING', 2: 'For', 3: 'PYTHON
PROGRAMMING'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'PYTHON PROGRAMMING'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
output
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'PYTHON PROGRAMMING', 2: 'For', 3: 'PYTHON PROGRAMMING'}
Dictionary with each item as a pair:
{1: 'PYTHON PROGRAMMING', 2: 'For'}
Nested Dictionary
# Creating a Nested Dictionary
Dict = {1: 'HELLO', 2: 'For',
3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'PYTHON PROGRAMMING'}}
print(Dict)
output :
{1: 'HELLO', 2: 'For', 3: {'A': 'Welcome', 'C': 'PYTHON PROGRAMMING', 'B':
'To'}}
Adding element
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'Python Programming'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Books'}}
print("\nAdding a Nested Key: ")
print(Dict)
output
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Python Programming', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'Python Programming', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Python Programming', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Python Programming', 2: 'Welcome', 3: 1, 5: {'Nested': {'1': 'Life', '2':
'Books'}}, 'Value_set': (2, 3, 4)}
Accessing Elements of a string
# Python program to demonstrate
# accessing a element from a Dictionary
# Creating a Dictionary
Dict = {1: 'Books', 'name': 'For', 3: 'Python Programming'}
# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])
# accessing a element using key
print("Accessing a element using key:")
print(Dict[1])
output
Accessing a element using key:
For
Accessing a element using key:
Books
Removing a key
# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Python Programming',
'A' : {1 : 'Software Engineering', 2 : 'For', 3 : 'Java Programming'},
'B' : {1 : 'Mobile Computing', 2 : '.NET Technology'}}
print("Initial Dictionary: ")
print(Dict)
# Deleting a Key value
del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)
# Deleting a Key from
# Nested Dictionary
del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)
output
Initial Dictionary:
{'A': {1: 'Software Engineering', 2: 'For', 3: 'Java Programming'}, 'B': {1:
'Mobile Computing', 2: '.NET Technology'}, 5: 'Welcome', 6: 'To', 7: 'Python
Programming'}
Deleting a specific key:
{'A': {1: 'Software Engineering', 2: 'For', 3: 'Java Programming'}, 'B': {1:
'Mobile Computing', 2: '.NET Technology'}, 5: 'Welcome', 7: 'Python
Programming'}
Deleting a key from Nested Dictionary:
{'A': {1: 'Software Engineering', 3: 'Java Programming'}, 'B': {1: 'Mobile
Computing', 2: '.NET Technology'}, 5: 'Welcome', 7: 'Python Programming'}
IMPLEMENTING PROGRAMS USING WRITTEN MODULES AND PYTHON
STANDARD LIBRARIES (pandas, numpy, Matplotlib, scipy)
Pandas
# Import pandas package
import pandas as pd
# Define a dictionary containing employee data
data = {'Name':['vijay ', 'Surya ', 'Ajith ', 'Siva'],
'Age':[27, 24, 22, 32],
'Address':['Thenkasi', 'Thirunelveli', 'chennai', 'Coambatore'],
'Qualification':['MCA', 'MA', 'Msc', 'Phd']}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# converting and overwriting values in column
df["Name"]= df["Name"].str.lower()
print(df)
output
Name Age Address Qualification
0 vijay 27 Thenkasi MCA
1 surya 24 Thirunelveli MA
2 ajith 22 Chennai Msc
3 siva 32 Coambatore Phd
Numpy
# Python program for
# Creation of Arrays
import numpy as np
# Creating a rank 1 Array
arr = np.array([1, 2, 3])
print("Array with Rank 1: \n",arr)
# Creating a rank 2 Array
arr = np.array([[1, 2, 3],
[4, 5, 6]])
print("Array with Rank 2: \n", arr)
# Creating an array from tuple
arr = np.array((1, 3, 2))
print("\nArray created using "
"passed tuple:\n", arr)
Output :
Array with Rank 1:
[1 2 3]
Array with Rank 2:
[[1 2 3]
[4 5 6]]
Array created using passed tuple:
[1 3 2]
Python plotting with Matplotlib
# Python program to show pyplot module
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.axis([0, 6, 0, 20])
plt.show()
output :
Python program to show pyplot module
# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
# Creating a new figure with width = 5 inches
# and height = 4 inches
fig = plt.figure(figsize =(5, 4))
# Creating a new axes for the figure
ax = fig.add_axes([1, 1, 1, 1])
# Adding the data to be plotted
ax.plot([2, 3, 4, 5, 5, 6, 6], [5, 7, 1, 3, 4, 6 ,8])
plt.show()
Output
IMPLEMENTING FILE HANDLING USING PYTHON
PROGRAM
Opening a File: It is done using the open() function. No
module is required to be imported for this function.
Syntax:
File_object = open(r"File_Name", "Access_Mode")
//Opening a File
# Open function to open the file "MyFile1.txt"
# (same directory) in read mode and
file1 = open("MyFile.txt", "w")
# store its reference in the variable file1
# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt", "w+")
Here, file1 is created as object for MyFile1 and file2 as object
for MyFile2.
Closing a file : close() function closes the file and frees the
memory space acquired by that file. It is used at the time when the
file is no longer needed or if it is to be opened in a different file
mode.
Syntax:
File_object.close()
# Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt", "w")
file1.close()
//Writing to file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
2. writelines() : For a list of string elements, each string is inserted in the
text file. Used to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
# Python program to demonstrate
# writing to file
# Opening a file
file1 = open('myfile.txt', 'w')
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
s = "Hello\n"
# Writing a string to file
file1.write(s)
# Writing multiple strings
# at a time
file1.writelines(L)
# Closing file
file1.close()
# Checking if the data is
# written to file or not
file1 = open('myfile.txt', 'r')
print(file1.read())
file1.close()
OUTPUT
Hello
This is Delhi
This is Paris
This is London
Appending to a file
When the file is opened in append mode, the handle is positioned at
the end of the file. The data being written will be inserted at the end, after
the
existing data. Let’s see the below example to clarify the difference between
write mode and append mode.
# Python program to illustrate
# Append vs write mode
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
file1.writelines(L)
file1.close()
# Append-adds at last
file1 = open("myfile.txt", "a") # append mode
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt", "r")
print("Output of Readlines after appending")
print(file1.read())
print()
file1.close()
# Write-Overwrites
file1 = open("myfile.txt", "w") # write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt", "r")
print("Output of Readlines after writing")
print(file1.read())
print()
file1.close()
OUTPUT
Output of Readlines after appending
This is Delhi
This is Paris
This is London
Today
Output of Readlines after writing
Tomorrow
PROGRAM
# Single quotes
str1 = 'Hi, NARAYANAGURU COLLEGE OF ENGINEERING'
print(str1)
# Double quotes
str1 = "Hi, DEPARTMENT OF MCA"
print(str1)
# Single quotes within double, no need to escape them or match them
str1 = "Hello , HOW ARE YOU ALL? "
# Double quotes within single, no need to escape them or match them
str1 = 'Hello, HOW ARE YOU "ALL"?'
str2 = 'Hello, "HOPE ALL ARE FINE?'
print(str1)
print(str2)
# triple quotes are multiline strings
str1 = '''Hello, welcome to
NARAYANAGURU COLLEGE OF ENGINEERING'''
print(str1)
str1 = """Hello, welcome to
DEPARTMENT OF MCA"""
print(str1)
OUTPUT:
Implementing programs using Functions.
AIM
ALGORITHM
PROGRAM
// Python Function Programs
To implement python functions there can be many useful function programs
in python. A list of top two python function programs are given below:
// Fibonacci sequence
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
# take input from the user
nterms = int(input("How many terms? "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
OUTPUT
//Display Calendar
# First import the calendar module
import calendar
# ask of month and year
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy,mm))
OUTPUT
Implementing Exception Handling Using Python
//Syntax error
# initialize the amount variable
amount = 10000
# check that You are eligible to
# purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced"
output :
File "<ipython-input-1-0e3b5d10b520>", line 6
if(amount > 2999)
^
SyntaxError: invalid syntax
//ZeroDiviserError
# initialize the amount variable
marks = 10000
# perform division with 0
a = marks / 0
print(a)
output :
ZeroDivisionError Traceback (most recent call last)
<ipython-input-2-757d9509a65c> in <module>
3
4 # perform division with 0
----> 5 a = marks / 0
6 print(a)
ZeroDivisionError: division by zero
//Try and Except Statement
# Python program to handle simple runtime error
#Python 3
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred
Output :
Second element = 2
An error occurred
//Catching Specific Exception
# Program to handle multiple errors with one
# except statement
# Python 3
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)
# note that braces () are necessary here for
# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
output :
ZeroDivisionError Occurred and Handled
//finally Keyword
# Python program to demonstrate finally
# No exception Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Output
Can't divide by zero
This is always executed