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

PYTHON

The document contains several Python programs demonstrating different concepts like arithmetic operations, conditional statements, functions, loops, strings, lists, tuples, dictionaries, sets, files handling, exceptions, NumPy and Pandas modules. The programs cover basic to advanced Python programming concepts.

Uploaded by

Vijay Anand.V
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)
33 views

PYTHON

The document contains several Python programs demonstrating different concepts like arithmetic operations, conditional statements, functions, loops, strings, lists, tuples, dictionaries, sets, files handling, exceptions, NumPy and Pandas modules. The programs cover basic to advanced Python programming concepts.

Uploaded by

Vijay Anand.V
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/ 39

Program To Compute Distance Between Two Points Taking Input From

The User

Program:
import math
a=int(input("enter a value:"))
b=int(input("enter b value:"))
c=int(input("enter c value:"))
d=int(input("enter d value:"))
distance = math.sqrt(((a-c)**2)+((b-d)**2))
print(" distance =",distance)

Output:

Result:

Register Number: 211423247______ Page |


Program To Perform Arithmetic Operations

Program:
num1=float(input("please enter the first number 1:"))
num2=float(input("please enter the second number 2:"))
add=num1+num2
sub=num1-num2
multi=num1*num2
div=num1/num2
mod=num1%num2
expo=num1**num2
print(" sum=",add)
print("difference=",sub)
print("product=",multi)
print("quotient=",div)
print(" remainder=",mod)
print("exponential value=",expo)

Output:

Result:

Register Number: 211423247______ Page |


Program To Demonstarte Different Number Datatypes In Python

Program:
#numbers
x=20
print(x)
print(type(x))
x=20.5
print(x)
print(type(x))
x=1j
print(x)
print(type(x))
#string
x="GoEduHub.com"
print(x)
print(type(x))
#list
x=["Go","Edu","Hub"]
print(x)
print(type(x))
#tuple
x=("Python","from","GoEduHub.com")
print(x)
print(type(x))
#boolean
x= True
print(x)
print(type(x))
x=b"Hello"
print(x)
print(type(x))
Output:

Result:

Register Number: 211423247______ Page |


Develop A Python Program To Demonstrate Various Conditional
Statements
Program:
#number is even or not
a=int(input())
if(a%2==0):
print("even")
else:
print("odd")

#finding the factorial of a number


a=int(input())
k=1
for i in range(1,a+1):
k=k*i
print("the factorial is",k)

#printing all prime numbers between an interval


lower=int(input("enter lower range"))
upper=int(input("enter upper range"))
for num in range(lower,upper+1):
if num>1:
for i in range(2,num):
if(num%i)==0:
break
else:
print(num)

Output:

Result:

Register Number: 211423247______ Page |


Implement User Defined Functions Using Python
Program:
def plus(a,b):
sum=a+b
return(sum,a)
sum,a=plus(3,4)
print("the sum is",sum)

Output:

Result:

Register Number: 211423247______ Page |


Develop A Python Script To Demonstrate Range() Function

Program:

for i in range(10):
print(i,end="")
print()
l=[10,20,30,40]
for i in range(len(l)):
print(l[i],end="")
print()
sum=0
for i in range(1,11):
sum=sum+i
print("sum of first 10 natural numbers:",sum)

Output:

Result:

Register Number: 211423247______ Page |


Program To Perform Various String Operations Like Slicing, Indexing &
Formatting
Program:
str="panimalar engineering college"
print("op of string slicing:")
print(str[3:18])
print(str[2:14:2])
print(str[ :8])
print(str[8:-1:1])
print(str[-9:-15])
print(str[0:9:3])
print(str[9: 29:2])
print(str[-6:-9:-3])
print(str[-9:-9:-1])
print(str[8:25:3])
def remove_char(str,n):
first=str[:n]
last=str[n+1:]
return first+last
print("output of string indexing")
print(remove_char('python',0))
print(remove_char('python',3))
print(remove_char('python',5))
txt1="my name is {fname},I'm {age}".format(fname="john",age=36)
txt2="my name is {0},I'm {1}".format("john",36)
txt3="my name is {},I'm {}".format("john",36)
print(txt1)
print(txt2)
print(txt3)

Output:

Result:

Register Number: 211423247______ Page |


Develop Python Program To Perform Operation On List & Tuple

Program:
list=[10,30,50,20,40]
tuple=(10,50,30,40,20)
print("length of list:",len(list))
print("length of tuple:",len(tuple))
print(" max of list:",max(list))
print( "max of tuple:",max(tuple))
print("min of list",min(list))
print("min of tuple",min(tuple))
print("sum of list",sum(list))
print("sum of tuple",sum(tuple))
print("list in sorted order",sorted(list))
print("tuple in sorted order",sorted(tuple))

Output:

Result:

Register Number: 211423247______ Page |


Demonstrate The Concept Of Dictionary With Python Program

Program:
dict1={1:"India",2:"USA",3:"UK",4:"Canada"}
print(dict1)
print(dict1.keys())
print(dict1.values())
print(dict1.items())

Output:

Result:

Register Number: 211423247______ Page |


Demonstrate The Concept of Set With Python Program

Program:
A={31,22,23,15,17,19,7}
B={2,4,6,7,9,0}
print('union:',A|B)
print('difference:',A-B)
print('intersection:',A&B)
print('symmetric difference:',A^B)

Output:

Result:

Register Number: 211423247______ Page |


Develop Python Codes To Perform Matrix Addition And Subtraction
Program:
matrix1=[[1,2],[3,4]]
matrix2=[[4,5],[6,7]]
print("printing elements of first matrix:")
for row in matrix1:
for element in row:
print(element,end="")
print()
print("printing elements of second matrix:")
for row in matrix2:
for element in row:
print(element,end="")
print()
result1=[[0,0],[0,0]]
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
result1[i][j]= matrix1[i][j]+matrix2[i][j]
result=[[0,0],[0,0]]
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
result[i][j]= matrix1[i][j]-matrix2[i][j]
print("subtraction of two matrix")
for row in result:
for element in row:
print(element,end="")
print()
print("addition of two matrix")
for row in result1:
for element in row:
print(element,end="")
print()
Output:

Result:

Register Number: 211423247______ Page |


Develop A Python Codes To Perform Matrix Transpose

Program:
matrix1=[[1,2],[3,4]]
print("printing elements of first matrix:")
for row in matrix1:
for element in row:
print(element,end="")
print()
result=[[0,0],[0,0]]
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
result[i][j]= matrix1[j][i]
print("transpose of matrix")
for row in result:
for element in row:
print(element,end="")
print()

Output:

Result:

Register Number: 211423247______ Page |


Develop Python Codes To Demonstrate The Concept Of Function
Composition And Anonymous Functions

Program:
def composite_function(f,g):
return lambda x:f(g(x))
def add(x):
return x+2
def multiply(x):
return x*2
add_multiply=composite_function(multiply,add)
print("result:",add_multiply(5))

Output:

Result:

Register Number: 211423247______ Page |


Demonstrate A Python Codes To Print Try, Except And Finally Block
Statements

Program:
try:
num1,num2= eval(input("enter 2 numbers,seperated by a comma:"))
result = num1/num2
print("result is",result)
except ZeroDivisionError:
print("division by zero is error!!")
except SyntaxError:
print(" comma is missing. Enter numbers seperated by comma like this 1,2")
except:
print("wrong input")
else:
print("no exceptions")
finally:
print("this will execute no matter what")

Output:

Result:

Register Number: 211423247______ Page |


Implement Python Program To Perform File Operations

Program:
my_file=open("D:\\file1.txt","x")
print("file created successfully")
with open("file1.text",'w',encoding='utf-8')as f:
f.write(" my first file\n")
f.write(" this file\n")
f.write(" contains 3 lines\n")
print("Successfully inserted")
my_file=open("D:\\file1.txt","r")
print(my_file.read())
my_file=open("D:\\file1.txt","r")
print("Readline:")
print(my_file.readline(10))
with open("file1.txt",'a',encoding='utf-8') as f:
f.write("jaisakthi\n")
print("successfully appended")

Output:

Result:

Register Number: 211423247______ Page |


Program To Handle And Raises A Value Error Exception If The Input Is
Not A Valid Integer
Program:
def get_integer_input(prompt):
try:
value=int(input(prompt))
return value
except ValueError:
print("error:invalidinput,input an integer")
n=get_integer_input("input an integer:")
print("input value:",n)

Output:

Register Number: 211423247______ Page |


Program To Handle And Raise A File Not Found Error Exception If The
File Does Not Exist

Program:
def open_file(filename):
try:
file=open(filename,'r')
contents=file.read()
print("file contents:")
print(contents)
file.close()
except FileNotFoundError:
print("error:file not found")
file_name=input("input a file name:")
open_file(file_name)

Output:

Register Number: 211423247______ Page |


Program To Handles And Raise A Type Error Exception If The Input Are
Not Numerical

Program:
def get_numeric_input(prompt):
while True:
try:
value=float(input())
return value
except ValueError:
print("error:invalidinput,please input a valid number")
n1=get_numeric_input("input first num:")
n2=get_numeric_input("input second num:")
result=n1+n2
print("product of the said two numbers:",result)

Output:

Register Number: 211423247______ Page |


Program To Handles An Index Error Except If The Index Is Out Of Range

Program:
def testindex(data,index):
try:
result=data[index]
print("result:",result)
except IndexError:
print("error:index out of range")
nums=[1,2,3,4,5,6,7]
index=int(input("input the index:"))
testindex(nums,index)

Output:

Result:

Register Number: 211423247______ Page |


Develop A Python Programs Using Packages Numpy And Pandas

