0% found this document useful (0 votes)
4 views19 pages

Python Programming Lab Exercises

The document outlines a Python programming lab with various practical exercises for students at Faridabad College of Engineering and Management. It includes tasks such as temperature conversion, calculating factorials, finding areas of geometric shapes, generating Fibonacci series, and implementing search and sort algorithms. Each task is accompanied by sample code and expected outputs.

Uploaded by

office88028802
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

Python Programming Lab Exercises

The document outlines a Python programming lab with various practical exercises for students at Faridabad College of Engineering and Management. It includes tasks such as temperature conversion, calculating factorials, finding areas of geometric shapes, generating Fibonacci series, and implementing search and sort algorithms. Each task is accompanied by sample code and expected outputs.

Uploaded by

office88028802
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

FARIDABAD COLLEGE OF ENGINEERING AND

MANAGEMENT

Python Programming
Lab
LC-CSE-215G

Student details:
Exam Roll No:
Name:

Submitted to Faculty:

Signature:
INDEX

S. No. Title
Write a program to convert the given temperature from
1 Fahrenheit to Celsius and vice versa depending upon user’s
choice.
Write a program to find the factorial of the given number.
2

Write a program , using user-defined function to find the area


of a rectangle, square, circle and triangle by accepting suitable
3 input parameters from the user.

Write a program to display the first n terms of the Fibonacci


4 series.
Write a program to find whether the given number is Armstrong
5 Number or not.
Write a program to create a function that accepts a string and
6 calculates the number of upper-case letters and lower-case
letters.

Write a program to perform string operations (concatenation,


7 slicing, indexing, and length).

Write a program to find the largest and smallest number in a


8 matrix entered by the user.

Write a program to count the number of even and odd numbers


9 from N numbers.

Write a program to find the largest and smallest numbers in the


10 list entered by the user.

Write a program to sort a list of elements using the bubble sort


11 algorithm.
Write a program to implement a linear search algorithm to
12 search an element in the list entered by a user.
Practical-1
WriteaprogramtoconvertthegiventemperaturefromFahrenheittoCelsius and
vice versa depending upon user’s choice.
Code:
deffahrenheit_to_celsius(fahrenheit
): return (fahrenheit - 32) * 5
/ 9

defcelsius_to_fahrenheit(celsius):
return (celsius * 9 / 5) + 32

print("Temperature Converter")
print("[Link]")
print("[Link]")

choice=input("Enteryourchoice(1or2):")
temperature=float(input("Enterthetemperaturevalue:"))

ifchoice=='1':
celsius = fahrenheit_to_celsius(temperature)
print(f"{temperature}°Fisequalto{celsius:.2f}°C")
elifchoice=='2':
fahrenheit = celsius_to_fahrenheit(temperature)
print(f"{temperature}°Cisequalto{fahrenheit:.2f}°F")
else:
print("Invalidchoice.")

Output:
Practical-2
Writeaprogramtofindthefactorialofthegivennumber. Code:
deffactorial(n):
if n <0:
return"Factorialisnotdefinedfornegativenumbers"elif
n == 0:
return1
else:
fact=1
foriinrange(1,n+1): fact
*= i
returnfact

num=int(input("Enteranon-negativeintegertofinditsfactorial:"))
result = factorial(num)

print(f"Thefactorialof{num}is{result}")

Output:
Practical-3
Write a program, using user-defined function to find the area of a rectangle,
square, circle and triangle by accepting suitable input parameters from the
user.
Code:
importmath
defarea_rectangle(length,width):
return length * width

defarea_square(side):
returnside*side

defarea_circle(radius):
[Link]*radius*radius

defarea_triangle(base,height):
return 0.5 * base * height

print("AreaCalculator")
print("1. Rectangle")
print("2. Square")
print("3. Circle")
print("4. Triangle")

choice=input("Enteryourchoice(1-4):")

if choice == '1':
length=float(input("Enterthelengthoftherectangle:"))
width=float(input("Enterthewidthoftherectangle:"))
print(f"Theareaoftherectangleis:{area_rectangle(length,width)}")
elif choice == '2':
side=float(input("Enterthesidelengthofthesquare:"))
print(f"The area of the square is: {area_square(side)}")
elifchoice=='3':
radius = float(input("Enter the radius of the circle: "))
print(f"Theareaofthecircleis:{area_circle(radius):.2f}")
elifchoice=='4':
base = float(input("Enter the base of the triangle: "))
height=float(input("Entertheheightofthetriangle:"))
print(f"Theareaofthetriangleis:{area_triangle(base,height)}")
else:
print("Invalidchoice.")
Output:
Practical-4
WriteaprogramtodisplaythefirstntermsoftheFibonacciseries. Code:
deffibonacci_series(n):
if n <= 0:
return[]
elif n == 1:
return[0]
else:
series=[0,1]
whilelen(series)<n:
next_term=series[-1]+series[-2]
[Link](next_term)
returnseries

num_terms=int(input("EnterthenumberofFibonaccitermstodisplay:"))
fib_sequence = fibonacci_series(num_terms)

if not fib_sequence and num_terms >0 :


print(f"Displaying{num_terms}terms."
)
elifnum_terms<=0:
print("Pleaseenterapositiveintegerfor thenumberofterms.")
else:
print(f"Thefirst{num_terms}termsoftheFibonacciseriesare:{fib_sequence}")

Output:
Practical-5
WriteaprogramtofindwhetherthegivennumberisArmstrongNumberor not.
Code:
def is_armstrong(number):
num_str = str(number)
num_digits=len(num_str)
sum_of_powers = 0
fordigitinnum_str:
sum_of_powers+=int(digit)**num_digits
return sum_of_powers == number

num=int(input("Enteranumbertocheckifit'san Armstrongnumber:")) if

is_armstrong(num):
print(f"{num}isanArmstrongnumber.")
else:
print(f"{num}isnotanArmstrongnumber.")

Output:
Practical-6
Write a program to create a function that accepts a string and calculates the
number of upper-case letters and lower-case letters.
Code:
defcount_case_letters(input_string)
: upper_count = 0
lower_count=0
forcharininput_string:
if [Link]():
upper_count+=1
[Link]()
: lower_count += 1
returnupper_count,lower_count

text=input("Enterastring:")
upper,lower=count_case_letters(text)

print(f"Numberofupper-caseletters:{upper}")
print(f"Numberoflower-caseletters:{lower}")

Output:
Practical-7
Write a program to perform string operations (concatenation, slicing,
indexing, and length).
Code:
print("StringOperationsDemo")

