Unit 1 - Lab Programs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Experiment 1.

1: Implement built-in functions and trace the type of data items


Aim: The aim of this code is to implement simplified versions of the sum() and max() functions
and trace the type of data items passed to them.

Algorithm:

1. Define a function my_sum(iterable) to calculate the sum of elements in the iterable.


2. Initialize a variable result to store the sum.
3. Iterate through each item in the iterable and add it to the result.
4. Return the final value of result.
5. Define a function my_max(iterable) to find the maximum element in the iterable.
6. Check if the iterable is empty. If it is, raise a ValueError.
7. Initialize a variable max_value with the first element of the iterable.
8. Iterate through the remaining elements of the iterable and update max_value if a
larger element is found.
9. Return the final value of max_value.
10. Test both functions with a list of numbers.
11. Use the type() function to trace the data types of the list, the sum, and the maximum
value.

This code illustrates the implementation of two common built-in functions, sum() and max(), along
with tracing the data types of the values involved.

def my_sum(iterable):
"""
Return the sum of elements in the iterable.
"""
result = 0
for item in iterable:
result += item
return result

def my_max(iterable):
"""
Return the maximum element in the iterable.
"""
if not iterable:
raise ValueError("max() arg is an empty sequence")

max_value = iterable[0]
for item in iterable[1:]:
if item > max_value:
max_value = item
return max_value

# Test the functions


my_list = [1, 5, 3, 9, 2]
print("Sum of my_list:", my_sum(my_list))
print("Max of my_list:", my_max(my_list))

# Tracing data types


print("Type of my_list:", type(my_list))
print("Type of sum of my_list:", type(my_sum(my_list)))
print("Type of max of my_list:", type(my_max(my_list)))
output:
Sum of my_list: 20
Max of my_list: 9
Type of my_list: <class 'list'>
Type of sum of my_list: <class 'int'>
Type of max of my_list: <class 'int'>
Experiment 1.2: Implement concepts of Conditional and Iterative
Statements.

Aim:
To implement conditional and iterative statements in Python to demonstrate basic
control flow mechanisms.

Algorithm:

1. Conditional Statements:
 if statement: Check if a condition is true, and execute a block of code if
it is.
 if-else statement: Check if a condition is true; if it is, execute one block
of code; otherwise, execute another block.
 if-elif-else statement: Check multiple conditions sequentially, and
execute different blocks of code based on the first true condition
encountered.
2. Iterative Statements:
 while loop: Repeat a block of code as long as a specified condition is
true.
 for loop: Iterate over a sequence of elements (e.g., a list or a range of
numbers) and execute a block of code for each element.

# Aim: Demonstrate conditional and iterative statements in Python

# Conditional Statements
x = 10
y=5

# If statement
if x > y:
print("Aim: x is greater than y")

# If-else statement
if x < y:
print("Aim: x is less than y")
else:
print("Aim: x is not less than y")

# If-elif-else statement
if x < y:
print("Aim: x is less than y")
elif x == y:
print("Aim: x is equal to y")
else:
print("Aim: x is greater than y")

# Iterative Statements
# While loop
count = 0
while count < 5:
print("Aim: Count:", count)
count += 1

# For loop
for i in range(5):
print("Aim: i:", i)

# Nested loops
for i in range(3):
for j in range(2):
print("Aim: i:", i, "j:", j)
output:
Aim: x is greater than y
Aim: x is not less than y
Aim: x is greater than y
Aim: Count: 0
Aim: Count: 1
Aim: Count: 2
Aim: Count: 3
Aim: Count: 4
Aim: i: 0
Aim: i: 1
Aim: i: 2
Aim: i: 3
Aim: i: 4
Aim: i: 0 j: 0
Aim: i: 0 j: 1
Aim: i: 1 j: 0
Aim: i: 1 j: 1
Aim: i: 2 j: 0
Aim: i: 2 j: 1
EX.No.1.3
Aim:

Write a Python program to read and write from a CSV file by using built-in CSV module.

Algorithm

Step 1: A CSV (Comma Separated Values) format is one of the most simple and common ways to

store tabular data. To represent a CSV file, it must be saved with the .csv file extens

Step 2: CSV file are separated by commas.

Step 3: Use the built-in open() function to work with CSV files in Python

Step 4: Before use the methods to the csv module, need to import the module first using import

command

Step 5: To read a CSV file in Python, use the csv.reader() function.

Step 6: To write to a CSV file in Python, use the csv.writer() function.The csv.writer() function returns

a writer object that converts the user's data into a delimited string. This string can later be

used to write into CSV files using the writerow() function.

open the people.CSV file using a text editor and store below data:

SN, Name, City

1, Michael, New Jersey

2, Jack, California

Program
Read from a CSV file

import csv

with open('people.csv', 'r') as file:

reader = csv.reader(file)

for row in reader:

print(row)

Output
['SN', ' Name', ' City']

['1', ' Michael', ' New Jersey']


['2', ' Jack', ' California']

[]

Write to a CSV file


import csv

with open('protagonist.csv', 'w', newline='') as file:

writer = csv.writer(file)

writer.writerow(["SN", "Movie", "Protagonist"])

writer.writerow([1, "Lord of the Rings", "Frodo Baggins"])

writer.writerow([2, "Harry Potter", "Harry Potter"])

Output
SN,Movie,Protagonist

1,Lord of the Rings,Frodo Baggins

2,Harry Potter,Harry Potter


Ex.No.1.4
Aim:
Write a Python program to Perform data analysis and visualization on a given dataset
using Python libraries like pandas numpy, matplotlib and display charts, graphs, and
plots.
A. Panda
import pandas as pd
# a simple dictionary
dict = {'raju': 10,
'babu': 20,
'somu': 30}
# create series from dictionary
ser = pd.Series(dict)

print(ser)

Output:
B. numpy
import numpy as np
a = np.array([[1, 4, 2],
[3, 4, 6],
[0, -1, 5]])

# sorted array
print ("Array elements in sorted order:\n",
np.sort(a, axis = None))
# sort array row-wise
print ("Row-wise sorted array:\n",
np.sort(a, axis = 1))

# specify sort algorithm


print ("Column wise sort by applying merge-sort:\n",
np.sort(a, axis = 0, kind = 'mergesort'))

# Example to show sorting of structured array


# set alias names for dtypes
dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)]

# Values to be put in array


values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),
('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]
# Creating array
arr = np.array(values, dtype = dtypes)
print ("\nArray sorted by names:\n",
np.sort(arr, order = 'name'))

print ("Array sorted by graduation year and then cgpa:\n",


np.sort(arr, order = ['grad_year', 'cgpa']))

Output:

C. Chart

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels)


plt.legend(title = "Four Fruits:")
plt.show()
Output

D. Graph

import matplotlib.pyplot as plt

# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]

# plotting the points


plt.plot(x, y)

# naming the x axis


plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph


plt.title('Python graph')

# function to show the plot


plt.show()

OUTPUT

You might also like