0% found this document useful (0 votes)
2 views20 pages

_bca 3rd python lab (1)

The document contains multiple Python programs demonstrating various data types, operations on lists, tuples, dictionaries, and arithmetic functions. It also includes examples of filtering even numbers, manipulating dates, counting character occurrences, and using NumPy and pandas for array and DataFrame manipulations. Each program is accompanied by sample outputs to illustrate the functionality.

Uploaded by

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

_bca 3rd python lab (1)

The document contains multiple Python programs demonstrating various data types, operations on lists, tuples, dictionaries, and arithmetic functions. It also includes examples of filtering even numbers, manipulating dates, counting character occurrences, and using NumPy and pandas for array and DataFrame manipulations. Each program is accompanied by sample outputs to illustrate the functionality.

Uploaded by

tanushree0624
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

#Program:1 Write a program to demonstrate basic data type in python

#Integer data type


a=10
print("Type of a: ", type(a))
print("Value of a:", a)

#Float data type


b=20.5
print("Type of bi", type(b))
print("Value of b", b)

#String data type


c="python"
print("Type of c", type(c))
print("Value of c", c)

#Boolean data type


d=True
print("Type of d: ",type(d))
print("Value of d: ", d)

#List data type

e =[1, 2, 3, 4]
print("Type of e:", type(e))
print("Value of e:", e)

#Tuple data type


f= (1, 2, 3, 4)
print("Type of f: ", type(f))
print("Value of f: ", f)

#Set data type


g={1, 2, 3, 4}
print("Type of g: ", type(g))
print("Value of g: ", g)

#Dictionary data type


h= { "name": "Srikanth", "age": 30}
print("Type of h: ", type(h))
print("Value of h: ", h)

#None data type


i = None
print("Type of i: ", type(i))
print("Value of i: ", i)

Type of a: <class 'int'>


Value of a: 10
Type of bi <class 'float'>
Value of b 20.5
Type of c <class 'str'>
Value of c python
Type of d: <class 'bool'>
Value of d: True
Type of e: <class 'list'>
Value of e: [1, 2, 3, 4]
Type of f: <class 'tuple'>
Value of f: (1, 2, 3, 4)
Type of g: <class 'set'>
Value of g: {1, 2, 3, 4}
Type of h: <class 'dict'>
Value of h: {'name': 'Srikanth', 'age': 30}
Type of i: <class 'NoneType'>
Value of i: None

#Program 2:
#create list and perform the following methods
#1.insert() 2.remove() 3.append 4,len() 5.pop() 6.clear()

#create a list
my_list =[1, 2, 3, 4, 5]
print("Original List: ", my_list)

#insert an element at a specific index


my_list.insert(2, 10)
print("List after inserting 10 at index 2;", my_list)

#remove an element from the list


my_list.remove(5)
print("List after removing 5: ", my_list)

#append an element to the end of the list


my_list.append(20)
print("List after appending 20: ", my_list)

#get the length of the list


list_length = len(my_list)
print("Length of the list", list_length)

#remove the last element from the list


last_element=my_list.pop()
print("Last element removed from the list", last_element)
print("List after removing the last element", my_list)

#clear all elements from the list


my_list.clear()
print("List after clearing all elements:", my_list)
Original List: [1, 2, 3, 4, 5]
List after inserting 10 at index 2; [1, 2, 10, 3, 4, 5]
List after removing 5: [1, 2, 10, 3, 4]
List after appending 20: [1, 2, 10, 3, 4, 20]
Length of the list 6
Last element removed from the list 20
List after removing the last element [1, 2, 10, 3, 4]
List after clearing all elements: []

#Program 3: Create a tuple and perform the following methods

#1. Add items 2. len() 3. check for item in tuple 4. Access items

# Create a tuple
my_tuple = (1, 2, 3, 4, 5)
print("Original Tuple: ", my_tuple)

# Get the length of the tuple


tuple_length = len(my_tuple)
print("Length of the Tuple:", tuple_length)

# Check if an item exists in the tuple


check = 2 in my_tuple
print("Is 2 in the Tuple?: ", check)

# Access items in the tuple


print("Item at index 2: ", my_tuple[2])

# Convert the tuple to a list as tuples are immutable


