Python Programming
Python Programming
Aim : Write a python program to find largest element among three numbers
Algorithm:
Step 1:Start
Step 4:Print the number which is greater than the other two numbers as the greatest number
Flowchart:
Program:
Largest=num1
Largest=num2
else:
Largest=num3
Output:
UNIT-1 EXPERIMENT-2
Algorithm:-
Step-1: start.
Step-2: Take the input values from the user for lower interval and upper interval.
step-3: By using the arithmetic operator(%) to find the prime numbers with in the intervals.
step-5: stop.
Flowchart:-
Start
Read n
Set i =1
i<=n
count==2
n%==0
Count=count+1
display n is prime Display not
prime
i=i+1
stop
Program:-
lower = 900
upper 1000
if num > 1:
if (num% i)=0
break
else:
print(num)
Output:-
907
911
919
929
937
941
947
953
967
971
977
983
991
997
Result:-
Unit-1: Experiment 3
Algorithm :
Step-1 : Start.
Step-5 : Stop.
Flow chart :
Start
Program :
x=5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
Output :
x = 10
y=5
UNIT-1: EXPERIMENT 5
ALGORITHM:
Step 1: start
(a+bi)+(c+di)
(a+bi) * (c+di)
(ac+adi+bci-bd)
(ac-bd+(ad+bc)i)
Step 9: End
FLOWCHART:
SS
Start
Input C1 ,C2
Add=C1+C2
Multiply=C1*C2
Print
Add
Multiply
End
PROGRAM:
print('PRODUCT',product)
OUTPUT:
SUM = (9+18j)
PRODUCT (-54+72j)
RESULT:
UNIT-1: Program 6
Algorithm:
Step 1: Start
Required
Print num*i=Result
Increment i by 1
Step 7: End!
Flow chart:
Start
I=1
If
i<=10
Print i*n
i=i+1
Stop
Program:
def multiplication_table(n):
for i in range(1,11):
print(f”{n}x{i}={n*i}”)
#Output
Multiplication_table(n)
Output:
enter a number16
16x1=16
16x2=32
16x3=48
16x4=64
16x5=80
16x6=96
16x7=112
16x8=128
16x9=144
16x10=160
Result:
Unit-2: Experiment 1
Algorithm :
Step -1 : Start
Step-7 : Stop.
Flow chart :
Start
def name()
return
“python”,”programming”
print(name())
name_1,name_2 = name()
print(name_1,name_2)
Stop
Program :
def name():
return "python","programming"
print(name())
print(name_1, name_2)
Output :
('python', 'programming')
python programming
UNIT-2:
PROGRAM-2
Algorithm:
Step-1: Start.
FLOWCHART:
Start
Student(firstname,
lastname=’Antony’,
standard=’fifth’)
Print (firstname,lastname,studies
in,standard,’standard’)
Print (firstname,lastname,studies
in,standard,’standard’)
Student(‘mark’)
Student(‘mark’,’
Hari’,’sixth’)
Student(firstname,
Student(‘mark’,’
astname=’Antony
l ’,
’)
standard=’fift
meclem h’)
Stop
PROGRAM:
def student(firstname, lastname ='Antony', standard ='Fifth'): print(firstname, lastname, 'studies in',
standard, 'Standard') student('Mark')
OUTPUT:
Mark Antony studies in Fifth Standard Mark Hari studies in Sixth Standard
RESULT:
UNIT:2
EXPERIMENT 3
AIM: Write a program to find length of the string without using any library functions.
ALGORITHM:
STEP 1: Start
. Go to step 7
STEP 5: Remove: Remove the first character from the string: s=s[1:]
STEP 7: Output: Print the value of count as the length of the string
STEP 8: End
FLOWCHART:
Start
Initialize
Count=0
String is empty
NO
Yes
Increment Count
Print Count
Stop
PROGRAM:
def string_length(name):
length = 0
OUTPUT: 17
RESULT:
A program to find length of the string without using any library functions is executed.
UNIT-2: Experiment 4
AIM: To write a python program that checks if a given substring is present in a main string.
ALGORITHM:
Step 1:start
Step 4:Use (in) operator to see if the substring is present in the main
string or NOT.
Step 8:stop!
Flow-chart:
START
Input(‘enter main
string”)
Input(“enter
substring”)
If substring
in main
string:
YES NO
stop
PROGRAM:
substring=(input("enter substring:"))
print(“does”,substring,”exist in”,string,”?”)
#output
if substring in string:
print(“string found:”,substring)
else:
OUTPUT:
enter substring:america
RESULT:
Unit-2
Experiment-5
SOFTWARE REQUIREMENT:Python(3.10)
ALGORITHM:
Step-1:start
Step-2:initialise thelist
Step-6:stop
FLOWCHART:
start
Addition operation
Insertion operation
Slicing operation
PROGRAME:-
def main():
"))
my_list.append(element_to_add)
"))
my_list.insert(index_to_insert, element_to_insert)
else:
len(my_list):
sliced_list = my_list[start_index:end_index]
else:
if __name__ == "__main__":
main()
RESULT:
AIM: To write a program to perform any 5 built-in functions by taking any list
SYSTEM REQUIRED: 16GB RAM, INTEL i5-10500 CPU@3.10GHZ
SYSTEM CONFIGURATION: Python (3.11.4)
ALGORITHM:
STEP 1: Start
STEP 2: Input the list contain integers, strings, or a mix of both.
Step 3: Add an element at the end of list.
STEP 4: Remove the first occurrence of a specified element from the list.
STEP 5: Sort the list in ascending order.
STEP 6: Count the occurrences of a specified element in the list.
STEP 7: Reverse the element of the list.
STEP 8: Stop.
FLOW CHART:
Start
My _list
My list appends(3)
Print(“After
appends(3)”;)
My list remove(s)
Print(“After
remove(s)”)
My list sort( )
Print(“After
PROGRAM:
#Sample list
my_list = [5, 2, 9, 1, 5, 6]
my_list.append (3)
my_list.remove (5)
my _list.sort ()
my _list.reverse ()
OUTPUT:
UNIT-3 PROGRAME-1
AIM:-
Write a program to create tuples (name, age, address, college) for at least two members and
Concatenate the tuples and print the concatenated tuples.
SYSTEM CONFIGURATION:-
Python 3.11.4
ALGORITHM :-
FLOWCHART:-
start
process
decision
process
end
PROGRAM:-
def create_tuples(members):
member_tuples = []
member_tuples.append(member_tuple)
return member_tuples
members = [
concatenated_tuples = create_tuples(members)
print(concatenated_tuples)
OUTPUT:-
[(‘Alice’, 20, ‘Hyderabad’, ‘IIT Hyderabad’), (‘Bob’, 22, ‘Bangalore’, ‘IIM Bangalore’)
RESULT:-
Program to create tuples (name, age, address, college) for at least two members and concatenate
Aim: To write a program to count the number of vowels in a string without control flow.
Algorithm:
Step 1: Start
Step 3: Use map(input_string.count, vowels) to count occurrences of each vowel in the input string.
Step 4: Apply sum() to the result of map() to get the total number of vowels.
Step 5: Return the total vowel count from the function.
Step 7: Call count_vowels(input_string) and print the total number of vowels in the string.
Step 8: Stop
Program:
def count_vowels(input_string):
vowels = "aeiouAEIOU"
Start
Use sum(map(input_string.count,
vowels)) function to calculate the
total number of vowels in the
input string.
Stop
UNIT-3 PROGRAM -4
Algorithm:
START
Declare an existing
dictionary my_dict
Print my_dict to
display output
STOP
Program:
my_dict={'hello':1,'world':2}
newkey=input('Enter a key:')
my_dict[newkey]=newval
print(my_dict)
output:
{ 'hello': 1,'world': 2}
Unit-3: Experiment 5
Aim : To write a python program to sum all the items in a given dictionary.
Algorithm :
Step-1 : Start
Flowchart :
Start
total_sum =
sum_dictionary_items(my_dictionary)
Program :
Output :
zUNIT-4: PROGRAM-1
AIM: Program to sort words in a file and put them in another file. The output file should have only
lower-case words, so any upper-case words form source must be lowered
Algorithm:
start
Open source
file
Read words
from source file
Convert word to
lowercase
Store lowercase word
in list
Sort words
end
Program:
def sort_words_in_file(input_file,output_file):
try:
Words=file.read().split()
Sorted_words=sorted(lower_case_words)
File.write(word+’\n’)
Except exception as e:
Input_file=’source.txt’
Output_file=’sorted_words.txt’
Sort_words_in_file,(input_file,output_file)
Output:
Hello World
hello world!
Result: Program to sort words in a file and put them into another file. The output file should have
only lower-case words,so any upper-case words from source must be lowered is executed.
Unit-4: Experiment 3
Aim : To python program to compute the number of characters, words and lines in a file
Algorithm :
Step-1 : Start
Flowchart :
Start
Open file
Content=file.read()
Calculate number
of word
Calculate number
of characters
print(f'Numbercharacters:
Error handling
STSTOP
Program :
def compute_file_statistics(file_path):
lines = content.splitlines()
num_lines = len(lines)
words = content.split()
num_words = len(words)
num_characters = len(content)
except Exception as e:
# Example usage
compute_file_statistics(file_path)
Output :
Words: 5
Characters: 16
Lines: 1v
Unit-4: Experiment 4
Aim : To create, display, append, insert and reverse the order of the items in an array by using
Python.
Algorithm :
Step-1 : Start
Step-7 : Stop
FLOWCHART:-
Start A
my_array.insert(1, 15)
my_array = []
my_array.reverse()
my_array.append(10)
my_array.append(20)
my_array.append(30)
Stop
A
Program :
def array_operation():
my_array = []
my_array.append(10)
my_array.append(20)
my_array.append(30)
my_array.insert(1, 15)
my_array.reverse()
array_operation()
Output :
Empty array: []
EXPERIMENT-5
ALGORITHM :
Step2 : Make sure the number of columns in A is equal to the number of rows in B
Step3 : For each element in the product matrix, multiply each element in a row of A by the
Step5 : Put the calculated elements in the correct positions to form the product matrix
Step6 : Take the first row of the matrix and make it the first column of the new transposed.
matrix
Step7 : Take the second row and make it the second column of the new transposed matrix
Step8 : The transpose of the sum of two matrices is equal to the sum of the transposes of the
individual matrices.
:
at[i][j]=a[j][i]
Print resultant
transpose matrix
STOP
PROGRAM :
rows = len(matrix_a)
cols = len(matrix_a[0])
for i in range(rows):
for j in range(cols):
return result
def transpose_matrix(matrix):
rows = len(matrix)
cols = len(matrix[0])
for i in range(rows):
for j in range(cols):
transposed[j][i] = matrix[i][j]
return transposed
cols_a = len(matrix_a[0])
rows_b = len(matrix_b)
cols_b = len(matrix_b[0])
if cols_a != rows_b:
rows in B.")
for i in range(rows_a):
for j in range(cols_b):
return result
def display_matrix(matrix):
for row in matrix:
print(row)
def main():
matrix_a = [
[1, 2, 3],
[4, 5, 6]
matrix_b = [
[7, 8, 9],
print("Matrix A:")
display_matrix(matrix_a)
print("\nMatrix B:")
display_matrix(matrix_b)
# Add matrices
display_matrix(added_matrix)
# Transpose matrix A
transposed_matrix_a = transpose_matrix(matrix_a)
display_matrix(transposed_matrix_a)
# Transpose matrix B
transposed_matrix_b = transpose_matrix(matrix_b)
display_matrix(transposed_matrix_b)
# Multiply matrices
matrix_c = [
[1, 2],
[3, 4],
[5, 6]
display_matrix(matrix_c)
display_matrix(multiplied_matrix)
main()
OUTPUT :
Matrix A:
[1, 2, 3]
[4, 5, 6]
Matrix B:
[7, 8, 9]
Transposed Matrix A:
[1, 4]
[2, 5]
[3, 6]
Transposed Matrix B:
[7, 10]
[8, 11]
[9, 12]
[1, 2]
[3, 4]
[5, 6]
[22, 28]
[49, 64]
UNIT-4: Experiment 6
Aim : To create a class that represents a shape. Include methods to calculate its area and perimeter.
Implement subclasses for different shapes like circle, triangle and square using Python.
Algorithm:
Step 1: start
Shape
Perimeter() methods
Perimeter() methods
Step 7: stop
Flow-chart:
start
Circle: Area=π*r^2
Perimeter=2*π*r
Triangle: Area=1/2*b*h
Perimeter=(sum of all
sides)
Square: Area=s*s
Perimeter=4*s
stop
PROGRAM:
class circle():
def _init_(self,r):
self.radius=r
def area(self):
return self.radius**2*3.14
def perimeter(self):
return 2*self.radius*3.14
new_circle=circle(5) print(new_circle.area())
print(new_circle.perimeter())
class triangle():
def _init_(self,a,b,c):
self.side1=a
self.side2=b
self.side3=c
def perimeter(self):
return self.side1+self.side2+self.side3
def area(self):
s=(self.side1+self.side2+self.side3)/2
print(new_triangle.perimeter())
print(new_triangle.area())
class square():
def _init_(self,a):
self.side=a
def perimeter(self):
return self.side*4
def area(self):
return self.side**2
new_square=square(1)
print(new_square.perimeter())
print(new_square.area())
OUTPUT:
78.5
31.400000000000002
0.0
UNIT-5 EXPERIMENT-1
AIM: To write a Python program to check whether a JSON string contains complex object or not.
HARDWARE REQUIRED:
16GB RAM, INTEL i5-10500 CPU @ 3.10GHZ
SOFTWARE CONFIGURATION:
Python (3.12.3)
ALGORITHM:
Step-3: If it is a list, look for any items that are dictionaries or lists.
Step-4: If a dictionary or list is found within the object, return "Contains complex object."
Step-6: Stop.
Flowchart : Start
Import JSON
If yes
Print false
Print true
Is json
complex
Stop
PROGRAM:
import json
def contains_complex_object(obj):
if isinstance(obj, dict):
for value in obj.values():
return True
return True
return False
def check_json_for_complex(json_str):
try:
obj = json.loads(json_str)
if contains_complex_object(obj):
else:
except json.JSONDecodeError:
OUTPUT:
AIM :
System Specilizations :
Software required :
Python (3.12.3)
Algorithm :
Step 1 : Start
Step 4 : Create a 2D array using np.array() with a nested list and display it.
Step 5 : Create a 3D array using np.array() with a nested list of lists and display it.
Step 6 : Create an array with a specified data type using np.array() and dtype parameter, and display
it.
Step 7 : End
Flowchart :
Start
Create 1D Array
Create 2D Array
Create 3D Array
End
Program :
import numpy as np
# Creating a 1D array
print("1D Array:")
print(array_1d)
# Creating a 2D array
print("\n2D Array:")
print(array_2d)
# Creating a 3D array
print("\n3D Array:")
print(array_3d)
print(array_dtype)
Output :
1D Array:
[1 2 3 4 5]
2D Array:
[[1 2 3]
[4 5 6]]
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
[1. 2. 3. 4.]
Algorithm :
Step-1 : Start
Step-3 Retrieve the number of dimensions (ndim) of arr and print it.
Step-5 : Retrieve the total number of elements (size) of arr and print it.
Step-6 : Retrieve the data type (dtype) of the elements of arr and print it.
Step-7: Stop.
Flowchart :
start
Initialize 2D array
Retrieve ndim
Print ndim
Retrieve shape
Print shape
Retrieve size
Print size
Retrieve dtype
Print dtype
stop
Program:
import numpy as np
Output :
Result : Python program to demonstrate use of ndim, shape, size, dtype is executed.
UNIT-5 PROGRAME-4
AIM: python program to demonstrate basic slicing, integer and Boolean indexing.
SYSTEM HARDWARE AND SOFTWARE REQUIRED: 16GB RAM, intel i5-10500 CPU @ 3.10GHz
ALGORITHM:
STEP 1: start
STEP 4: access the elements using integer indexing and Boolen indexing
PROGRAM:
import numpy as np
[6, 7, 8, 9, 10],
print("Original Array:")
print(arr)
print(sliced_array)
print(sliced_array2)
print("\nInteger Indexing:")
element = arr[1, 3]
print("\nBoolean Indexing:")
FLOW CHART : START
Import numpy as np
Create an array
Boolean indexing
END
OUTPUT:
Original Array:
[[10 20 30]
[40 50 60]
[70 80 90]]
[[10 20]
[40 50]]
Integer Indexing:
[60 70 80 90]
Unit-5: Experiment 5
Aim : Python program to find min, max, sum cumulative sum of array.
Algorithm :
Step-1 : Start
Step-12: Stop.
Flowchart :
Start
Import numpy as np
Arr = np.array([10,20,30,40,50])
Min = np.min(arr)
Max = np.max(arr)
Sum = np.sum(arr)
print(min,max,sum,cum sum)
Stop
Program:
Import numpy as np
Min_value = np.min(arr)
Max_value = np.max(arr)
total_sum = np.sum(arr)
Cumulative_sum = np.cumsum(arr)
Output :
Minimum value : 10
Maximum value : 50
Result : Python program to find min, max, sum, cumulative sum of array is executed.
UNIT-5 EXPERIMENT-6
AIM: Create a dictionary with at least five keys and each key represent value as a list where This list
contains at least ten values and convert this dictionary as a panda’s data frame and explore the data
through the data frame as follows: a) Apply head () function to the panda’s data frame b) Perform
various data selection operations on Data Frame.
STEP-1: Start
STEP-2: Create Dictionary with at least five keys. Each key will represent a value which is a list
containing at least ten values
STEP-3: Convert Dictionary to panda’s data frame by using pd. Data Frame () function
STEP-4: Apply the head () Function to display the first five rows
STEP-5: Perform data selection operations (select specific rows, columns in data frame by applying
various indexing techniques).
STEP-6: Stop
Flow chart:
import pandas as pd
# Create a dictionary with five keys and lists as values
data =
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'B': [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
'C': [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
'D': [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
'E': [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
df = pd.DataFrame(data)
# Explore the data using pandas functions
# a) Apply head() function to display the first few rows of the DataFrame
print("First few rows using head():")
print(df.head(), "\n") # By default, head() shows the first 5 rows
# b) Perform various data selection operations on DataFrame
# Select a specific column (e.g., column 'A')
print("Column 'A':")
print(df['A'], "\n")
# Select multiple columns (e.g., columns 'A' and 'C')
print("Columns 'A' and 'C':")
print(df
'A', 'C'
, "\n")
# Select specific rows (e.g., first 3 rows)
print("First 3 rows:")
print(df.iloc[:3], "\n")
# Select rows based on condition (e.g., values in column 'B' greater than 15)
print("Rows where values in 'B' are greater than 15:")
‘B’
15
, "\n")
import pandas as pd
data = {
'B': [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
'C': [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
'D': [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
'E': [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
df = pd.DataFrame(data)
# a) Apply head() function to display the first few rows of the DataFrame
print("Column 'A':")
print(df['A'], "\n")
print("First 3 rows:")
print(df.iloc[:3], "\n")
# Select rows based on condition (e.g., values in column ‘B’ greater than 15)
Print(df.loc[4], “\n”)
# Select a specific element using `iloc` (e.g., element at row 2, column ‘C’)
OUTPUT:
ABCDE
0 1 11 21 31 41
1 2 12 22 32 42
2 3 13 23 33 43
3 4 14 24 34 44
4 5 15 25 35 45
Column ‘A’:
01
12
23
34
45
56
67
78
89
9 10
0 1 21
1 2 22
2 3 23
3 4 24
4 5 25
5 6 26
6 7 27
7 8 28
8 9 29
9 10 30
First 3 rows:
ABCDE
0 1 11 21 31 41
1 2 12 22 32 42
2 3 13 23 33 43
ABCDE
5 6 16 26 36 46
6 7 17 27 37 47
7 8 18 28 38 48
8 9 19 29 39 49
9 10 20 30 40 50
A5
B 15
C 25
D 35
E 45
RESULT: a dictionary with at least five keys and each key represent value as a list where this list
contains at least ten values and convert this dictionary as a pandas data frame is executed.
UNIT-5
EXPERIMENT-7:
Aim: TO create a data visualization tool that enables users to select two columns from a dataset and
generate scatter plots, line plots, and line plots with annotations to observe the change in one
attribute with respect to the other.
Algoritham:
Step 1: Start.
Step 2: Import Necessary Libraries and load the Dataset Load the dataset into a pandas DataFrame.
Step 3: Select Two Attributes Create a Scatter Plot Use matplotlib to create a scatter plot with the
selected attributes.
Step 4: Label the Axes and Add a Title and create a Line Plot.
Step 5: Create a Line Plot with Annotations and add annotations to label each data point. Display the
Plots.
Step 6: End.
Flow chart:
import pandas as pd
data =
[1, 2, 3, 4, 5],
df = pd.DataFrame(data)
column1 = 'A'
column2 = 'B'
plt.figure(figsize=(10,6))
plt.scatter(df[column1],
df[column2], label=f'
column2
vs
column1
', marker='o')
plt.xlabel(column1)
plt.ylabel(column2)
plt.title(f'Line plot of
Column2
vs
')
column1
plt.legend()
Program:
import pandas as pd
df = pd.DataFrame(data)
# Select two columns
column1 = 'A'
column2 = 'B'
plt.figure(figsize=(10,6))
plt.xlabel(column1)
plt.ylabel(column2)
plt.legend()
plt.show()
plt.figure(figsize=(10,6))
plt.xlabel(column1)
plt.ylabel(column2)
plt.legend()
plt.show()
Output: