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

Python programs

The document contains a series of Python programs demonstrating various programming concepts including temperature conversion, factorial calculation, Fibonacci series, list operations, matrix operations, and exception handling. Each program is followed by sample output, showcasing its functionality. The programs cover a wide range of topics suitable for beginners to understand basic programming constructs and data manipulation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python programs

The document contains a series of Python programs demonstrating various programming concepts including temperature conversion, factorial calculation, Fibonacci series, list operations, matrix operations, and exception handling. Each program is followed by sample output, showcasing its functionality. The programs cover a wide range of topics suitable for beginners to understand basic programming constructs and data manipulation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Program 1:

#Program for Temperature Conversion


#Centigrade to Farenheit Conversion
print('Enter the Temperature in Centigrade:')
c = int(input('Centigrade='))
f = 1.8*c+32
print('centigrade {} equal to farenheit is {}'.format(c,f))
print('Enter the Temperature in Farenheit:')
fa= input('Farenheit=')
c1=(f-32)/1.8
print('farenheit {} equal to Centigrade is {}'.format(fa,c1))

OUTPUT:
Enter the Temperature in Centigrade:
Centigrade=97
centigrade 97 equal to farenheit is 206.6
Enter the Temperature in Farenheit:
Farenheit=206.6
farenheit 206.6 equal to Centigrade is 97.0

1
Program 2:

#Find Factorial of a Number


def fact(n):
prod =1
if n==0:
print('factorial of 0 : ',n)
else:
i =1
whilei<=n:
prod =prod*i
i+=1
print('factorial of {} is {}'.format(n,prod))
#Calling the function Factorial
fact(5)

OUTPUT:

factorial of 5 is 120

2
Program 3:
#Fibonacci Series up to a limit
print('Enter a number to print Fibonacci Series upto that Number')
n = int(input('Enter the Number:'))
t1,t2 = 1,1
print('Fibonacci Series')
print(t1,t2)
i=1
whilei<=n:
t3 = t1+t2
print(t3)
t1,t2 = t2,t3
i = i+1
print('End of the series')

OUTPUT:

Enter a number to print Fibonacci Series upto that Number


Enter the Number:5
Fibonacci Series
11
2
3
5
8
13
End of the series

3
Program 4:

#Sum and product of all the items in the list


lst =[]
num = int(input('How many Numbers:'))
for n in range(num):
numbers = int(input('number:'))
lst.append(numbers)
print('The Given List=',lst)
sum = 0
product =1
fori in lst:
sum = sum +i
product=product* i
print('Sum of the elements in List:',sum)
print('Product of elements in List:',product)

OUTPUT:

How many Numbers:5


number:10
number:20
number:30
number:40
number:50
The Given List= [10, 20, 30, 40, 50]
Sum of the elements in List: 150
Product of elements in List: 12000000
4
Program 5:

#Print The Multiplication Table of a Number


n =int(input('Enter the number to print its Multiplication Table'))
i=1
prod = 1
print('Multiplication Table of a given Number')
whilei<=10:
prod = n*i
print('%d * %d = %d' %(n,i,prod))
i= i+1

OUTPUT:

Enter the number to print its Multiplication Table 5


Multiplication Table of a given Number
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

5
Program 6:
#Print largest and smallest of items in the list.
lst=[]
print('How many elements ?')
n = int(input())
fori in range(n):
print('Enter Element:')
lst.append(int(input()))
print('The Given List =',lst)
big = lst[0]
small = lst[0]
fori in range(1,n):
iflst[i]>big: big= lst[i]
iflst[i]<small: small=lst[i]
print('Maximum is :',big)
print('Minimum is :',small)
OUTPUT:
How many elements ?
5
Enter Element:
1
Enter Element:
2
Enter Element:
3
Enter Element:
4
Enter Element:
6
5
The Given List = [1, 2, 3, 4, 5]
Maximum is : 5
Minimum is : 1

7
Program:7

#Removing Duplicates from List


l= [1,2,3,53,1,6,8,99,10,2,5,13,67]
print('The given List',l)
s =[]
fori in l:
ifi not in s:
s.append(i)
print("List after removing Duplicates",s)

OUTPUT:

The given List [1, 2, 3, 53, 1, 6, 8, 99, 10, 2, 5, 13, 67]


List after removing Duplicates [1, 2, 3, 53, 6, 8, 99, 10, 5, 13, 67]

8
Program: 8
#Addition, Subtraction of Matrices
x = [[1,2,3],[4,5,6],[7,8,9]]
y = [[7,8,9],[4,5,6],[1,2,3]]
a=[[0,0,0],[0,0,0],[0,0,0]]
b= [[0,0,0],[0,0,0],[0,0,0]]
c=[[0,0,0],[0,0,0],[0,0,0]]
fori in range(len(x[0])):
for j in range(len(y[0])):
a[i][j]=x[i][j]+y[i][j]
b[i][j]=x[i][j]-y[i][j]
print("Addition of Matrices=")
for r in a:
print(r)
print()
print("Subtraction of Two Matrices=")
for k in b:
print(k)

OUTPUT:
Addition of Matrices=
[8, 10, 12]
[8, 10, 12]
[8, 10, 12]
Subtraction of Two Matrices=
[-6, -6, -6]
[0, 0, 0]
[6, 6, 6]
9
Program 9:

#Transpose Of a Matrix
x =[[12,7,3],[4,5,6],[7,8,9]]
t = [[0,0,0],[0,0,0],[0,0,0]]
fori in range(len(x[0])):
for j in range(len(x[0])):
t[i][j]=x[j][i]
print("Transpose Matrix is:")
for r in t:
print(r)

OUTPUT:

Transpose Matrix is:


[12, 4, 7]
[7, 5, 8]
[3, 6, 9]

10
Program 10:

#Second Smalles and Largest Number in List


a = []
n = int(input("Enter the Number of Elements "))
fori in range(n):
b = input("Enter a Number")
a.append(b)
a.sort()
print("Second largest Element is ",a[n-2])

OUTPUT:
Enter the Number of Elements 5
Enter a Number5
Enter a Number45
Enter a Number6
Enter a Number78
Enter a Number90
Second largest Element is 78

11
Program-11
#Counting the number of elements in List
list1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]
l = 40
r = 80
print("The given List")
print(list1)
c=0
fori in list1:
ifi>=l and i<=r:
c = c+1
print("Number of elements in List within a range", c)

The given List


[10, 20, 30, 40, 50, 40, 40, 60, 70]
Number of elements in List within a range 6

12
Program-12

#Program to find the frequency of elements in a list


list1 = [10,20,30,10,40,50,30,60,10]
print("Given List",list1)
c=0
print("Enter the element to find the frequncy")
ele = int(input("Element:"))
i=0
fori in list1:
ifi==ele :
c = c+1
print("Number of times the element %d occured %d",ele,c)
Given List [10, 20, 30, 10, 40, 50, 30, 60, 10]
Enter the element to find the frequncy
Element:10
Number of times the element %d occured %d 10 3

13
Program-13
# A function to test whether a number is even or odd
Def even_odd(num):
If num % 2==0:
Print(num,” is odd”)
Else:
Print(num, “ is odd”)
# call the function
even_odd(12)
even_odd(13)

OUTPUT
12 is even
13 is odd

14
Program – 14
# function to check string is palindrome or not
defisPalindrome(str):

# Run loop from 0 to len/2


fori inrange(0, int(len(str)/2)):
ifstr[i] !=str[len(str)-i-1]:
returnFalse
returnTrue

# main function
s =input(‘Enter a String:’)
ans =isPalindrome(s)

if(ans):
print("Given string is Palindrome")
else:
print("Given string is not a Palindrome")

OUTPUT:
Enter a String: Malayalam
Given string is palindrome

15
Program 15
# Program to demonstrate on scope of a variable
a,b = 5,6
Def fun1():
a,b = 1,2
Print(“ a =%d and b = %d”%(a,b)
b= 10
def fun2():
a =25
fun1()
print(“a =%d and b =%d”%(a,b))
b=7
fun1()
print(“a=%d and b =%d”%(a,b))
a = 30
fun2()
print(“a=%d and k = %d”%(a,b))

OUTPUT:
a =1 and b = 2
a= 5 and b =7
a= 1 and b = 2
a = 25 and b =7
a= 30 and b =7
Output:
a=1 and b=2

16
16. Program to find roots of quadratic equation

import cmath
a=float(input('enter a:'))
b=float(input('enter b:'))
c=float(input('enter c:'))
d=(b*b)-(4*a*c)
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:
enter a:8
enter b:5
enter c:99
The solution are(-0.3125-3.503904072602445j) and (-0.3125+3.503904072602445j)

17
17. #Program on break and continue

#Example for break statement


var = 0
output = []
while var <= 20 :
output.append(var)
if var == 15 :
break
var=var+1
print(output)

OUTPUT:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Example for continue statement

var = 0
output = []
while var <= 20 :
if var == 15 :
var=var+1
continue
output.append(var)
var=var+1
print(output)

OUTPUT
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20]

18
18. #Program on recursion.

def list_sum_recursion(a_list):
if len(a_list)==0:
return 0
return a_list[0]+list_sum_recursion(a_list[1:len(a_list)])

#finding the sum of the elements of a list


#initializing a list

a_list=[10,20,30,40,50,60,70,80,90]
total=list_sum_recursion(a_list)
print("sum of the elements in a list =",total)

OUTPUT:
sum of the elements in a list = 450

19
19. Read , write and append a file program

#display.txt ,existed data file


fp=open("C:\\Users\\vijaya\\GE python lab practicals\\display.txt",'r')
for line in fp.readlines():
print(line.strip())

OUTPUT(in display.txt file)


Respect for Others
Forgive Others
Admit Fault
Express Gratitude
Respect Yourself
Respect your Parents
Respect Difference

fp=open("C:\\Users\\vijaya\\GE python lab practicals\\outputfile.txt",'w')


fp.write('line 1\n')
fp.write('line 2\n')
fp.close()
fp=open("C:\\Users\\vijaya\\GE python lab practicals\\outputfile.txt",'a')
fp.write('line 3\n')
fp.write('line 4\n')
fp.close()

20
20. Python Program on Exception

def causeError(): #difinition of a method


try:
return 1+'a'
except TypeError:
print("There was a type error")
except ZeroDivisionError:
print("There was a zero Division Error")
except Exception:
print("There was some sort of error")

causeError() #calling method causeError()


output:
There was a type error

21
21. Display invalid mark exception if mark is greater than 100.

class invalid_marksexception(Exception):
pass

marks = int(input("Enter student marks: "))

try:
if marks>100 or marks<0:
raise invalid_marksexception()
except invalid_marksexception:
print ("Marks should be in 1 to 100 ")
Enter student marks: 102
Marks should be in 1 to 100

22

You might also like