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

Python Programming Lab Manual 2024

Uploaded by

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

Python Programming Lab Manual 2024

Uploaded by

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

Ex.

no:1

Python Programming Language


2. Analyzing how to use variables, string operator and functions.

Ex.no-2(a) Exchange the value of two variables

Aim:
To write python programs using simple statements and expressions
with exchange the value of two variables

Algorithm:

STEP 1: Read the values of P and Q


STEP 2: temp = P
STEP 3: P = Q
STEP 4: temp = P
STEP 5: PRINT P, Q

Program / Source code:


P = int( input("Please enter value for P: "))

Q = int( input("Please enter value for Q: "))

temp= P
P=Q
Q = temp
print ("The Value of P after swapping: ", P)

print ("The Value of Q after swapping: ", Q)

Output:

Please enter value for P: 5


Please enter value for Q: 7
The Value of P after swapping: 7
The Value of Q after swapping: 5

RESULT:
Thus the program to exchange the value of two variables is executed and the output is obtained.
2. b. Write a program to demonstrate variable and different number data types in
Python.

AIM:
To write a python program to demonstrate variable and different number data types in Python.

ALGORITHM:
Step1:Start.
Step2: read the value
Step3: Read B,C value.
Step4: Check the data type in each input
Step5: find out the data type

Step 6: print the result


Step7:Stop.

PROGRAM / SOURCECODE:
a=5
print("The type of a", type(a))

b = 40.5
print("The type of b", type(b))

c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))

OUTPUT:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

RESULT:
Thus the program to demonstrate variable and different number data types in Python is executed
and the output is obtained.
2.C. PROGRAM TO DEMONSTRATE STRING METHODS/FUNCTIONS

AIM:

To write a python program to demonstrate the following string methods: len(),


capitalize(), upper(), lower(), replace() and split().

ALGORITHM :

Step 1: Start

Step 2: Read a string “hello, World!”

Step 3: Find the length of string using len()

Step 4: Convert the first character of string to uppercase using capitalize()

Step 5: Convert the entire string to upper case using upper()

Step 6: Convert the entire string to lower case using lower()

Step 7: Check whether the string contains substring “hello” and print True or false Step8:

Replace the word “World” with “Python” using replace()

Step9: Split the entire string to words using split()

Step10: Stop

PROGRAM /SOURCE CODE:

# Input a string

input_string = "hello, World!" #

1. Length of the string length =

len(input_string)

print("Length of the string:",length)


# 2. Convert first character to uppercase

cap_string = input_string.capitalize()

print("Capitalized string:",cap_string)

# 3. Convert to uppercase

uppercase_string = input_string.upper()

print("Uppercase:",uppercase_string)
# 4. Convert to lowercase

lowercase_string = input_string.lower()

print("Lowercase:",lowercase_string)

# 5. Check if the string contains a substring using membership operator

substring = "hello"

contains_substring = substring in input_string

print(‘Contains’, substring,’:’, contains_substring)

# 6. Replace a substring with another

new_string = input_string.replace("World", "Python")

print("String after replacement:",new_string)

# 7. Split the string into a list of words

words = input_string.split() print("Words

in the string:",words)

OUTPUT

Length of the string: 13 Capitalized

string: Hello, world! Uppercase:

HELLO, WORLD! Lowercase:

hello, world!

Contains hello: True

String after replacement: hello, Python!

Words in the string: ['hello,', 'World!']

RESULT:
Python program to demonstrate the following string methods : len(), capitalize(),upper(),
lower(), replace() and split() is executed and the output is obtained
3. Creating more in depth working of python like inputting the data.

3.(a) Calculate the Area of a Triangle

AIM:
To write a python program to Calculate the Area of a Triangle.

Algorithm:
STEP 1: Read the values of three sides of a triangle
STEP 2: Calculate‘s’ value
STEP 3: Calculate the area using the formula (s*(s-a)*(s-b)*(s-c))
STEP 4: Find the square root of the result
STEP 5: Print the result
STEP 6: Stop

Program/source code:
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))

c = float(input('Enter third side: '))


s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is:', area)

Output:
Enter first side: 5
Enter second side: 4
Enter third side: 2
The area of the triangle is: 3.799671038392666

RESULT:

Thus The program to find the Area of a Triangle is executed and the output is obtained.
3 . (b) Calculation of Simple Interest and Compound Interest

AIM:

To write a python program to calculate the Simple Interest and Compound Interest

