INDEX
S. No. Name of the Experiment Page No. Signature
Develop a program to find the largest element among three
1
numbers
2 Develop a program to display all prime numbers within an interval
Develop a program to swap two numbers without using a
3
temporary variable
4 Demonstrate various operators in Python with suitable examples
5 Develop a program to add and multiply complex numbers
6 Develop a program to print multiplication table of a given number
7 Develop a program to define a function with multiple return values
8 Develop a program to define a function using default arguments
Develop a program to find the length of the string without using
9
any library functions
Develop a program to check if the substring is present in a given
10
string or not
Develop a program to perform addition, insertion, and slicing
11
operations on a list
Develop a program to perform any 5 built-in functions by taking
12
any list
Develop a program to create and concatenate tuples and print the
13
result
Develop a program to count the number of vowels in a string (No
14
control flow allowed)
Develop a program to check if a given key exists in a dictionary or
15
not
Develop a program to add a new key-value pair to an existing
16
dictionary
17 Develop a program to sum all the items in a given dictionary
Develop a program to sort words in a file and store them in
18
another file
19 Develop a program to print each line of a file in reverse order
20 Develop a program to count characters, words, and lines in a file
Develop a program to create, display, append, insert and reverse
21
the items in an array
22 Develop a program to add, transpose, and multiply two matrices
Develop a program to create a class representing shapes and
23
compute area and perimeter
Develop a Python program to check whether a JSON string
24
contains complex object or not
25 Demonstrate NumPy array creation using array() function
26 Demonstrate use of ndim, shape, size, and dtype in NumPy
27 Demonstrate basic slicing, integer and Boolean indexing
Develop a program to find min, max, sum, and cumulative sum of
28
array
Prepare a dictionary, convert to pandas DataFrame and explore
29
data using head() and selections
Plot scatter graph between two attributes from DataFrame using
30
Matplotlib
Experiment-1
Aim: Develop a program to find the largest element among three numbers.
Description:
➢ input() : Reads input from user.
➢ int() : Converts input string to integer.
➢ if- elif- else : Conditional statements for comparison.
➢ print() : Displays output.
Program:
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
c = int(input('Enter third number: '))
if a >= b and a >= c:
print('Largest is', a)
elif b >= a and b >= c:
print('Largest is', b)
else:
print('Largest is', c)
Output:
Result: Hence, the program was executed successfully.
Experiment-2
Aim: Develop a Program to display all prime numbers within an interval.
Description:
➢ input() : Reads input.
➢ int() : Converts to integer.
➢ for : Looping.
➢ range() : Generates sequence.
➢ if : Checks divisibility.
➢ print() : Displays prime numbers.
Program:
start = int(input('Enter start: '))
end = int(input('Enter end: '))
for num in range(start, end+1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
print(num)
Output:
Result: Hence, the program was executed successfully.
Experiment-3
Aim: Develop a program to swap two numbers without using a temporary variable.
Description:
➢ input(): Reads input.
➢ int(): Converts string to integer.
➢ Tuple assignment (`a, b = b, a`): Swaps values.
➢ print(): Displays result.
Program:
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
a, b = b, a
print('After swapping: a =', a, ', b =', b)
Output:
Result: Hence, the program was executed successfully.
Experiment-4
Aim: Demonstrate various operators in Python with suitable examples.
Description:
➢ `+`, `-`, `*`, `/`: Arithmetic operators.
➢ `>`, `==`: Relational operators.
➢ `and`: Logical operator.
➢ `&`, `|`: Bitwise operators.
➢ `:=`: Assignment operator.
➢ `in`: Membership operator.
➢ `is`: Identity operator.
Program:
a, b = 10, 5
print('Arithmetic:', a+b, a-b, a*b, a/b)
print('Relational:', a > b, a == b)
print('Logical:', a > 0 and b > 0)
print('Bitwise:', a & b, a | b)
print('Assignment:', (a := a+1))
print('Membership:', 5 in [1,2,3,4,5])
print('Identity:', a is b)
Output:
Result: Hence, the program was executed successfully.
Experiment-5
Aim: Develop a program to add and multiply complex numbers.
Description:
➢ complex(): Creates complex numbers.
➢ `+`: Adds two complex numbers.
➢ `*`: Multiplies two complex numbers.
➢ `print(): Displays result.
Program:
a = complex(2, 3)
b = complex(1, 4)
print('Addition:', a+b)
print('Multiplication:', a*b)
Output:
Result: Hence, the program was executed successfully.
Experiment-6
Aim: Develop a program to print multiplication table of a given number.
Description:
➢ input(): Reads number.
➢ int(): Converts input.
➢ for: Loop for table.
➢ range(): Generates sequence 1–10.
➢ print(): Displays table.
Program:
n = int(input('Enter a number: '))
for i in range(1, 11):
print(n, 'x', i, '=', n*i)
Output:
Result: Hence, the program was executed successfully.
Experiment-7
Aim: Develop a program to define a function with multiple return values.
Description:
➢ def: Used to define a function, a reusable block of code.
➢ return: Sends back multiple values at once, grouped as a tuple.
➢ print(): Displays the output returned by the function on the screen.
Program:
def calculator(a, b):
add = a + b
sub = a - b
mul = a * b
if b==0:
div = a / b
else:
div= “Undefined”
return add, sub, mul, div
def main():
x = float(input("Enter first number: "))
y = float(input("Enter second number: "))
add, sub, mul, div = calculator(x, y)
print(f"Addition: {add}")
print(f"Subtraction: {sub}")
print(f"Multiplication: {mul}")
print(f"Division: {div}")
main()
Output:
Result: Hence, the program was executed successfully.
Experiment-8
Aim: Develop a program to define a function using default arguments.
Description:
➢ def: Used to create a function with optional/default values.
➢ Default parameter: If no value is given while calling, it uses the default one.
➢ print(): Prints the result of the function call.
Program:
def greet(name='Guest'):
print(f'Hello, {name}!')
greet()
greet('Kiran')
Output:
Result: Hence, the program was executed successfully.
Experiment-9
Aim: Develop a program to find the length of the string without using any library
functions.
Description:
➢ input(): Takes text input from the user.
➢ for: Loops through each character in the string.
➢ Counter variable: Adds 1 for every character to count total length.
➢ print(): Displays the total number of characters.
Program:
string = input('Enter string: ')
count = 0
for char in string:
count += 1
print('Length:', count)
Output:
Result: Hence, the program was executed successfully.
Experiment-10
Aim: Develop a program to check if the substring is present in a given string or not.
Description:
➢ input(): Takes text input from the user.
➢ for: Loops through each character in the string.
➢ Counter variable: Adds 1 for every character to count total length.
➢ print(): Displays the total number of characters.
Program:
string = input('Enter string: ')
substr = input('Enter substring: ')
if substr in string:
print('Substring found')
else:
print('Substring not found')
Output:
Result: Hence, the program was executed successfully.
Experiment-11
Aim: Develop a program to perform the given operations on a list:
i. addition ii. Insertion iii. slicing
Description:
➢ list: Stores multiple items in one variable.
➢ append(): Adds an item at the end of the list.
➢ insert(): Adds an item at a specific position.
➢ slicing: Extracts a portion of the list.
➢ print(): Shows the updated or sliced list.
Program:
lst = [1, 2, 3]
lst.append(4)
lst.insert(1, 5)
sliced = lst[1:3]
print('Updated list:', lst)
print('Sliced part:', sliced)
Output:
Result: Hence, the program was executed successfully.
Experiment-12
Aim: Develop a program to perform any 5 built-in functions by taking any list.
Description:
➢ len(): Counts how many items are in the list.
➢ max(): Finds the biggest item in the list.
➢ min(): Finds the smallest item in the list.
➢ sum(): Adds up all the numbers in the list.
➢ sorted(): Gives a new list with items arranged in order.
Program:
lst = [3, 1, 4, 2]
print('Length:', len(lst))
print('Sorted:', sorted(lst))
print('Max:', max(lst))
print('Min:', min(lst))
print('sum:', sum(lst))
Output:
Result: Hence, the program was executed successfully.
Experiment-13
Aim: Develop a program to create tuples (name, age, address, college) for at least two
members and concatenate the tuples and print the concatenated tuples.
Description:
➢ tuple(): Used to create a group of values that cannot be changed.
➢ +: Joins two tuples into one.
➢ print(): Shows the new combined tuple.
Program:
t1 = ('Steve', 22, 'NY')
t2 = (‘Jobs’, 23, 'LA')
t = t1 + t2
print('Concatenated tuple:', t)
Output:
Result: Hence, the program was executed successfully.
Experiment-14
Aim: Develop a program to count the number of vowels in a string (No control flow
allowed).
Description:
➢ input(): Takes a string from the user.
➢ for: Goes through each character one by one.
➢ in: Checks if the character is a vowel.
➢ Counter variable: Increases whenever a vowel is found.
➢ print(): Shows total number of vowels.
Program:
string = 'hello world'
vowels = 'aeiou'
count = sum(1 for char in string if char in vowels)
print('Number of vowels:', count)
Output:
Result: Hence, the program was executed successfully.
Experiment-15
Aim: Develop a program to check if a given key exists in a dictionary or not.
Description:
➢ dict: Stores data as key-value pairs.
➢ in: Checks if a specific key exists in the dictionary.
➢ print(): Tells whether the key is present or not.
Program:
d = {'name':'Kiran', 'age':21}
key = 'age'
if key in d:
print('Key found')
else:
print('Key not found')
Output:
Result: Hence, the program was executed successfully.
Experiment-16
Aim: Develop a program to add a new key-value pair to an existing dictionary.
Description:
➢ dict: Creates a dictionary to store data.
➢ Assignment (d[key] = value): Adds a new key and value to the dictionary.
➢ print(): Shows the updated dictionary.
Program:
d = {'name':'Kiran'}
d['age'] = 21
print('Updated dictionary:', d)
Output:
Result: Hence, the program was executed successfully.
Experiment-17
Aim: Develop a program to sum all the items in a given dictionary.
Description:
➢ dict: Stores numeric values with keys.
➢ values(): Gets all the numbers (not keys) from the dictionary.
➢ sum(): Adds all these values together.
➢ print(): Displays the total.
Program:
d = {'a':10, 'b':20, 'c':30}
print('Sum of items:', sum(d.values()))
Output:
Result: Hence, the program was executed successfully.
Experiment-18
Aim: Develop a 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 from source must be
lowered.
Description:
➢ open(): Opens a file to read or write.
➢ read(): Reads the whole file content.
➢ split(): Breaks the text into individual words.
➢ lower(): Converts all words to small letters (for uniform sorting).
➢ sorted(): Arranges the words in alphabetical order.
➢ write(): Saves the sorted list to a file.
Program:
in_file = open("D://source.txt", "r")
text = in_file.read()
in_file.close()
words = text.split()
for i in range(len(words)):
words[i] = words[i].lower()
words.sort()
op_file = open("D://sorted_words.txt", "w")
for word in words:
op_file.write(word + "\n")
op_file.close()
Output:
Result: Hence, the program was executed successfully.
Experiment-19
Aim: Develop a Python program to print each line of a file in reverse order.
Description:
➢ open(): Opens a file for reading.
➢ readlines(): Reads all lines as a list.
➢ for: Goes through each line.
➢ [::-1]: Reverses the characters in each line.
➢ print(): Shows the reversed lines.
Program:
in_file = "D://sample.txt"
f=open(in_file, "r")
lines = f.readlines()
for line in lines:
reversed_line = line.strip()[::-1]
print(reversed_line)
f.close()
Output:
Result: Hence, the program was executed successfully.
Experiment-20
Aim: Develop a Python program to compute the number of characters, words and
lines in a file.
Description:
➢ open(): Opens a text file.
➢ read(): Loads the entire file content.
➢ split(): Splits the text into words.
➢ len(): Counts number of items (characters, words, or lines).
➢ splitlines(): Splits content line by line for line count.
Program:
f=open('input.txt', 'r')
text = f.read()
chars = len(text)
words = len(text.split())
lines = len(text.splitlines())
print('Chars:', chars)
print('Words:', words)
print('Lines:', lines)
Output:
Result: Hence, the program was executed successfully.
Experiment-21
Aim: Develop a program to create, display, append, insert and reverse the order of
the items in the array.
Description:
➢ list: Used as an array to store items.
➢ append(): Adds a new item at the end.
➢ insert(): Adds a new item at a specific position.
➢ reverse(): Reverses the order of items.
➢ print(): Shows the final array.
Program:
import numpy as np
def main():
arr = np.array([10, 20, 30, 40, 50])
print("Initial Array:", arr)
print("Displaying Array:", arr)
arr = np.append(arr, [60, 70])
print("After Appending [60, 70]:", arr)
arr = np.insert(arr, 2, 25)
print("After Inserting 25 at index 2:", arr)
arr = arr[::-1]
print("Reversed Array:", arr)
main()
Output :
Result: Hence, the program was executed successfully.
Experiment-22
Aim: Develop a program to add, transpose and multiply two matrices.
Description:
➢ list: Stores a 2D list to represent a matrix.
➢ Nested for: Used to go through rows and columns.
➢ Arithmetic +, *: Used to add or multiply elements.
➢ zip(): Helps switch rows to columns (transpose).
➢ print(): Displays resulting matrix
Program:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
print('Sum:', a+b)
print('Transpose of a:', a.T)
print('Product:', np.dot(a, b))
Output:
Result: Hence, the program was executed successfully.
Experiment-23
Aim: Develop a Python program to create a class that represents a shape. Include
methods tocalculate its area and perimeter. Implement subclasses for different shapes
like circle, triangle, and square.
Description:
➢ class: Used to group data and functions into one object.
➢ __init__(): Initializes values when object is created.
➢ Inheritance: Allows one class to get features of another.
➢ area(), perimeter(): Functions that calculate shape properties.
➢ print(): Shows the result.
Program:
class Shape:
def area(self):
pass
def perimeter(self):
pass
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return 3.14 * self.r * self.r
def perimeter(self):
return 2 * 3.14 * self.r
c = Circle(5)
print('Area:', c.area())
print('Perimeter:', c.perimeter())
Output:
Result: Hence, the program was executed successfully.
Experiment-24
Aim: Develop a Python program to check whether a JSON string contains complex
object or not.
Description:
➢ json.loads(): Converts JSON text into Python object.
➢ type(): Checks what kind of data (e.g., list or dict) was converted.
➢ print(): Shows the result and its type.
Program:
import json
s = '{"name": "Kiran", "data": {"x": 10}}'
d = json.loads(s)
# Check if the value of key 'data' is itself a dictionary
if isinstance(d['data'], dict):
print('Complex object present')
else:
print('Not present')
Output:
Result: Hence, the program was executed successfully.
Experiment-25
Aim: Demonstrate NumPy arrays creation using array () function.
Description:
➢ import numpy: Loads the NumPy library.
➢ array(): Creates a NumPy array (like a list but faster).
➢ print(): Shows the array.
Program:
import numpy as np
arr = np.array([1,2,3,4])
print('Array:', arr)
Output:
Result: Hence, the program was executed successfully.
Experiment-26
Aim: Demonstrate use of ndim, shape, size, dtype.
Description:
➢ ndim: Tells how many dimensions (1D, 2D, etc.).
➢ shape: Shows the number of rows and columns.
➢ size: Counts total elements in the array.
➢ dtype: Tells the type of values stored (int, float, etc.).
Program:
import numpy as np
arr = np.array([[1,2],[3,4]])
print('ndim:', arr.ndim)
print('shape:', arr.shape)
print('size:', arr.size)
print('dtype:', arr.dtype)
Output:
Result: Hence, the program was executed successfully.
Experiment-27
Aim: Demonstrate basic slicing, integer and Boolean indexing.
Description:
➢ array[]: Used to select specific items or slices.
➢ Integer indexing: Picks elements by position.
➢ Boolean indexing: Picks elements based on condition.
➢ print(): Shows selected values.
Program:
import numpy as np
arr = np.array([1,2,3,4,5])
print('Slice:', arr[1:4])
print('Boolean Index:', arr[arr > 2])
Output:
Result: Hence, the program was executed successfully.
Experiment-28
Aim: Develop a Python program to find min, max, sum, cumulative sum of array
Description:
➢ min(): Finds the smallest value.
➢ max(): Finds the largest value.
➢ sum(): Adds all elements.
➢ cumsum(): Adds elements one by one and shows running total.
Program:
import numpy as np
arr = np.array([1,2,3,4])
print('Min:', arr.min())
print('Max:', arr.max())
print('Sum:', arr.sum())
print('Cumulative sum:', np.cumsum(arr))
Output:
Result: Hence, the program was executed successfully.
Experiment-29
Aim: Prepare 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 and explore the data through the data frame as follows:
a) Apply head () function to the pandas data frame
b) Perform various data selection operations on Data Frame
Description:
➢ dict: Stores data in column format.
➢ pd.DataFrame(): Creates a table-like structure with rows and columns.
➢ head(): Shows first few rows.
➢ Column selection: Lets you view data in a specific column.
Program:
import pandas as pd
book={
"Name":["python","Java","DataStructures","HTML","C"],
"Author":["Nageswar","Balaguruswamy","Debasis","Sridhar","Dennis"],
"Price":[677,800,500,230,440],
"Copies":[120,200,100,150,220],
"discount":[10,15,15,17,11]
}
df=pd.DataFrame(book)
print(df.head())
print(df[“Name”])
mask=df["Price"]>600
df[mask]
Output:
Result: Hence, the program was executed successfully.
Experiment-30
Aim: Select any two columns from the above data frame, and observe the change in
one attribute with respect to other attribute with scatter and plot operations in
matplotlib.
Description:
➢ pd.DataFrame(): Prepares data for graph.
➢ matplotlib.pyplot: Library to draw charts.
➢ plt.scatter(): Plots points based on two values (x and y).
➢ plt.show(): Displays the chart window.
Program:
import pandas as pd
import matplotlib.pyplot as plt
df.plot.scatter(x='Price', y='Copies',title ="Price Vs Copies")
plt.show()
Output:
Result: Hence, the program was executed successfully.