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

Python Lab Programs

Python program samples

Uploaded by

MJAYASURYA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Python Lab Programs

Python program samples

Uploaded by

MJAYASURYA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

PROGRAM 1: Program using variables, constants, I/O statements in Python

PROGRAM :
print(‘To find the area , perimeter , circumference calculation using variable , constants , I/O
statements’)
PI=3.14
len=int(input("Enter the Length of rectangle:"))
bre=int(input("Enter the Breadth of rectangle:"))
r=int(input("Enter the Radius of Circle:"))
area1=len*bre
perimeter=2*(len+bre)
area2=PI*r*r
circum=2*PI*r
print("Area of Rectangle =",area1)
print("Perimeter of Rectangle =",perimeter)
print("Area of Circle =",area2)
print("Circumference of Circle =",circum)

OUTPUT:
To find the area , perimeter , circumference calculation using variable , constants , I/O
statements:

Enter the Length of rectangle:20


Enter the Breadth of rectangle:30
Enter the Radius of Circle:10
Area of Rectangle = 600
Perimeter of Rectangle = 100
Area of Circle = 314.0
Circumference of Circle = 62.800000000000004
Program 2: Program using Operators in Python.

PROGRAM:

print('Expressions Evaluations using operators \n')


a=int(input("Enter the First Number:"))
b=int(input("Enter the Second Number:"))
x=input("Enter the String:")

c=((a+b)*(a-b)/(a))
d=((a**b)+(a//b))
print('\nResult for using Arithmetic operators : ' , c , d)
a += b
print('Result for using Assignment Operator: ', (a))
print('Result for using Relational & Logical operators : ' , ((a > b) and (c <= d) or (b>=c)))
print('Result for using Bitwise operators (& , | , ~ , ^) : ' , (a&b) , (a|b) , (~a) , (a^b))
print('Result for using Bitwise Shift operators (<< , >>) : ' , (a<<2) , (b>>2))
print('Result for using Identity operators : ' , (a is b) , (c is not d))
print('Result for using Membershif Operators : ' , ('H' in x) , ('hello' not in x))

OUTPUT:
Expressions Evaluations using operators
Enter the First Number:4
Enter the Second Number:2
Enter the String:hello

Result for using Arithmetic operators : 3.0 18


Result for using Assignment Operator: 6
Result for using Relational & Logical operators : True
Result for using Bitwise operators (& , | , ~ , ^) : 2 6 -7 4
Result for using Bitwise Shift operators (<< , >>) : 24 0
Result for using Identity operators : False True
Result for using Membershif Operators : False False
Program 3: Program using Conditional Statements.
PROGRAM:
print('Finding Biggest and Smallest number using conditional statements')
print('\nTo Find the Biggest among the given three numbers for using Nested IF sttement')
print('and To Find the Smallest among the given three numbers for using IF_ElIF_ELSE sttement')
a=int(input('Enter the Number1: '))
b=int(input('Enter the Number2: '))
c=int(input('Enter the Number3:' ))
if (a>b):
if (a>c):
g=a
else:
g=c
else:
if (b>c):
g=b
else:
g=c
print('The Largest Number is = ',g)
s=0
if (a < b and a < c ):
s=a
elif (b < c):
s=b
else :
s=c
print('The Smallest Number is =',s)
OUTPUT:
Finding Biggest and Smallest number using conditional statements
To Find the Biggest among the given three numbers for using Nested IF sttement
and To Find the Smallest among the given three numbers for using IF_ElIF_ELSE sttement
Enter the Number1: 25
Enter the Number2: 45
Enter the Number3: 15
The Largest Number is = 45
The Smallest Number is = 15
4. Program using Loops

PROGRAM
print('Program For Demonstrating the various looping statements')
print('\n Print the reverse digits of given number using while loop')
number = int(input('Enter the integer number: '))
revs_number = 0
while (number > 0):
remainder = number % 10
revs_number = (revs_number * 10) + remainder
number = number // 10
print('The reverse number is : {}'.format(revs_number))
print('\n Sum of N natural numbers using for loop')
num = int(input("Please enter the number: "))
sum = 0
for value in range(1, num + 1):
sum = sum + value
print('the sum of first',num,'natural number is =',sum)

OUTPUT:
Program For Demonstrating the various looping statements

Print the reverse digits of given number using while loop


Enter the integer number: 6318
The reverse number is : 8136

Sum of N natural numbers using for loop


Please enter the number: 10
the sum of first 10 natural number is = 55
5.Program using Jump Statements

PROGRAM:
import math
print(‘To find the Square root of given numbers using Jump Statements\n’)
while(1):
num = int(input('Enter the Number:'))
if(num == 999):
break
elif (num<0):
print('Square root of negative numbers cannot be calculated')
continue
else:
print('Square root of',num,'=',math.sqrt(num))

OUTPUT:
To find the Square root of given numbers using Jump Statements
Enter the Number:81
Square root of 81 = 9.0
Enter the Number:78
Square root of 78 = 8.831760866327848
Enter the Number:-49
Square root of negative numbers cannot be calculated
Enter the Number:999
6. Program using Functions.

PROGRAM:
def swap(x,y):
print('Before swapping a :',x)
print('Before swapping b :',y)
x,y=y,x
return x,y
print('Swapping of two numbers using function\n')
a=int(input('Enter the a value : '))
b=int(input('Enter the b value : '))
a,b=swap(a,b)
print('After swapping a becomes :',a)
print('After swapping b becomes :',b)

OUTPUT:
Swapping of two numbers using function
Enter the a value : 80
Enter the b value : 40
Before swapping a : 80
Before swapping b : 40
After swapping a becomes : 40
After swapping b becomes : 80
7. Program using Recursion.

PROGRAM:
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
print('Factorial Calculation Using Recursive Function')
num =int(input('Enter the Number : '))
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:
Factorial Calculation Using Recursive Function
Enter the Number : 5
The factorial of 5 is 120
8.Program using Arrays.
PROGRAM:
print('Sorting the Numbers using Arrays')
NumArr = [ ]
Number = int(input('Please enter the Total Number of Array Elements: '))
for i in range(1, Number + 1):
value = int(input('Please enter the Value of %d Element : ' %i))
NumArr.append(value)
for i in range (Number):
for j in range(i + 1, Number):
if(NumArr[i] > NumArr[j]):
temp = NumArr[i]
NumArr[i] = NumArr[j]
NumArr[j] = temp
print('Element After Sorting Array Elements in Ascending Order is : ', NumArr)
sort_numbers = sorted(NumArr, reverse=True)
print('\nElements After Sorting Array Elements in Descending Order is :',sort_numbers)

OUTPUT:
Sorting the Numbers using Arrays
Please enter the Total Number of Array Elements: 5
Please enter the Value of 1 Element : 30
Please enter the Value of 2 Element : 50
Please enter the Value of 3 Element : 10
Please enter the Value of 4 Element : 20
Please enter the Value of 5 Element : 40
Element After Sorting Array Elements in Ascending Order is : [10, 20, 30, 40, 50]
Elements After Sorting Array Elements in Descending Order is : [50, 40, 30, 20, 10]
9. Program using Strings.
PROGRAM:
print('Palindrome Checking using Strings\n')
def isPalindrome(string):
if(string == string[::-1]) :
return'The given string is a palindrome.'
else:
return'The given string is not a palindrome.'
string = input('Enter the input string:')
print(isPalindrome(string))

OUTPUT:
Palindrome Checking using Strings
Enter the input string: AMMA
The given string is a palindrome.

Palindrome Checking using Strings


Enter the input string: Nareshkumar
The given string is not a palindrome.
10.Program using Modules
PROGRAM:
# Module (fibonacci.py)
def fib(nterms):
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print('Please enter a positive integer ')
elif nterms == 1:
print('Fibonacci sequence upto',nterms,':')
print(n1)
else:
print('Fibonacci sequence:')
while (count < nterms):
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1

fibprog.py
import fibonacci
print('Fibonacci Series using Modules\n')
num=int(input('Enter any number to print Fibonacci series : '))
fibonacci.fib(num)

OUTPUT:
Fibonacci Series using Modules
Enter any number to print Fibonacci series : 6
Fibonacci sequence:
0
1
1
2
3
5
11. Program using Lists.
PROGRAM:
print('Searching Element in List\n')
lst=eval(input('Enter list:'))
length=len(lst)
element=int(input('Enter element to be searched for:'))
for i in range(0,length):
if element==lst[i]:
print(element,'found at index',i)
break
else:
print(element,'not found in given list')

OUTPUT:
Searching Element in List
Enter list:5,15,25,35,45,55
Enter element to be searched for:35
35 found at index 3

Searching Element in List


Enter list:2,12,22,32,42,52
Enter element to be searched for:23
23 not found in given list
12. Program using Tuples.
PROGRAM
print('Find the sum of given positive Numbers only using Tuple\n')
user_input = input('Enter space-separated integers: ')
tp = tuple(int(item) for item in user_input.split())
def sum_pos(*args):
tot = 0
for i in args:
if (i>0):
tot += i
return tot
print('The sum of Positive Numbers =',sum_pos(*tp))

OUTPUT:
Find the sum of given positive Numbers only using Tuple
Enter space-separated integers: 10 -20 35 -40 55 60 -32 25
The sum of Positive Numbers = 185
13. Program using Dictionaries.

PROGRAM:
print('Employee salary details checking using Dictionary\n')
employees = { }
max_length = int(input('Please enter the Employees count: '))
while (len(employees) < max_length):
name = input('Enter employees name: ')
salary = input('Enter employees salary: ')
if name not in employees:
employees[name] = salary
print(employees)
print('The highest salary getting employee is')
print([key for key in employees.keys() if employees[key]==max(employees.values())])

OUTPUT:
Employee salary details checking using Dictionary
Please enter the Employees count: 3
Enter employees name: S.Prasanth
Enter employees salary: 30000
Enter employees name: K.Sathishwaran
Enter employees salary: 45000
Enter employees name: N.Anmol
Enter employees salary: 50000
{S.'Prasanth': '30000', 'K.Sathishwaran': '45000', 'N.Anmol': '50000'}
The highest salary getting employee is
['N.Anmol']
14. Program for File Handling.
PROGRAM:
import sys
print('Copied the contents from one file into another file using File Methods\n')
file_name = input('Filename with extension, e.g. example.txt: ')
print('Press CTRL + D (Unix) or CTRL + Z (Windows) to exit')
with open(file_name, 'w', encoding='utf-8') as my_file:
my_file.writelines(sys.stdin.readlines( ))
file1 = open('file1.txt','r')
file2 = open('file2.txt','w')
num = 1
for line in file1:
file2.write(str(num) + ': ' +line)
num = num + 1
file1.close( )
file2.close( )
file2 = open('file2.txt','r')
print('File2 contents are copied from file1 suessfully!')
print('File2 copied contents are')
cons = file2.read( )
conlines = cons.split('\n')
for lines in conlines:
print(lines)
file2.close( )

OUTPUT:
Copied the contents from one file into another file using File Methods
Filename with extension, e.g. example.txt: file1.txt
Press CTRL + D (Unix) or CTRL + Z (Windows) to exit
ARIGNAR ANNA COLLEGE
WELCOME TO BCA
^Z
File2 contents are copied from file1 suessfully!
File2 copied contents are
1: ARIGNAR ANNA COLLEGE
2: WELCOME TO BCA

You might also like