Program:
import numpy as np
import pandas as pd
numpyArray=np.array([[5,22,3],[13,24,6]])
columns=[['x','y','z']
panda_df=pd.DataFrame(data=numpyArray,index=["A","B"],columns=columns)
print(panda_df)

Output:

Result:

Register Number: 211423247______ Page |


Develop Python Programs Using Tkinter

Program:
import tkinter as tk
master=tk.Tk()
master.title("MARKSHEET")
master.geometry("700x250")
e1=tk.Entry(master)
e2=tk.Entry(master)
e3=tk.Entry(master)
e4=tk.Entry(master)
e5=tk.Entry(master)
e6=tk.Entry(master)
e7=tk.Entry(master)
def display():
tot=0
if e4.get()=="A":
tk.Label(master,text="40").grid(row=3,column=4)
tot+=40
if e4.get()=="B":
tk.Label(master,text="36").grid(row=3,column=4)
tot+=36
if e4.get()=="C":
tk.Label(master,text="32").grid(row=3,column=4)
tot+=32
if e4.get()=="D":
tk.Label(master,text="28").grid(row=3,column=4)
tot+=28
if e4.get()=="P":
tk.Label(master,text="24").grid(row=3,column=4)
tot+=24
if e4.get()=="F":
tk.Label(master,text="0").grid(row=3,column=4)
tot+=0
if e5.get()=="A":
tk.Label(master,text="40").grid(row=4,column=4)
tot+=40
if e5.get()=="B":
tk.Label(master,text="36").grid(row=4,column=4)
tot+=36
if e5.get()=="C":
tk.Label(master,text="32").grid(row=4,column=4)
tot+=32
if e5.get()=="D":
tk.Label(master,text="28").grid(row=4,column=4)

Register Number: 211423247______ Page |


tot+=28
if e5.get()=="P":
tk.Label(master,text="24").grid(row=4,column=4)
tot+=24
if e5.get()=="F":
tk.Label(master,text="0").grid(row=4,column=4)
tot+=0
if e6.get()=="A":
tk.Label(master,text="40").grid(row=3,column=4)
tot+=40
if e6.get()=="B":
tk.Label(master,text="36").grid(row=4,column=4)
tot+=36
if e6.get()=="C":
tk.Label(master,text="32").grid(row=4,column=4)
tot+=32
if e6.get()=="D":
tk.Label(master,text="28").grid(row=4,column=4)
tot+=28
if e6.get()=="P":
tk.Label(master,text="24").grid(row=4,column=4)
tot+=24
if e6.get()=="F":
tk.Label(master,text="0").grid(row=4,column=4)
tot+=0
if e7.get()=="A":
tk.Label(master,text="40").grid(row=4,column=4)
tot+=40
if e7.get()=="B":
tk.Label(master,text="36").grid(row=4,column=4)
tot+=36
if e7.get()=="C":
tk.Label(master,text="32").grid(row=4,column=4)
tot+=32
if e7.get()=="D":
tk.Label(master,text="28").grid(row=4,column=4)
tot+=28
if e7.get()=="P":
tk.Label(master,text="24").grid(row=4,column=4)
tot+=24
if e7.get()=="F":
tk.Label(master,text="0").grid(row=4,column=4)
tot+=0
tk.Label(master,text="name").grid(row=0,column=0)
tk.Label(master,text="reg.no").grid(row=0,column=3)

Register Number: 211423247______ Page |


tk.Label(master,text="rollno").grid(row=1,column=0)
tk.Label(master,text="srlno").grid(row=2,column=0)
tk.Label(master,text="1").grid(row=3,column=0)
tk.Label(master,text="2").grid(row=4,column=0)
tk.Label(master,text="3").grid(row=5,column=0)
tk.Label(master,text="4").grid(row=6,column=0)
tk.Label(master,text="subject").grid(row=2,column=1)
tk.Label(master,text="PYTHON").grid(row=3,column=1)
tk.Label(master,text="JAVA").grid(row=4,column=1)
tk.Label(master,text="HTML").grid(row=5,column=1)
tk.Label(master,text="OOPS").grid(row=6,column=1)
tk.Label(master,text="Grade").grid(row=2,column=2)
e4.grid(row=3,column=2)
e5.grid(row=4,column=2)
e6.grid(row=5,column=2)
e7.grid(row=6,column=2)
tk.Label(master,text="Sub credit").grid(row=2,column=3)
tk.Label(master,text="4").grid(row=3,column=3)
tk.Label(master,text="4").grid(row=4,column=3)
tk.Label(master,text="3").grid(row=5,column=3)
tk.Label(master,text="4").grid(row=6,column=3)
tk.Label(master,text=" credit obtained").grid(row=2,column=4)
e1=tk.Entry(master)
e2=tk.Entry(master)
e3=tk.Entry(master)
e2.grid(row=0,column=4)
e3.grid(row=1,column=1)
button1=tk.Button(master,text="submit",bg="green",command=display)
button1.grid(row=8,column=1)
tk.Label(master,text="total credit").grid(row=7,column=3)
tk.Label(master,text="SGPA").grid(row=8,column=3)
master.mainloop()
OUTPUT:

Register Number: 211423247______ Page |


Result:

Register Number: 211423247______ Page |


ADDITIONAL PROGRAMS

Python Program to check if a Number is Odd or Even

Program:

num = int(input("Enter any number to test whether it is odd or even:"))

if (num % 2) == 0:

print ("The number is even")

else:

print ("The provided number is odd")

Output:

Result:
:

Register Number: 211423247______ Page |


Python Program to check if a Number is Positive, Negative or 0

Program:
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Output:

Result:

Register Number: 211423247______ Page |


Python Program to Find the Factorial of a Number

Program:

def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 7
result = factorial(num)
print("The factorial of", num, "is", result)

Output:

Result:

Register Number: 211423247______ Page |


Python Program To Solve Quadratic Equation
Program:
# import complex math module
import cmath
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))

# calculate the discriminant


d = (b**2) - (4*a*c)

# find two solutions


sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))

Output:

Result:

Register Number: 211423247______ Page |


Python Program To Guess An Integer Number In Range

Program:
import random
num = random.randint(1, 10)
guess = None
while guess != num:
guess = input("guess a number between 1 and 10: ")
guess = int(guess)
if guess == num:
print("congratulations! you won!")
break
else:
print("nope, sorry. try again!")

Output:

Result:

Register Number: 211423247______ Page |


Python Program To Display Calendar

Program:

import calendar
# Enter the month and year
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy,mm))

Output:

Result:

Register Number: 211423247______ Page |


Python Program To Check Prime Number
Program:
def PrimeChecker(a):
if a > 1:
for j in range(2, int(a/2) + 1):
if (a % j) == 0:
print(a, "is not a prime number")
break
else:
print(a, "is a prime number")
else:
print(a, "is not a prime number")
a = int(input("Enter an input number:"))
PrimeChecker(a)

Output:

Result:

Register Number: 211423247______ Page |


Python Program To Print Calculator
Program:
def add(P, Q):
# This function is used for adding two numbers
return P + Q
def subtract(P, Q):
# This function is used for subtracting two numbers
return P - Q
def multiply(P, Q):
# This function is used for multiplying two numbers
return P * Q
def divide(P, Q):
# This function is used for dividing two numbers
return P / Q
# Now we will take inputs from the user
print ("Please select the operation.")
print ("a. Add")
print ("b. Subtract")
print ("c. Multiply")
print ("d. Divide")
choice = input("Please enter choice (a/ b/ c/ d): ")
num_1 = int (input ("Please enter the first number: "))
num_2 = int (input ("Please enter the second number: "))
if choice == 'a':
print (num_1, " + ", num_2, " = ", add(num_1, num_2))
elif choice == 'b':
print (num_1, " - ", num_2, " = ", subtract(num_1, num_2))
elif choice == 'c':
print (num1, " * ", num2, " = ", multiply(num1, num2))
elif choice == 'd':
print (num_1, " / ", num_2, " = ", divide(num_1, num_2))
else:
print ("This is an invalid input")

Register Number: 211423247______ Page |


Output:

Result:

Register Number: 211423247______ Page |


Python Program To Sort The Elements Of An Array In Descending Order

Program:

#Initialize array
arr = [5, 2, 8, 7, 1];
temp = 0;

#Displaying elements of original array


print("Elements of original array: ");
for i in range(0, len(arr)):
print(arr[i]),

#Sort the array in descending order


for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
if(arr[i] < arr[j]):
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

print();

#Displaying elements of array after sorting


print("Elements of array sorted in descending order: ");
for i in range(0, len(arr)):
print(arr[i]),

Output:

Register Number: 211423247______ Page |


Result:

Register Number: 211423247______ Page |


Python Program To Find Using Binary Search

Program:
def binary_search(list1, n):
low = 0
high = len(list1) - 1
mid = 0
while low <= high:
# for get integer result
mid = (high + low) // 2
# Check if n is present at mid
if list1[mid] < n:
low = mid + 1
# If n is greater, compare to the right of mid
elif list1[mid] > n:
high = mid - 1

# If n is smaller, compared to the left of mid


else:
return mid
# element was not present in the list, return -1
return -1
# Initial list1
list1 = [12, 24, 32, 39, 45, 50, 54]
n = int(input("Enter the Number to find"))

# Function call
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:

Register Number: 211423247______ Page |


Result:

Register Number: 211423247______ Page |


Python Program To Sort Using Merge Sort

Program:
def Merge_Sort(array):
if len(array) > 1:
# mid is the point where the array is divided into two subarrays
mid = len(array)//2
#print(mid)
Left = array[:mid]
Right = array[mid:]

Merge_Sort(Left)
Merge_Sort(Right)
i=j=k=0
print(Left)
print(Right)
while i < len(Left) and j < len(Right):
if Left[i] < Right[j]:
array[k] = Left[i]
i =i+ 1
else:
array[k] = Right[j]
j =j+ 1
k += 1
while i < len(Left):
array[k] = Left[i]
i =i+ 1
k =k+ 1

while j < len(Right):


array[k] = Right[j]
j =j+ 1
k =k+ 1
# Print the array
def printarray(array):
for i in range(len(array)):
print(array[i], end=" ")
print()
# Driver program
if __name__ == '__main__':
array = [7, 2, 5, 6, 3, 1, 8, 4]
print("Orignal Array is: ", array)
Merge_Sort(array)
print("Sorted array is: ")
printarray(array)

Register Number: 211423247______ Page |


Output:

Result:

Register Number: 211423247______ Page |

You might also like