str1 = input("Enter the first string:


") str2=input("Enterthesecondstring:")

concatenated_string=str1+str2

print(f"\nConcatenation:'{str1}'+'{str2}'='{concatenated_string}'")
print(f"Length of '{str1}': {len(str1)}")
print(f"Lengthof'{concatenated_string}':{len(concatenated_string)}")

ifstr1:
print(f"\nIndexing on '{str1}':")
print(f"Firstcharacter(index0):
{str1[0]}") if len(str1) >1:
print(f"Secondcharacter(index1):{str1[1]}")
if len(str1) >0:
print(f"Lastcharacter(index-1):{str1[-1]}")
else:
print(f"\n'{str1}'isempty,skippingindexingdemonstrationforit.")

ifconcatenated_string:
print(f"\
nSlicingon'{concatenated_string}':") if
len(concatenated_string) >= 4:
print(f"Slicefromindex1to3:'{concatenated_string[1:4]}'")
else:
print(f"Slicefromindex1toend:'{concatenated_string[1:]}'(stringtooshort for
[1:4])")
iflen(concatenated_string)>=3:
print(f"Slicefirst3characters:'{concatenated_string[:3]}'")
else:
print(f"Sliceallcharacters:'{concatenated_string[:]}'(stringtooshortfor
[:3])")

iflen(concatenated_string)>=2:
print(f"Slicefromindex2toend:'{concatenated_string[2:]}'")
else:
print(f"Slicefromindex0toend:'{concatenated_string[0:]}'(stringtooshort for
[2:])")
iflen(concatenated_string)>1:
print(f"Everysecondcharacter:'{concatenated_string[::2]}'")
else:
print(f"\nConcatenatedstringisempty,skippingslicingdemonstration.")
Output:
Practical-8
Writeaprogramtofindthelargestandsmallestnumberinamatrixentered by the
user.
Code:
defget_matrix_from_user():
rows = int(input("Enter the number of rows:
"))
cols=int(input("Enterthenumberofcolumns:"))

matrix=[]
print("Entertheelementsofthematrixrowbyrow(space-separatednumbers):")

foriinrange(rows):
while True:
try:
row_input=input(f"Row{i+1}:").split()
row = [int(num) for num in row_input]
if len(row) == cols:
[Link](row
) break
else:
print(f"Pleaseenterexactly{cols}numbersforrow{i+1}.")
except ValueError:
print("[Link].")
return matrix

deffind_min_max_in_matrix(matrix)
: ifnotmatrixornotmatrix[0]:
returnNone,None

min_val=matrix[0][0]
max_val=matrix[0][0]

forrowinmatrix:
forelementinrow:
ifelement<min_val:
min_val=element
ifelement>max_val:
max_val=element
return min_val, max_val

user_matrix=get_matrix_from_user(

if user_matrix: print("\
nEnteredMatrix:") for r
in user_matrix:
print(r)

smallest,largest=find_min_max_in_matrix(user_matrix
Practical-8
) if smallest is not None and largest is not None:
print(f"\nSmallestnumberinthematrix:{smallest}")
print(f"Largest number in the matrix: {largest}")
else:
print("\nThematrixisempty.")
else:
print("Nomatrixentered.")

Output:
Practical-9
WriteaprogramtocountthenumberofevenandoddnumbersfromN numbers.
Code:
defcount_even_odd():
n=int(input("Howmanynumbersdoyouwanttoenter?"))

ifn<=0:
print("PleaseenterapositivenumberforN.")
return
numbers=[]

print(f"Enter{n}integers:")

for i in range(n):
whileTrue:
try:
num=int(input(f"Enternumber{i+1}:"))
[Link](num)
break
exceptValueError:
print("[Link].")

even_count=0
odd_count=0

for num in
numbers: ifnum
%2==0:
even_count+=1
else:
odd_count+=1

print(f"\nNumberofevennumbers:{even_count}")
print(f"Number of odd numbers: {odd_count}")

count_even_odd()
Output:
Practical-10
Write a program to find the largest and smallest numbers in the list entered
by the user.
Code:
deffind_min_max_in_list():
input_str=input("Enteralistofnumbersseparatedbyspaces:")

try:
numbers=[float(num)fornumininput_str.split()]
except ValueError:
print("[Link].")
return

ifnotnumbers:
print("Thelistisempty.")
return

smallest=min(numbers)
largest = max(numbers)

print(f"Theenteredlistis:{numbers}")
print(f"Thesmallestnumberinthelistis:{smallest}")
print(f"The largest number in the list is: {largest}")

find_min_max_in_list()

Output:
Practical-11
Writeaprogramtosortalistofelementsusingthebubblesortalgorithm. Code:
defbubble_sort(arr)
: n = len(arr)
for i in range(n):
swapped=False
forjinrange(0,n-i-1):
ifarr[j]>arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]
swapped = True
ifnotswapped:
break
returnarr

input_str=input("Enteralistofnumberstosort(separatedbyspaces):") try:
my_list=[float(num)fornumininput_str.split()]
except ValueError:
print("[Link].")
exit()

ifnotmy_list:
print("[Link].") else:
print(f"Original list: {my_list}")
sorted_list=bubble_sort(my_list.copy())
print(f"Sorted list: {sorted_list}")

Output:
Practical-12
Writeaprogramtoimplementalinearsearchalgorithmtosearchanelement in the
list entered by a user.
Code:
deflinear_search(arr,target):
forindex,elementinenumerate(arr):
if element == target:
returnindex
return -1

input_str=input("Enteralistofelements(separatedbyspaces):")

try:
my_list=[float(num)fornumininput_str.split()]
exceptValueError:
my_list=input_str.split()

ifnotmy_list:
print("[Link].")
else:
print(f"Thelistis:{my_list}")
search_element_str=input("Entertheelementtosearchfor:")

try:
if isinstance(my_list[0], float):
search_element=float(search_element_str
)
else:
search_element=search_element_str
except ValueError:
search_element=search_element_str
result_index=linear_search(my_list,search_element)

ifresult_index!=-1:
print(f"Element'{search_element}'foundatindex{result_index}."
) else:
print(f"Element'{search_element}'notfoundinthelist.")

Output:

You might also like