my_list = list(my_tuple)

# Insert an element at a specific index in the list


my_list.insert(2, 20)

# Append an element to the end of the list


my_list.append(6)

# Convert the list back to a tuple


my_tuple = tuple(my_list)

# Print the updated tuple


print("Elements in Tuple: ",my_tuple)

Original Tuple: (1, 2, 3, 4, 5)


Length of the Tuple: 5
Is 2 in the Tuple?: True
Item at index 2: 3
Elements in Tuple: (1, 2, 20, 3, 4, 5, 6)
# Program 4 : Create a dictionary and apply the following methods

#1. Print the dictionary items 2. Access items 3. use get() 4.


change values 5. use len()

# Create a dictionary
student = {"name": "Mary", "age": 20, "grade": "A"}

# Print the dictionary items directly


print("Dictionary items using items(): \n", student.items())

# Print the dictionary items by traversing it


print("Dictionary items by traversing:")
for key, value in student.items():
print(key, ":", value)

# Access items in the dictionary using keys


print("Age of student:", student["age"])

# Use the get() method to access items


print("Grade of student:", student.get("grade"))

# Change values in the dictionary


student["grade"] = "B"
print("Updated dictionary:", student)

# Get the length of the dictionary


dict_length = len(student)
print("Length of the dictionary:", dict_length)

Dictionary items using items():


dict_items([('name', 'Mary'), ('age', 20), ('grade', 'A')])
Dictionary items by traversing:
name : Mary
age : 20
grade : A
Age of student: 20
Grade of student: A
Updated dictionary: {'name': 'Mary', 'age': 20, 'grade': 'B'}
Length of the dictionary: 3

# program 5:Write a program to create a menu with the following


options

# 1. TO PERFORM ADDITION 2 .TO PERFORM SUBTRACTION

#3. TO PERFORM MULTIPLICATION 4. TO PERFORM DIVISION

#Accepts users input and perform the arguments. operation accordingly.


Use functions with arguments
# Define arithmetic operation functions
def add(a, b):
return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


if b == 0:
return "Error: Division by zero"
return a / b

# Menu-driven program
while True:
# Display the menu
print("\nARITHMETIC OPERATIONS")
print("1. TO PERFORM ADDITION")
print("2. TO PERFORM SUBTRACTION")
print("3. TO PERFORM MULTIPLICATION")
print("4. TO PERFORM DIVISION")
print("5. EXIT")
choice = int(input("Enter your choice: "))
if choice==5:
print("existing the program")
break
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Perform the selected operation


if choice == 1:
result = add(num1, num2)
print("Result: ", result)
elif choice == 2:
result = subtract(num1, num2)
print("Result: ", result)
elif choice == 3:
result = multiply(num1, num2)
print("Result: ", result)
elif choice == 4:
result = divide(num1, num2)
print("Result: ", result)
else:
print("Invalid option, please try again.")
ARITHMETIC OPERATIONS
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
5. EXIT
Enter your choice: 1
Enter first number: 12
Enter second number: 13
Result: 25.0

ARITHMETIC OPERATIONS
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
5. EXIT
Enter your choice: 2
Enter first number: 12
Enter second number: 13
Result: -1.0

ARITHMETIC OPERATIONS
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
5. EXIT
Enter your choice: 3
Enter first number: 12
Enter second number: 14
Result: 168.0

ARITHMETIC OPERATIONS
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
5. EXIT
Enter your choice: 4
Enter first number: 12
Enter second number: 13
Result: 0.9230769230769231

ARITHMETIC OPERATIONS
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
5. EXIT
Enter your choice: 5
existing the program

# program 6: Write a python program to print a number is


positive/negative using if-else.

#Input a number

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

#Check if the number is positive or negative


if num >=0:

print(num, "is a positive number")


else:
print(num, "is a negative number")

Enter a number: -7
-7 is a negative number

#Program 7: Write a program for filter() to filter only even numbers


from a given list.

#Input list of numbers


numbers= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#Define a function to check for even numbers

def is_even(num):
return num % 2 == 0
#Use filter() to filter only even numbers
even_numbers = list(filter(is_even, numbers))

#Print the filtered list of even numbers

print("The even numbers are: ", even_numbers)

The even numbers are: [2, 4, 6, 8, 10]

#Program 8:Write a program to print date, time for today and now

import datetime

#Get the current date and time


now= datetime.datetime.now()

#Print the date and time


print("Today's date and time:", now)

Today's date and time: 2024-10-07 17:00:17.068352


# program :9 Write a python program to add some days to your present
date and print the date

import datetime

#Get the current date

today =datetime.datetime.now().date()

#Print the current date


print("Current Date is", today)

#Input number of days to add

days_to_add= int(input("Enter the number of days to add: "))

#Add the days to the current date


new_date= today + datetime.timedelta(days=days_to_add)

#Print the new date

print("Date after adding", days_to_add, "days is:", new_date)

Current Date is 2024-10-07


Enter the number of days to add: 6
Date after adding 6 days is: 2024-10-13

#Program 10: Write a program to count the number of occurrences of


each character in a string and store the result in a dictionary data
structure:

def count_characters(string):
# Create an empty dictionary
char_count = {}

# Loop through each character in the string


for char in string:
# If the character is already in the dictionary, increment its
count by 1
if char in char_count:
char_count[char] += 1
# If the character is not in the dictionary, add it and set
its count to 1
else:
char_count[char] = 1

# Return the dictionary


return char_count

# Input the string


string = input("Enter a string: ")

# Call the function and store the result in a variable


result = count_characters(string)

# Print the result


print(f"Character count in '{string}' is:\n{result}")

Enter a string: hdhkdjisjod


Character count in 'hdhkdjisjod' is:
{'h': 2, 'd': 3, 'k': 1, 'j': 2, 'i': 1, 's': 1, 'o': 1}

# Program 11: Write a program to count frequency of characters in a


given fle

def count_characters(filename):
# Open the file in read mode
with open(filename, "r") as file:
# Read the contents of the file into a string
contents = file.read()

# Create an empty dictionary


char_count = {}

# Loop through each character in the string


for char in contents:
# If the character is already in the dictionary, increment its
count by 1
if char in char_count:
char_count[char] += 1
# If the character is not in the dictionary, add it and set
its count to 1
else:
char_count[char] = 1

# Return the dictionary


return char_count

# Input the data


data = input("Enter the data: ")

# Input the filename to be saved


filename = input("Enter the filename to save the data: ")

# Write the data to the file


with open(filename, "w") as file:
file.write(data)
# Inform that the file is being opened for reading
print(f"Opening the file '{filename}' for reading...")

# Call the function and store the result in a variable


result = count_characters(filename)

# Print the result


print(f"Character frequency in '{filename}' is:\n{result}")

Enter the data: misisippi


Enter the filename to save the data: myData.txt
Opening the file 'myData.txt' for reading...
Character frequency in 'myData.txt' is:
{'m': 1, 'i': 4, 's': 2, 'p': 2}

#Program 12:Using a numpy module create an array and check the


following

# 1. Type of array 3. Shape of array

#2. Axes of array 4. Type of elements in array.

import numpy as np

# Create a one-dimensional array


arr = np.array([1, 2, 3, 4, 5])

# Print the type of the array


print("Type of array:", type(arr))

# Print the number of axes (dimensions) of the array


print("Axes of array:", np.ndim(arr))

# Print the shape of the array


print("Shape of array:", arr.shape)

# Print the type of elements in the array


print("Type of elements in array:", arr.dtype)

Type of array: <class 'numpy.ndarray'>


Axes of array: 1
Shape of array: (5,)
Type of elements in array: int32

#Program 13: Write a python program to concatenate the dataframes with


two different objects.
import pandas as pd

# Create the first DataFrame (df1)


df1 = pd.DataFrame({
'Name': ['Snigdha', 'Smayan', 'Satvik'],
'age': [20, 19, 18],
'grade': ['A', 'C', 'A']
}, index=[1, 2, 3])

# Create the second DataFrame (df2)


df2 = pd.DataFrame({
'Name': ['Mary', 'Nirmala', 'Shantala'],
'age': [23, 30, 28],
'grade': ['B', 'C', 'A']
}, index=[4, 5, 6])

# Concatenate the two DataFrames into a single DataFrame


result = pd.concat([df1, df2])

# Display the concatenated DataFrame


print(result)

Name age grade


1 Snigdha 20 A
2 Smayan 19 C
3 Satvik 18 A
4 Mary 23 B
5 Nirmala 30 C
6 Shantala 28 A

#rogram 14 :Write a python code to read a csv file using pandas module
and print the first and five lines of a file.

import pandas as pd

# Read the CSV file into a DataFrame using pd.read_csv()


df = pd.read_csv('Downloads/hw_200.csv')

# Display the first 5 rows of the DataFrame using head()


print("First 5 Rows:")
print(df.head(5))

# Display the last 5 rows of the DataFrame using tail()


print("\nLast 5 Rows:")
print(df.tail(5))

First 5 Rows:
Index Height(Inches)" "Weight(Pounds)"
0 1 65.78 112.99
1 2 71.52 136.49
2 3 69.40 153.03
3 4 68.22 142.34
4 5 67.79 144.30
Last 5 Rows:
Index Height(Inches)" "Weight(Pounds)"
195 196 65.80 120.84
196 197 66.11 115.78
197 198 68.24 128.30
198 199 68.02 127.47
199 200 71.39 127.88

#Program 15: Write a python program which accepts the radius of a


circle from user and computes the area (use math module)

import math

# Get the radius of the circle from the user


radius = float(input("Enter the radius of the circle: "))

# Calculate the area of the circle


area = math.pi * radius**2

# Print the result


print(f"The area of the circle is: {area}")

Enter the radius of the circle: 7


The area of the circle is: 153.93804002589985

#Program 16: Use the following data (load it as CSV file) for this
exercise. Read thi or NumPy or using in-built matplotlib function.

#create excel file


months pen book marker chair table pen stand total units
total profit
1 2500 1500 5200 9200 1200 1500 21100 211000
2 2630 1200 5100 6100 2100 1200 18330 183300
3 2140 1340 4550 9550 3550 1340 22470 224700
4 3400 1130 5870 8870 1870 1130 22270 222700
5 3600 1740 4560 7760 1560 1740 20960 209600
6 2760 1555 4890 7490 1890 1555 20140 201400
7 2980 1120 4780 8980 1780 1120 29550 295500
8 3700 1400 5860 9960 2860 1400 36140 361400
9 3540 1780 6100 8100 2100 1780 23400 234000
10 1990 1890 8300 10300 2300 1890 26670 266700
11 2340 2100 7300 13300 2400 2100 41280 412800
12 2900 1760 7400 14400 1800 1760 30020 300200

#Program 16 (a) DIAPLAYING SALES TREND OF ALL PRODUCTS


# Get total uints of all months and show line ploat with the following
style properties generated line ploat must include
#follwing style operation
#1,line style dotted and line color should be blue
#2.Show legend at the lower right location

#3.X label name= Months

#4.y label name=sold units

#5.Line width should be 4

#Important Note: It's Important to plot data that makes sense and is
relevant to the analysis w are trying to perform,
#in the code, we are plotting the sales trend by having the x-azis an
"Months and y-axis as "Total Units" This makes
#sense as it gives us the trend of units sold over the months However,
marking profits in the y-axis and labeling it as
#"Sold Units" does not make sense. To plot the profit trend, we need
to have the saxis as "Months" and y-axis as "Total Profit
#This gives us the trend of profits earned over the months. So, it's
important to plot relevant data in the ass and
#y-axis for the analysis we are trying to perform. We have mindified
the program title to display the total units of all months
#in y-axis.
import pandas as pd
import matplotlib.pyplot as plt

# Read the csv file into a DataFrame using pd.read_csv()


df = pd.read_csv('Documents/sale.csv')

# Get the data for the "Total Units" column


sold_units = df["total units"]

# Plot the total profit data


plt.plot(sold_units, color='blue', marker='o', linestyle='dotted',
label="sold Units", linewidth=4)

# Add X and Y axis label


plt.xlabel("months")
plt.ylabel("sold Units")

# Add title
plt.title("Sales Trend of All Products")

# Add a legend at the lower right location


plt.legend(loc="lower right")

# Add xticks to include all months


plt.xticks(range(len(df)), df['months'], rotation=45)

# Show the plot


plt.show()

#Program 16 (a)

#Displaying Profit Trend of All Products

#Get total profit of all months and show line plot with the following
Style properties Generated line plot must include
#following Style properties:
# 1.line style dootted and line -color should be blue
#2.show legend at the lower right location
#X label name = Months

#Y label name =Total Profit

#line width should be 4

#Important Note: This program is to show the profits trend over the
months. To plot the profit , we need to have the x-axis as
#"Months" and y-axis as lower profit

import pandas as pd
import matplotlib.pyplot as plt

# Read the CSV file into a DataFrame


df = pd.read_csv('Documents/sale.csv')

# Get the data for the "Total Units" column


sold_units = df["total units"]

# Plot the total units data with specified style


plt.plot(sold_units, color='blue', marker='o', linestyle='dotted',
label="Sold Units", linewidth=4)

# Add X and Y axis labels


plt.xlabel("Months")
plt.ylabel("Sold Units")

# Add title
plt.title("Sales Trend of All Products")

# Add a legend at the lower right location


plt.legend(loc="lower right")

# Add xticks to include all months


plt.xticks(range(len(df)), df['months'], rotation=45)

# Show the plot


plt.show()
#Program 16 (b): diasplY the number of units sold per month for each
product using multiline plots
#(i.e seperate plot line for each product)
import pandas as pd
import matplotlib.pyplot as plt

# Read the CSV file into a DataFrame using pd.read_csv()

df = pd.read_csv('Documents/sale.csv')
# Plot the units sold data for each product
plt.plot(df["months"], df['pen'], color='blue', marker='o',
label="Pen")
plt.plot(df["months"], df['book'], color='red', marker='o',
label="Book")
plt.plot(df["months"], df['marker'], color='green', marker='o',
label="Marker")
plt.plot(df["months"], df['chair'], color='yellow', marker='o',
label="Chair")
plt.plot(df["months"], df['table'], color='purple', marker='o',
label="Table")
plt.plot(df["months"], df['pen stand'], color='orange', marker='o',
label="Pen Stand")

# Add X and Y axis labels


plt.xlabel("Months")
plt.ylabel("Sold Units")
# Add title
plt.title("Sales Trend By Product")

# Add a legend at the upper left location


plt.legend(loc="upper left")

# Show the plot


plt.show()

#Program 16 (c) Read chair and tablet sales data and show it using The
bar chart .
# the bar chart should display the number of units sold per month for
each product add a seperate bar
#for each product in the same chart
import pandas as pd
import matplotlib.pyplot as plt

# Read the CSV file into a DataFrame using pd.read_csv()

df = pd.read_csv('Documents/sale.csv')
# Extract the data for Chair and Table products
data = df[["months", "chair", "table"]]

# Set the bar width


bar_width = 0.35

# Create positions for the bars on the x-axis


index = data.index

# Create a bar chart for Chair and Table products


plt.bar(index, data["chair"], bar_width, label="chair", color='blue')
plt.bar(index + bar_width, data["table"], bar_width, label='table',
color='red')

# Add X and Y axis labels


plt.xlabel("months")
plt.ylabel("sold units")

# Add title
plt.title("Sales Trend of Chair and Table")

# Add a legend at the upper left location


plt.legend(loc="upper left")

# Set the X-axis tick labels to be the months


plt.xticks(index + bar_width / 2, data['months'])

# Show the plot


plt.show()

#Program 16 (d) Read all product sales data and show it using the
stack plot.
import pandas as pd
import matplotlib.pyplot as plt

# Read the CSV file into a DataFrame using pd.read_csv()


df = pd.read_csv('Documents/sale.csv')

# Extract the data for all products


data = df[["months", "pen", "book", "marker", "chair", "table", "pen
stand"]]

# Plot the data using a stack plot


plt.stackplot(data["months"],
data["pen"],
data["book"],
data["marker"],
data["chair"],
data["table"],
data["pen stand"],
labels=["pen", "book", "marker", "chair", "table", "pen
stand"])

# Add X and Y axis labels


plt.xlabel("months")
plt.ylabel("sold units")

# Add a legend at the upper left location


plt.legend(loc="upper left")

# Add title
plt.title("Sales Trend of All Products")

# Show the plot


plt.show()

You might also like