Algorithm:
STEP 1: Read the values of principal amount, no of years and rate of interest
STEP 2: Calculate the simple interest using (principal*time*rate)/100
STEP 3: Calculate the compound interest using principal * ( (1+rate/100)**time - 1)
STEP 4: Display the two values
STEP 5: Stop
Program /source code:
principal = float(input('Enter amount: '))
time = float(input('Enter time: '))
rate = float(input('Enter rate: '))
simple_interest = (principal*time*rate)/100

compound_interest = principal * ( (1+rate/100)**time - 1)


print('Simple interest is:',simple_interest) print('Compound
interest is:' , compound_interest)

Output:
Enter amount: 20000
Enter time: 5
Enter rate: 6.7
Simple interest is: 6700.0
Compound interest is: 7659.994714602134

RESULT:

Thus The program to find the Calculation of Simple Interest and Compound Interest is
executed and the output is obtained.
4. Understanding and working with Boolean and other statements.

4.a. FIND THE MAXIMUM OF A LIST OF NUMBERS

AIM:
To write a python program to find the maximum of a list of numbers.

ALGORITHM :
Step 1: Start.
Step 2: Read the number of element in the list.
Step 3: Read the number until loop n-1.
Step 4: Then Append the all element in list
Step 5: Go to STEP-3 up to n-1.
Step 6: Sort the listed values. Step
Step 7: Print the a[n-1] value.
PROGRAM/SOURCE CODE:
a=[ ]
n=int(input("Enter number of elements:")) for i in
range(1,n+1):
b=int(input("Enter element:"))
a.append(b)

a.sort()

print("Largest element is:",a[n-1])

OUTPUT :
Enter number of elements:5

Enter element: 3

Enter element:2

Enter element:1

Enter element:5

Enter element:4

Largest element is: 5

RESULT:
The program to find the Maximum of a List of numbers is executed and the output is obtained.
4. (b) Sum of digits of a number

AIM:
To write a python program to find the sum of digits of a numbers.

Algorithm:
Step 1: Enter the value and store it in a variable.
Step 2: The while loop is used and the last digit of the number is obtained by using the
modulus operator.
Step 3: The digit is added to another variable each time the loop is executed.

Step 4: This loop terminates when the value of the number is 0.


Step 5: The total sum of the number is then printed.
Step 6: Stop

Program/source code:
n=int(input("Enter a number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)

Output:
Enter a number:4 5 6
The total sum of digits is: 15

RESULT:

The program to find the sum of digits of a numbers is executed and the output is obtained.
4 (c) Printing Fibonacci Series

AIM:
To write a python program to find the Fibonacci Series of a numbers.
Algorithm:
Step 1: Start
Step 2: Declare variables i, t1,t2 , sum
Step 3: Initialize the variables, t1=0, t2=1, and sum=0
Step 4: Enter the number of terms of Fibonacci series to be printed
Step 5: Print First two terms of series
Step 6: Use loop for the following steps
-> sum=t1+t3
-> t1=t2
-> t2=sum
-> increase value of i each time by 1
-> print the value of show
Step 7: Stop

Program/source code:
n = int(input("Enter the value of 'n': "))
t1 = 0
t2 = 1
sum = 0
count = 1

print("Fibonacci Series: ")


while(count <= n):
print(sum, end = " ")

count += 1
t1 = t2
t2 = sum
sum = t1 + t2

Output:

Enter the value of 'n': 7


Fibonacci Series:
0112358
RESULT:

The program to find the Fibonacci Series of a numbers is executed and the output is obtained.

4. (d) Prime Numbers in a range


AIM:

To write a python program to find the Prime Numbers in a range

Algorithm:

Step 1: Start
Step 2: Read lower and upper range
Step 3: Using a for loop, iterate on all the numbers in the range
Step 4 : For each number, check if its prime or not
Step 5 : If the number is prime, print
Else skip
Step 6 : Stop

Program / source code:


lower = 900
upper = 1000
print("Prime numbers between", lower, "and", upper, "are:")
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:
Prime numbers between 900 and 1000 are:
907
911
919
929
937
941
947
953
967
971
977
983
991
997
Result:
Thus, the program using conditionals and loops has been executed and verified.
5., Understanding to provide the use of pandas’ library for data analysis.

Program using pandas :

AIM:

To create data frames using pandas in python.

ALGORITHM:
1. Start the Program.
2. Import numpy and pandas
3. Create a dictionary with student name, marks of three subjects
4. Convert the dictionary to a data frame
5. Print the data frame
6. Stop

PROGRAM:
import numpy as np
import pandas as pd
mydictionary = {'names': ['Somu', 'Kiku', 'Amol', 'Lini'],
'
‘physics': [68, 74, 77, 78],
'chemistry': [84, 56, 73, 69],
'algebra': [78, 88, 82, 87]}

#create dataframe using dictionary


df_marks = pd.DataFrame(mydictionary)
print(df_marks)

OUTPUT:
names physics chemistry algebra

0 Somu 68 84 78
1 Kiku 74 56 88

2 Amol 77 73 82
3 Lini 78 69 87

Result:
Thus, the pandas program has been executed and verified successfully.
6. Understanding how to deal with different type of errors that one can encounter while working

with python.

Different type of errors

AIM:
To write a python program to deal with different type of errors that one can encounter
while working with python.

Algorithm:

Step 1: Start
Step 2: Read the values
Step 3: Using a for loop, iterate on all the numbers in the
range

Step 4 : For each value, check if its error or not


Step 5 : If the error is occur, print
and correct the errors
Step 6 : Stop

Program /source code:


Syntax error:

X=10

If x==10

Print(“x is 10”)

Output:

If x == 10
^
SyntaxError: expected ':'

Name error:

def calculate_sum(a, b):


total = a + b
return total

x=10
y=15
z = calculate sum(x,w)
print(z)

output:

Z = calculate_sum(x, w)
^
NameError: name 'w' is not defined

Type error:

X =” 10”

Y= 5

Z=X+Y

Print(Z)

Output:

Z = x + y
~~^~~
TypeError: can only concatenate str (not "int") to str

Index error:

my_list[100,200,300,400,500]

Print(my_list[6])

Output:

print(my_list[p
~~^~~
IndexError: list index out of range

Result:

Thus the python program to deal with different type of errors that one can encounter
while working with python successfully.
7.Understanding and finding how to deal with miscellaneous things in python and regression

analysis with the help of a use case.

#Three lines to make our compiler able to draw:

import sys

import matplotlib

matplotlib.use('Agg')

import matplotlib.pyplot as plt

from scipy import stats

x = [5,7,8,7,2,17,2,9,4,11,12,9,6]

y = [99,86,87,88,111,86,103,87,94,78,77,85,86]

slope, intercept, r, p, std_err = stats.linregress(x, y)

def myfunc(x):

return slope * x + intercept

mymodel = list(map(myfunc, x))

plt.scatter(x, y)

plt.plot(x, mymodel)

plt.show()

#Two lines to make our compiler able to draw:

plt.savefig(sys.stdout.buffer)

sys.stdout.flush()
OUTPUT

Result:

Thus, the matplotlib program has been executed and verified successfully
8.Understanding the try, throw, catch, throwing an exception, catching an exception.

AIM:
To write a python program to deal with different exception that one can encounter
while working with python.

Algorithm:

Step 1: Start
Step 2: Read the values
Step 3: Using a for loop, iterate on all the numbers in the
range

Step 4 : For each value, check if its error or not


Step 5 : If and for loop use the
exception is occur, print
and correct the output
Step 6 : Stop

Program /source code:

# define Python user-defined exceptions

class InvalidAgeException(Exception):

"Raised when the input value is less than 18"

pass

# you need to guess this number

number = 18

try:

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

if input_num < number:

raise InvalidAgeException

else:

print("Eligible to Vote")

except InvalidAgeException:
print("Exception occurred: Invalid Age")

OUTPUT:

Result:

Thus the program to deal with try, throw, catch, throwing an exception, catching an

exception while working with python successfully.


9.Understanding the exploratory data analysis and correlation matrix and the visualization

using matplotlib.

AIM:

To create data frames using matplotlib in python.

ALGORITHM:
1. Start the Program.
2. Import numpy , matplotlib and pandas.

3. Create a dictionary with student name, marks of three subjects

4. Convert the dictionary to a data frame


5. Print the data frame
6. Stop

DATA SETS:

Program /source code:

import pandas as pd
import matplotlib.pyplot as plt

import seaborn as sns

full_health_data = pd.read_csv("dataset.csv", header=0, sep=",")

correlation_full_health = full_health_data.corr()

axis_corr = sns.heatmap(

correlation_full_health,

vmin=-1, vmax=1, center=0,

cmap=sns.diverging_palette(50, 500, n=500),

square=True

plt.show() OUT PUT:


Result:
Thus, the matplotlib program has been executed and verified successfully.

You might also like