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

Python Lab Manual

The document contains a series of programming exercises covering basic concepts in Python, including addition, square roots, area calculations, quadratic equations, unit conversions, variable swapping, and more. Each exercise includes a program, expected output, and sometimes explanations of the syntax used. The programs demonstrate fundamental programming techniques and mathematical operations.

Uploaded by

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

Python Lab Manual

The document contains a series of programming exercises covering basic concepts in Python, including addition, square roots, area calculations, quadratic equations, unit conversions, variable swapping, and more. Each exercise includes a program, expected output, and sometimes explanations of the syntax used. The programs demonstrate fundamental programming techniques and mathematical operations.

Uploaded by

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

1.(AJADDITION OF TwO NUMBERS.

1.(a): write a program for addition of two numbers.

PROGRAM:

x = input ("Type a number: ")

y = input (" Type another number: ")

sum = int(x) + int(y)

print ("The sum is: ", sum)

OUTPUT:

Type a number: 5
Type another number:6

The sum is: 11

1
1.(B)sQUARE ROOT FOR POSITIVE AND REAL &COMPLEX NUMBES.

1.(b): write a program to find square root for positive and real & complexnumbers.
PROGRAM:
from cmath import sqrt

a= 16
b0.2 +
c=-4

print(sqr(a ))

print(sqr(b )
print(sqrt(c)

OUTPUT:

(4+0j)

(0.4472135954999579+0)

2
1.(C)AREAS FOR GIVEN DIMENSION.

1.(c): write a program to calculate area of a triangle.

PROGRAM:
import math

|=loat(input('Length'))

b=float(input('Breadth')

h=float(input(Height)

-float(input(Radius)

print('area ofrectanglestr(1*b) )
print('area of square=tstr(1*1)

print('area of triangle=+str(b*h/2)

print('area of circle='+str(math.pi*r*r)

OUTPUT:

Length :2

Breadth:3

Height: 4

Radius :6

area of rectangle=6.0
area ofsquare =4.0
area of triangle =6.0
area of circle = 113.0973355292 3255

3
2.(A)QUADRATIC EQUATION.

2.() write a program to solve an


quadratic equation .
PROGRAM:
# Solvethequadratic equation
ax*"2+ bx +c0

# import complex math module


import cmath

a=1
b=5

C=6
# calculate the
discriminant

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

# find twO solutions

soll = (-b-cmath.sqrt(d))/(2"a)

sol2 = (-b+cmath.sqrt(d))/(2"a)

print('The solution are (0) and (1)'.format(se1,sol2)

OUTPUT:

Enter a: 1

Enter b: 5

Enter c: 6
The solutions are (-3+0j) and (-2+0j)
2.(B)CONVERSION OF KILOMETERS TOMILES

2.(b): write a program to convert kilometers to miles.

PROGRAM:
# Taking kilometers input from
the user

kilometers =float(input("Entervalue in kilometers:")

# conversion factor

conv_fac= 0.621371

# calculate miles

miles = kilometers * conv fac

print(%0.2f kilometers is equal to %0.2f miles' %(kilometers, miles))

OUTPUT:

Enter value in kilometers: 3.5

3.50 kilometers is equal to 2.17 miles


2.(C)SWAPING TWO VAIRABLES.

2.(c): write a program to swap two vairables.

PROGRAM:

# Python program toswap two variables

X=5

y= 10

# To take inputs from the user

#x = input('Enter value of x:')

#y = input('Enter value of y: ')

# create a temporary variable and swap the values

temp = X

X=y
y= temp

print('The value of x after swapping: (}'.format(x)

print('The value of y after swapping: (}'.format(y))

OUTPUT:

The value of x after swapping: 10

The value of y after swapping: 5

6
3.(A)PRINTING OUTPUT WITHOUT A NEW LINE

3.(a): write a program to print output without a new line.

PROGRAM:

print("python"),

print("is fun to learn'")

# Array

a = (1, 2,3, 4)

# Printing each element on the same line


for iin xrange(4):

print(a[),

OUTPUT:

python phython is fun to learn

1234
3.(B)FACTORIAL OF NUMBER
A

3.(b): write a program to find factorial of a number.

SYNTAX:
Int =converts the specified value into a integer
number.
=
For iterating over a sequence.
If= executes the body if the statement is true.
Print = print the specified message to the screen.

PROGRAM:
num=int(input("Enter a number:\t"))
fact=num
if num=0:
fact=1

else:

for i in range(1,num):
fact*=i

print ("Factorialof the given number is:" +str(fact)

OUTPUT:
Enter a number:5
Factorial of the given number is:120
3.(C) LARGESTOF THREE NUMBERS

3.(: write a program to find the largest among the three numbers.

PROGRAM:
# Take three numbersfrom the user

numl = float(input("Enterthe first number: ")


num2 = float(input("Enterthe second number:")
num3 = float(input("Enterthe third number:")

Compare the numbersto


#
find the largest

if (num1 >= num2) and (num1 >= num3):

largest = num1
elif (num2 >= num1) and (num2 >= num3):

largest = num2
else:

largest = num3
# Print the result

print("The largest number is", largest)

UTPUT:

Enter the frist number:9

Enter the second number:6

Enter the third number:32

The largest number is 32

9
4.(A)CHECKING GIVEN NUMBER IS A PRIME NUMBER (OR) NOT.

4.(a): write a program to check if a number is positive, negative (or)zero.

PROGRAM:
num = float(input("Entera number:")

if num > 0:

print("Positive number")
elif num == 0:

print("Zero")

else:

print("Negative number")

OUTPUT:

Enter a number:2

Positive number

10
4.(B)CHECKING GIVEN NUMBER IS ODD(OR)EVEN.

4.(b): write a program to check if a number is odd (or) even.

PROGRAM:
#Python program tocheck if the input number is odd or even.

#A number is even if division by 2 givesa remainder of 0.

#If the remainder is 1, it is an odd number.

num = int(input("Enter number: ") a

if (num % 2) == 0:

print("{0} is Even".format(num)

else:

print("{0) is Odd".format(num))

OUTPUT:

Enter a number:43

43 is Odd

11
4.(C)LEAP YEAR.

4.(c): write a program to check leap year.

SYNTAX:
Int =converts the specified value into an integer number.
If= executes the body if the
statement is true.
Print print the specified message to the screen.

PROGRAM:

year=int(input('Enterayear))
if(year%400==0) and (year%100=-0):
print('{0}is a leap year'. format(year))
elif(year%4==0) and (year%100!=0):
print('{0} is not a leap
year'.format(year)
else:

print({0} is not a leap year. format(year)

OUTPUT:

Enter a year:2022
2022 is not a leap year

12
5.(A)CHECKING GIVEN NUMBER IS A PRIME NUMBER(ORJNOT.

s.la): write a program to check prime number.

SYNTAX:

Int convertsthe specified value into ainteger number.


If- executes the body if the statement is true.
Break- break the loop.

Print - print the specified messageto the screen.

PROGRAM:

num=int(input("Enter a number:In")
flag-0
if num=1:
print("It is neither prime nor composite")
else:

for i in range(2,num):
if (num%i)=0:
flag-1
break
if flag-0:
print(str(num) +"is a prime number")
else:

print(str(num)+" is not a prime number")

OUTPUT:

Enter a number: 24
24 isnot a prime number.

13
5.(B)PRINTING PRIME NUMBERS

5.(b): write a program to print all prime numbers in an interval.

PROGRAM:

# Function to check if a number is prime


def is_prime(num):
if num > 1:

for in range(2, num):


i
if (num 9% i) == 0:
return False

return True

else:

return False
# Take the interval from the user
lower = int(input(" Enter the lower bound of the interval: ")
upper = int(input("Enterthe upper bound of
the interval:
")
# Print all prime numbersin the interval

print(f"The prime numbers between(lower) and {upper) are:")


for num in range(lower, upper + 1):
if is_prime(num):

print(num)

OUTPUT:

Enter the lower bound ofthe interval:

Enter the upper bound of the interval:

The prime numbers between 2 and 10 are:3 57

14
5.(C)PRINTING MULTIPLICATION TABLE.

5.(c): writea programto display the multiplication table.

PROGRAM:
# Multiplication table (from 1 to 10) in Python

num = 12

# To take input from the user

# num = int(input("Display multiplication table of? ")

# Iterate 10 times from i= 1 to 10


for i in range(1, 11):

print(num, 'x', i,',num"i)

OUTPUT:

12 x 1 = 12

12 x 2 = 24

12 x 3 = 36
12 x 4 =48
12 x5 =60

12 x 6 =72
12 x 7 = 84

12 x 8= 96

12 x9 = 108

12 x 10= 120

15
6.(A)ADDITION & SUBTRACTION OF MA TRICES.

6.(a): write a program to add and subtract matrices.

SYNTAX:

List =list type variable


Map =function works as an
that iterator to returna result ater applying a function to every
item of an iterable

Int =converts the specified value into a integer number.


For= iterating over a sequence.

PROGRAM:

ml = [list(map(int, input("Enter row: ").split(" ")))


for i in
range(int(input("Enter Number of rows: ")I
m2 = [list(map(int, input("Enter row: ").split(" "))
for iin range(int(input("Enter Number of rows: ")))]
print("Add Matrix:")
r-[[ml[OG] +m2[ÜG]
for j in range(len(ml[0]))] foriin range(len(ml )]
print(r)

print("Subtract Matrix:")
r=[[ml [JG]- m2[iJ[]
for jin range(len(m l[0))] for i in range(len(m1)]
print(r)

16
OUTPUT:
Enter Number of rows: 3
Enter row: 231

Enter row: 4 56
Enter row: 7 89
Enter Number of rows:3
Enter row: 7 89
Enter row: 4 56
Enter row: 1 23
Add Matrix:
[[8,10, 12]. (8, 10, 12], [8, 10, 12]1
Subtract Matrix:

(-6, -6, -6], (0,0, 0], [6, 6, 6]]

17
6.(8) REVERSEAN STRING .

6.(b): write a programto reverse words in a string.

SYNTAX:
Def- define the function
Return end the executionof the function call.
Str converts the specified value in to a
string.
Print - print the specified message
to the sereen.

PROGRAM:

def rev(strng):

stng-strng[::-1]
return strng
S=str(input('enter a string:n)
print(The reversed string is:")

print(rev(s)

OUTPUT:

enter a string: snake


The reversed string is: ekans

18
6.(C) REVERSE AN INTEGER.

6.(c): write a program to reverse an integer.

SYNTAX:

Int =converts the specified value into a integer number.


While executes the statement until it is true.
Print = print the specified message to the
screen

PROGRAM:

num=int(input("Enter a numbert")
rev-0
while num!-0:
rem=num%10
rev=rev*10+rem
num/=10
print("the reversed number:")

print(rev)

OUTPUT:

Enter a number: 12546


the reversed number: 64521

19
7.(A)PRINTING
FIBONACCI SERIES.

7.(a): write a program to print Fibonacci


series.

SYNTAX:

Int =converts the specified value into a integer


While= executes the statement number.
until it is true,
Print print the specificd
message to the screen.

PROGRAM:

num=int(input("Enter number of terms\(")


a-0
b=1
i-0
print("The Fibonacci Series:")
while i<num:

print(a)

it-1
C=atb
a-b
b=c

OUTPUT:

Enter number of terms: 5


The Fibonacci Series:

2
3

20
7.(B)PRINTING A TRIANGLE
UuSING STARS()

7.(b): write a program to


producestar triangle.

SYNTAX:
Int =converts the specified value
into a integer
For = over a sequence.
iterating
number.
Print =print the specified message to
the screen
PROGRAM:

num=ínt(input("Enter no.of rows")


for iin range(1,numn+l):

print(""(num-i)+"* "*i)

OUTPUT:

Enter no.of rows:5

21
7.(C)BASIC CALCULATOR

.
7.c): write a program for calculator.

SYNTAX:

Int =converts the specified value into an integer number.


Print =print the specified messageto
the screen.

PROGRAM:

a=int(input(Enter 1st number:)


b=int(input('enter 2nd number:)
print('sum='+str(a+b))
print('difference='+str(a-b)

print('product='+str(a*b))
print('quotient='+str(a/b))
print('remainder='+str(a%b)

OUTPUT:

Enter 1st number :3


enter 2nd number:
sum = 8
difference = -2

product 15
quotient = 0.6
remainder = 3

22
8.(A)PRINTIN CURRENT DATE & TIME.

8.(a): write a program to get


current date and time.
SYNTAX:

Import access to code from


another module by
Print the specified
print
importing the file.
message tothe screen.

PROGRAM:

from datetime import datetime


today-datetime.today()
print('Today date and time:'+str(today)

OUTPUT:

Today date and


time:2022-08-25 16:34:20.048881

:
RESULT Hence the program executed successfully and generates the correct
outputs.

23
8.(B)BINARY SEARCH.

s.(b): write a program for binary search.

SYNTAX:

Def= defines a user function


Binary search( ) = calls user defined function
Int =converts the specified value into a integer number.
For = iterating over a sequence.
If=executes the body if the statement is true.
Print =print the specified message to the screen.

PROGRAM:

def binary_search(arr, low, high, x):

if high >= low:

mid
if arr[mid]
return mid
=
=(high + low)
x:
l/ 2

elif arr[mid] > x:


return binary_search(arr, low, mid - 1, x)
else:

return binary_ search(arr, mid + 1, high, x)


else:

return -1

arr =(]
num=int(input('no.of elements)

for iin range(0,num):


ele-int(input('enterelement')
arr.append(ele)
X =int(input('Enter no.to be searched'))
result = binary search(arr, 0, len(arr)-1, x)
if result !=-1:

print("Element is present at index", str(result)


else:

print("Element is not present in array")

24
OUTPUT:

po. ofclements 4
enter clement
56
34
enter element
enter element 11
enter element
77
Enter no.to be searched 34
Element is present atindex 1

25
8.(c)CALCULATOR OPERATIONS USING
CLASSES.

a program to create
write a class
8.(c): which performs basic calculator operations.

PROGRAM:

dlass calculator_ implementation(0:

def _init_(self,in_1,in_):

self.a=in_1

self.b=in_2

def add_vals(self):

return self. a+self.b

def multiply_vals(self):

return self.a*self.b

def divide_vals(self):

return self. a/self.b

def subtract_vals(self):

return self.a-self.b

input_1 = int(input("Enter the first number:")

input_2 = int(input("Enter the second number:")

print("The entered first and second numbers are :")

print(input_1,input_2)

my_instance = calculator_implementation(input_1,input_2)
choice=1

while choice!=0:

print("0. Exit")

print("1. Addition")

print("2. Subtraction'")

print("3. Multiplication'")

print("4. Division")

26
choiceint(input("Enter your choice.."))

if choicel:

print("The computed addition result is


:",my instance.add_vals())
elif choicesn2:

print("The computed subtraction result is :",my instance.subtract_vals()


elif choice=-3:

print("The computed product result is ",my instance.multiply_vals())

choice=4:
elif

print("The computed division result is :",round(myinstance.divide_vals(),2)


elif choice==0:

print("Exit")

else:

print("Sorry, invalid choice!")

print()

OUTPUT:

Enter the first number:70

Enter the second number:2

The entered first and second numbers are


:
70 2

0. Exit

1. Addition

2. Subtraction

3. Multiplication

4. Division

Enter your choice...1

The computed addition result is :72


0. Exit

1. Addition

27
2.Subtraction

3. Multiplication

4. Division

choice...
2
Enter your

subtraction result is:68


The computed

0.Exit

1. Addition

2.Subtraction

3.Multiplication

4. Division

3
Enter your choice...

The computed productresult is: 140

0.Exit

1. Addition

2. Subtraction

3. Multiplication

4. Division

Enter your choice... 0


Exit

28
9.(A)APPEND, DELE TE& DISPLAY
ELEMENTs OF LIST USING CLASSES.

write
eaprogramto append ,delete and display elements
9.la):
of a list using classes.

PROGRAM:
MyList:
class

def_init_(sel):

self.items
- ()

item):
def append(self,

self.items.append(item)

def delete(self,
item):

if item in self.items:

self.items.remove(item)

def display(self):

print(self.items)

# Create an instance of the MyList class

my_list = MyList()

# Append some items to the list

my_list.append(1)

my_list.append(2)

my_list.append(3)

# Display the list

my_list.display()

29
# Delete an item from the list

my_list.delete(2)

# Display the list again

my_list.display()

OUTPUT:

[1, 2,31

[1, 3]

30
9.(B)CREATING A PERSON
CLASS&DETERMINE HIS AGE.

write
a progran to create a person's class
9.(b): Anclude attributes like name,countryand
date offbirth.Implement method Ito determine the person's age.

PROGRAM:
from datetime importdate

class Person:

def init_(self, name, country, dob):

self.name = name

self.country = country

self.dob = dob

def age(self):

today = date.today()

return today.year - self.dob.year - (today.month, today.day) < (self.dob.month,

self.dob.day))

person1 = Person('John', 'India', date(1990, 1,


1)
print(person1.age())

OUTPUT:

33

31
9.(c)AREA&PERIMETEROF CIRCLE,
TRIANGLERSQUARE BY SUBCLASSES.

write ea python program to


9.(c): create a classthat
represents ashap.include methods to
it's area and
calculate perimeter.implement subclasses for different shapes like circle
,triangle &square.

PROGRAM:
math
import

class Shape:

def_init_(self):

self.name = "Shape"

def area(self):

pass

def perimeter(self):

pass

class Circle(Shape):

def init_(self, radius):

super().init_()

self.radius = radius

self.name = "Circle"

def area(self):

return math.pi * self.radius ** 2

def perimeter(self):

return 2* math.pi self.radius

class Triangle(Shape):

32
def init_(selt,,side1,
side2, side3):

super()init_0

self. sidel
side1

self.side2
e side2

self.side3
side3

self.name"Triangle"

def area(self):

s (self.sidel + self.side2 + self.side3) /2


return math.sqrt(s (s - self.side1) (s self.side2) * (s -self.side 3))

def perimeter(self):

return self.side1 + self.side2 + self.side3

class Square(Shape):

def__init__(self,side):

super).init_0

self.side = side

self.name = "Square"

def area(self):

return self.side ** 2

def perimeter(self):

return 4 * self.side

circle = Circle(5)

print(circe.name)

print(circle.area()

33
print(circle.perimeter(0)

triangle = Triangle(3, 4, 5)

print(triangle.name)

print(triangle.area()

print(triangle.perimeter)

square =Square(4)
print(square.name)

print(square.area()

print(square.perimeter()

OUTPUT:

Circle

78.539816339 74483

31.41592653589793

Triangle

6.0

12

Square

16

16

34

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy