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

Python Experiments.HARSH[1]

The document contains a series of Python programming exercises conducted by Harsh S Suryavanshi, covering topics such as student registration, arithmetic operations, password validation, string and list operations, Fibonacci series, duplicate detection, and object-oriented programming concepts. Each experiment includes input prompts, code snippets, and expected outputs. The document serves as a comprehensive guide for learning and practicing Python programming.

Uploaded by

pratiknew03
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)
5 views

Python Experiments.HARSH[1]

The document contains a series of Python programming exercises conducted by Harsh S Suryavanshi, covering topics such as student registration, arithmetic operations, password validation, string and list operations, Fibonacci series, duplicate detection, and object-oriented programming concepts. Each experiment includes input prompts, code snippets, and expected outputs. The document serves as a comprehensive guide for learning and practicing Python programming.

Uploaded by

pratiknew03
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/ 64

NAME: HARSH S SURYAVANSHI ROLL NO.

67

EXPERIMENT NO. 1

1) Write a python program to input student details and display welcome message to newly added
student record.

INPUT:

print("NEW STUDENT REGISTRATION !\n")


name = input("Please Enter your name : ")
course = input("Please Enter your course : ")
class_div = input("Please Enter your class : ")
rollno = input("Please Enter your roll no : ")

print("\nWELCOME,",name+"!!")

print("\nYour Details are :\n")


print("Name :",name)
print("Course :",course)
print("Class :",class_div)
print("Roll No :",rollno

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

2) Write a python Program to perform arithmetic operations on any given inputs

INPUT:

print("Arithmetic Operations!\n")

# Input for numbers


num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))

# Arithmetic operations
add = num1 + num2
sub = num1 - num2
mul = num1 * num2
div = num1 / num2

# Output the results


print("\nAddition of First Number and Second Number is ", add)
print("\nSubtraction of First Number and Second Number is ", sub)
print("\nMultiplication of First Number and Second Number is ", mul)
print("\nDivision of First Number and Second Number is ", div)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

3) Write a python Program for Password Length Checker.

INPUT:

print("Password Length Checker !!")

user_input = input("Enter a password : ")

if (len(user_input)<8 or len(user_input)>12):
print("Not valid ! Total characters should be between 8 and 12 !")
else:
print("Password is valid !")
print("Length of Password :",len(user_input))

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

EXPERIMENT NO. 02

1) Write a program that performs various operations on strings

INPUT:

# String Operations Program

# String Creation
single_quote_str = 'Hello, World!'
double_quote_str = "Python Programming"
triple_quote_str = '''This is a multi-line string
that spans multiple lines.'''

# Display the strings


print("Single-quoted string:", single_quote_str)
print("Double-quoted string:", double_quote_str)
print("Triple-quoted string:", triple_quote_str)

# Indexing
print("\nIndexing:")
print("First character of single_quote_str:", single_quote_str[0]) # 'H'
print("Last character of double_quote_str:", double_quote_str[-1]) # 'g'

# Slicing
print("\nSlicing:")
print("Substring of single_quote_str (from index 0 to 4):", single_quote_str[0:5]) # 'Hello'
print("Substring of double_quote_str (from index 7 to the end):", double_quote_str[7:]) # 'Programming'

# Concatenation
str1 = "Good"
str2 = "Morning"
concatenated_str = str1 + " " + str2
print("\nConcatenation:", concatenated_str)

# Repetition
repeat_str = "Hello! " * 3
print("\nRepetition:", repeat_str)

# Length of a string
print("\nLength of single_quote_str:", len(single_quote_str))

# String Methods
upper_str = single_quote_str.upper()
lower_str = double_quote_str.lower()
replaced_str = single_quote_str.replace("World", "Universe")
find_str = single_quote_str.find("World")
split_str = double_quote_str.split(" ")
NAME: HARSH S SURYAVANSHI ROLL NO.67

print("\nString Methods:")
print("Uppercase version of single_quote_str:", upper_str)
print("Lowercase version of double_quote_str:", lower_str)
print("Replaced 'World' with 'Universe' in single_quote_str:", replaced_str)
print("Index of 'World' in single_quote_str:", find_str)
print("Splitted double_quote_str:", split_str)

# Strip whitespaces (leading and trailing)


str_with_spaces = " Hello Python! "
stripped_str = str_with_spaces.strip()
print("\nString with spaces removed:", stripped_str)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

2) Write a program that performs various operations on list.

INPUT:

# Set Operations Program

# Create sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Display the initial sets


print("Set 1:", set1)
print("Set 2:", set2)

# Adding Elements
set1.add(6) # Add a single element to set1
set1.update([7, 8, 9]) # Add multiple elements from a list
print("\nSet 1 after adding 6 and updating with [7, 8, 9]:", set1)

# Removing Elements
set1.remove(9) # Removes 9, raises KeyError if 9 is not in the set
print("\nSet 1 after removing 9:", set1)

set1.discard(10) # Discards 10 (does not raise error if not found)


print("\nSet 1 after discarding 10 (not found):", set1)

# Pop an element (removes and returns an arbitrary element)


removed_element = set1.pop() # Since the set is unordered, we can't predict which element will be removed
print("\nRemoved element using pop:", removed_element)
print("Set 1 after pop:", set1)

# Clearing all elements from the set


set1.clear()
print("\nSet 1 after clearing all elements:", set1)

# Union of two sets (combine all elements)


union_set = set2 | {1, 2, 3} # Or use set2.union({1, 2, 3})
print("\nUnion of Set 2 and {1, 2, 3}:", union_set)

# Intersection of two sets (common elements)


intersection_set = set2 & {5, 6, 7} # Or use set2.intersection({5, 6, 7})
print("\nIntersection of Set 2 and {5, 6, 7}:", intersection_set)
NAME: HARSH S SURYAVANSHI ROLL NO.67

# Difference of two sets (elements in set2 but not in {5, 6, 7})


difference_set = set2 - {5, 6, 7} # Or use set2.difference({5, 6, 7})
print("\nDifference of Set 2 and {5, 6, 7}:", difference_set)

# Symmetric Difference (elements in either set, but not both)


symmetric_difference_set = set2 ^ {5, 6, 7} # Or use set2.symmetric_difference({5, 6, 7})
print("\nSymmetric Difference of Set

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

3) Write a program that performs various operations on list

INPUT:

# List Operations Program

# Create a list with different data types


my_list = [10, 20, 30, 40, 50]
print("Original List:", my_list)
# Accessing List Elements (Zero-based indexing)
print("\nFirst element of the list:", my_list[0]) # 10
print("Last element of the list:", my_list[-1]) # 50
# Modifying List Elements (Changing an element at index 2)
my_list[2] = 100
print("\nList after modifying element at index 2:", my_list)
# Adding Elements to the List
my_list.append(60) # Adds 60 at the end of the list
print("\nList after appending 60:", my_list)
my_list.insert(2, 25) # Inserts 25 at index 2
print("List after inserting 25 at index 2:", my_list)
# Removing Elements from the List
my_list.remove(40) # Removes the first occurrence of 40
print("\nList after removing 40:", my_list)
popped_element = my_list.pop(3) # Pops the element at index 3
print("\nPopped element at index 3:", popped_element)
print("List after popping the element:", my_list
# Using del to remove an element by index or delete the entire list
del my_list[1] # Removes the element at index 1
print("\nList after deleting element at index 1:", my_list)
# Slicing Lists (Extracting a portion of the list)
sublist = my_list[1:4] # Slices the list from index 1 to 3 (excluding index 4)
print("\nSliced portion of the list (from index 1 to 3):", sublist)
# List Operations
# Length of the list
print("\nLength of the list:", len(my_list))
# Concatenation of two lists
another_list = [70, 80, 90]
concatenated_list = my_list + another_list
print("\nConcatenated list:", concatenated_list)
# Repetition of a list
repeated_list = my_list * 2 # Repeats the list twice
NAME: HARSH S SURYAVANSHI ROLL NO.67

print("\nRepeated list:", repeated_list)


# List Methods
# Sorting the list in ascending order
my_list.sort() # In-place sorting
print("\nList after sorting:", my_list)
# Reversing the list
my_list.reverse() # In-place reversal
print("List after reversing:", my_list)
# Counting occurrences of an element
count_20 = my_list.count(20)
print("\nCount of 20 in the list:", count_20)
# Finding the index of an element
index_30 = my_list.index(30) # Finds the index of first occurrence of 30
print("Index of 30 in the list:", index_30)
# Extending the list with another list
my_list.extend(another_list) # Adds all elements of another_list to my_list
print("\nList after extending with another_list:", my_list)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

EXPERIMENT NO. 03

1) Write a python program that finds the Fibonacci series from 0 to 20.

INPUT:

# Python program to print Fibonacci series!


print("Python program to print Fibonacci series!\n")

# Input for the number of positions in the Fibonacci series


pos = int(input("Enter position: "))

# Initialize the first two numbers in the Fibonacci sequence


fno = 0
sno = 1

# Print the first two numbers


print(fno, end=" ")
print(sno, end=" ")

# Start a loop to generate the next Fibonacci numbers


i = 3 # Start from the 3rd position
while i <= pos:
tno = fno + sno # Next Fibonacci number is the sum of the last two
print(tno, end=" ") # Print the next Fibonacci number
fno = sno # Update the first number to the second number
sno = tno # Update the second number to the new number
i = i + 1 # Increment the position

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

2) Write a python program that finds duplicates from the list [`a`,`b`,’c`,`a`,`a`,`b`,`d`].

INPUT:

# Python program that finds duplicates from the list!


print("Python program that finds duplicates from the list!\n")

# Given list
given_list = ['a', 'b', 'c', 'a', 'a', 'b', 'd']

# Sorting the given list


my_list = sorted(given_list)

# List to store duplicates


duplicates = []

# Loop to find duplicates


for d in my_list:
if my_list.count(d) > 1: # Check if the element occurs more than once
if d not in duplicates: # Avoid adding the same duplicate multiple times
duplicates.append(d)

# Print the results


print("Given List: ", given_list)
print("Duplicate Elements in List: ", duplicates)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

3) Write a python program that display the CAR shape output.

INPUT:

# Python program to display a car shape


print("Python program to display a CAR shape:\n")

# Drawing the car shape using ASCII characters


car = '''
______
/|_||_\`.__
( _ _ _\
=`-(_)--(_)-'
'''

# Print the car shape


print(car)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

EXPERIMENT NO. 04

1) Write a python program that accepts two strings as input and find the string with max length.

INPUT:

# Python program that accepts two strings as input and find the string with max length!
print("Python program that accepts two strings as input and find the string with max length!\n")

# Function to compare the lengths of two strings and print the result
def printVal(s1, s2):
len1 = len(s1) # Find length of first string
len2 = len(s2) # Find length of second string

if len1 > len2:


print("String with max length is: ", s1) # If first string is longer
elif len1 < len2:
print("String with max length is: ", s2) # If second string is longer
else:
print("Both Strings have the same length!") # If both strings have the same length
NAME: HARSH S SURYAVANSHI ROLL NO.67

# Accept input from the user


s1 = input("Enter First String: ")
s2 = input("Enter Second String: ")

# Call the function with the user inputs


printVal(s1, s2)

OUTPUT:

2) Write a python program to print dictionary where keys are no’s between 1 and 20(both
included) & values are square of keys.

INPUT:

# Python program to print dictionary where keys are numbers between 1 and 20 (both included) & values are the square
of keys!
print("Python program to print dictionary where keys are no's between 1 and 20(both included) & values are square of
keys!\n")

# Function to create and print the dictionary


def printDict():
d = dict() # Initialize an empty dictionary
for i in range(1, 21): # Loop from 1 to 20 (both included)
d[i] = i ** 2 # Assign square of i as value for the key i
print(d) # Print the dictionary

# Call the function to print the dictionary


NAME: HARSH S SURYAVANSHI ROLL NO.67

printDict()

OUTPUT:

3) Write a python program to implement Object Oriented Programming concept like


Classes, encapsulation, inheritance and multiple inheritance.

CONCEPT : CLASS AND OBJECTS


INPUT:

print("Python program to implement Object Oriented Programming concept like Creating Class
and Object!\n")

class Parrot:

# class attribute
species = "bird"

# instance attribute
NAME: HARSH S SURYAVANSHI ROLL NO.67

def init (self, name, age):


self.name = name
self.age = age

# instantiate the Parrot class


blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)

# access the class attributes


print("Blu is a {}".format(blu. class .species))
print("Woo is also a {}".format(woo. class .species))

# access the instance attributes


print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

CONCEPT : METHODS

INPUT:

print("Python program to implement Object Oriented Programming concept like Creating

Methods!\n") class Parrot:

# instance attributes
def init (self, name, age):
self.name = name
self.age = age

# instance method
def sing(self,
song):
return "{} sings {}".format(self.name, song)

def dance(self):
return "{} is now dancing".format(self.name)

# instantiate the object


blu = Parrot("Blu",
10)

# call our instance methods


print(blu.sing("'Happy'"))
print(blu.dance())

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

CONCEPT : INHERITANCE

INPUT:

print("Python program to implement Object Oriented Programming concept like Inheritance!\n")


# parent class
class Bird:

def init (self):


print("Bird is ready")

def whoisThis(self):
print("Bird")

def swim(self):
print("Swim faster")

# child class
class Penguin(Bird):

def init (self):


# call super() function
super(). init ()
print("Penguin is ready")

def whoisThis(self):
print("Penguin")

def run(self):
print("Run faster")

peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

CONCEPT : DATA ENCAPSULATION

INPUT:

print("Python program to implement Object Oriented Programming concept like Data


Encapsulation!\n") class Computer:

def init (self):


self _ maxprice = 900

def sell(self):
print("Selling Price: {}".format(self. maxprice))

def setMaxPrice(self,
price): self. maxprice =
price

c = Computer()
c.sell()

# change the price


c. maxprice =
1000 c.sell()

# using setter function


c.setMaxPrice(1000)
c.sell()

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

CONCEPT : POLYMORPHISM

INPUT:

print("Python program to implement Object Oriented Programming concept like

Polymorphism!\n") class Parrot:

def fly(self):
print("Parrot can
fly")

def swim(self):
print("Parrot can't
swim")

class Penguin:

def fly(self):
print("Penguin can't fly")

def swim(self):
print("Penguin can
swim")

# common
interface def
flying_test(bird):
bird.fly()

#instantiate
objects blu =
Parrot() peggy =
Penguin()

# passing the object


flying_test(blu)
flying_test(peggy)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

CONCEPT : MULTIPLE INHERITANCE


INPUT:

print("Python program to implement Multiple Inheritance!\n")

class marks:
def getdata1(self):
self.pt1 = int (input ("Enter IA1 Marks : "))
self.pt2 = int (input ("Enter IA2 Marks :
"))
def display1(self):
print ("IA 1 : ", self.pt1)
print ("IA 2 : ",
self.pt2) class microproject
:
def getdata2(self):
self.m = int (input ("Enter Microproject Marks :
")) def display2(self):
print("Microproject : ", self.m)
class student (marks, microproject):
def display3(self):
total = self.pt1 + self.pt2 +
self.m print("Total : ", total)
s1 = student()
s1.getdata1()
s1.getdata2()
s1.display1()
s1.display2()
s1.display3()

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

EXPERIMENT NO. 05

1) Python program to append data to existing file and then display the entire file

INPUT:

# Python program to append data to existing file and then display the entire file
print("Python program to append data to existing file and then display the entire file!\n")

# Open the file in write mode and write initial data


file_a = open("AkshayPython.txt", "w")
C = ["My Name is Akshay Chandarkar! \n", "Computer Engineer \n"]
file_a.writelines(C) # Write the list of strings to the file
file_a.close() # Close the file after writing

# Open the file in read mode and display the contents before appending
file_a = open("AkshayPython.txt", "r")
print("Output of Readlines before appending!")
print(file_a.read()) # Read and display the entire content of the file
print() # For better formatting
file_a.close() # Close the file after reading

# Append data to the existing file


file_a = open("AkshayPython.txt", "a")
file_a.write("\n") # Add a new line before appending new data
file_a.write("Python program to append data to existing file succeeded!") # Append the new content
file_a.close() # Close the file after appending

# Open the file in read mode and display the contents after appending
file_a = open("AkshayPython.txt", "r")
print("Output of Readlines after appending!")
print(file_a.read()) # Read and display the entire content of the file
print() # For better formatting
file_a.close() # Close the file after reading

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

2) Python program to count number of lines, words and characters in a file.


INPUT:

# Python program to count number of lines, words and characters in a file!

print("Python program to count number of lines, words and characters in a file!\n")

# Open the file in read mode

file_a = open("AkshayPython.txt", "r")

# Initialize counters for lines, words, and characters

number_lines = 0

number_words = 0

number_characters = 0

# Read through each line in the file

for line in file_a:

line = line.strip("\n") # Remove the newline character at the end of each line

words = line.split() # Split the line into words

number_lines += 1 # Increment the line counter

number_words += len(words) # Add the number of words in the current line to the total

number_characters += len(line) # Add the number of characters in the line to the total# Close the file after reading

file_a.close()

# Display the results

print("Lines : ", number_lines)

print("Words : ", number_words)

print("Characters: ", number_characters)


NAME: HARSH S SURYAVANSHI ROLL NO.67

OUTPUT:

3) Python program to display file available in current directory

INPUT:

# Python program to display files available in the current directory


import os

# Get the list of files and directories in the current directory


files = os.listdir()

# Filter and display only the files (excluding directories)


print("Files available in the current directory:")
for file in files:
if os.path.isfile(file):
print(file)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

EXPERIMENT NO. 06

Python program to send emails using modules and packages.

INPUT:

# Python program to send an email

print("Python program to send mail!\n")

import smtplib

from email.mime.text import MIMEText

# Sender's and receiver's email addresses

from_email = '[email protected]'

to_email = '[email protected]'

# Message content

msg = MIMEText('Hello!\nPushkaraj Chaudhary here!\nThis mail is sent by using Python Program!')

msg['Subject'] = 'PYTHON EXPERIMENT'

msg['From'] = from_email

msg['To'] = to_email

# Set up the SMTP server

server = smtplib.SMTP('smtp.gmail.com', 587)

server.starttls() # Secure the connection using TLS

server.ehlo() # Identify yourself to the SMTP server


NAME: HARSH S SURYAVANSHI ROLL NO.67

# Login credentials (use an app password instead of your actual Gmail password)

server.login('[email protected]', '*********') # Replace with your app password

# Send the email

server.sendmail(from_email, to_email, msg.as_string())

# Confirmation message

print("Your Mail was sent Successfully!!!")

# Close the connection to the server

server.quit()

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

EXPERIMENT NO. 07
1. Import Numpy
INPUT:
import numpy as np
# Creating a numpy array
arr = np.array([1, 2, 3, 4, 5])
# Displaying the array
print(arr)

OUTPUT:

2. Create an array of 10 zeroes


INPUT:

# Python program to create an array of 10 zeros!


print("Python program to create array of 10 zeros!\n")

import numpy as np
NAME: HARSH S SURYAVANSHI ROLL NO.67

# Create an array of 10 zeros


array = np.zeros(10)

# Print the array


print("An array of 10 zeros:")
print(array)

OUTPUT:

3. Create an array of 10 ones


INPUT:

# Python program to create an array of 10 ones!


print("Python program to create array of 10 ones!\n")
import numpy as np
# Create an array of 10 ones
array = np.ones(10)
# Print the array
print("An array of 10 ones:")
print(array)

OUTPUT:

4. Create an array of 10 fives


INPUT:

print("Python program to create array of 10 fives!\n")


import numpy as np
NAME: HARSH S SURYAVANSHI ROLL NO.67

array=np.ones(10)*5
print("An array of 10 fives:")
print(array)

OUTPUT:

5. Create an array of the integers from 10 to 50


INPUT:

print("Python program to create array of all the integers from 10 to 50!\n")


import numpy as np
array=np.arange(10,51)
print("Array of all the integers from 10 to 50:\n")
print(array)

OUTPUT:

6. Create an array of all the even integers from 10 to 50


INPUT:

# Python program to create array of all the even integers from 10 to 50!
print("Python program to create array of all the even integers from 10 to 50!\n")
NAME: HARSH S SURYAVANSHI ROLL NO.67

import numpy as np
# Create an array of all the even integers from 10 to 50
array = np.arange(10, 51, 2)
# Print the array
print("Array of all the even integers from 10 to 50 :")
print(array)

OUTPUT:

7. Create a 3x3 matrix with values ranging from 0 to 8


INPUT:

# Python program to create a 3x3 matrix with values ranging from 0 to 8!


print("Python program to create a 3x3 matrix with values ranging from 0 to 8!\n")
import numpy as np
# Create a 3x3 matrix with values ranging from 0 to 8
x = np.arange(0, 9).reshape(3, 3)
# Print the matrix
print(x)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

8. Create a 3x3 identity matrix


INPUT:

print("Python program to create a 3x3 identity matrix!\n")


import numpy as np
array_2D=np.identity(3)
print('3x3 matrix:')
print(array_2D)

OUTPUT:

9. Use Numpy to generate a random number between 0 to 1


INPUT:

print("Python program to generate a random number between 0 to 1!\n")


import numpy as np
rand_num = np.random.normal(0,1,1)
print("Random number between 0 and 1 : ")
print(rand_num)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

10. Use Numpy to generate an array of 25 random numbers sampled from standard
normal distribution
INPUT:

print("Python program to generate an array of 25 random numbers sampled from standard


normal distribution!\n")
import numpy as np
rand_num = np.random.normal(0,1,25)
print("25 random numbers from a standard normal distribution : ")
print(rand_num)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

11. Create a matrix 10x10 matrix values between 0 to 1


INPUT:

print("Python program to generate a matrix 10x10 matrix values between 0 to 1!\n")


import numpy as np
x = np.ones((10, 10))
x[1:-1, 1:-1] = 0
print(x)

OUTPUT:

12. Create an array of 20 linearly spaced points between 0 and 1


INPUT:
# Python program to create an array of 20 linearly spaced points between 0 and 1!
print("Python program to create an array of 20 linearly spaced points between 0 and 1!\n")

import numpy as np

# Create an array of 20 linearly spaced points between 0 and 1


num_line = np.linspace(0, 1, 20)

# Print the array


print(num_line)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
NAME: HARSH S SURYAVANSHI ROLL NO.67

13. Create an 2D array with 3 rows and 4 columns values starting from 12 to 25
INPUT:

print("Python program to create an 2D array with 3 rows and 4 columns values starting from 12
to 25!\n")
import numpy as np
x = np.arange(12, 24).reshape(3,4)
print(x)

OUTPUT:

14. Write code to Extract value 20 from 2d array


INPUT:

print("Python program to Extract value 20 from 2d array!\n")


import numpy as np
x = np.arange(12, 24).reshape(3,4)
print(x)
print("Extracted Value : ",x[2:,0])

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

15. Write code to Extract only first two rows


INPUT:

print("Python program to Extract only first two rows!\n")


import numpy as np
x = np.arange(12, 24).reshape(3,4)
print(x)
print("Extract first two rows : ")
r = x[:2]
print(r)

OUTPUT:

16. Write code to Extract first column


INPUT:

print("Python program to Extract first column!\n")


import numpy as np
x = np.arange(12, 24).reshape(3,4)
print(x)
print("Extract first column:")
r = x[:,[0]]
print®

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

17. Write code to Extract second column and Third column


INPUT:
print("Python program to Extract first column!\n")
import numpy as np
x = np.arange(12, 24).reshape(3,4)
print(x)
print("Extract second and third columns:")
r = x[:,[1,2]]
print(r)

OUTPUT:

18. Write code to Perform basic numpy operation on arr(1,25)


INPUT:
print("Python program to Perform basic numpy operation on arr(1,25)!\n")
import numpy as np
arr1 = np.arange(1,25)
print('First array:')
print(arr1)
print('\nSecond array:')
arr2 = np.arange(1,25)
print(arr2)
print('\nAdding the two arrays:')
print(np.add(arr1, arr2))
print('\nSubtracting the two arrays:')
print(np.subtract(arr1, arr2))
print('\nMultiplying the two arrays:')
print(np.multiply(arr1, arr2))
print('\nDividing the two arrays:')
print(np.divide(arr1, arr2))

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
NAME: HARSH S SURYAVANSHI ROLL NO.67

EXPERIMENT NO. 08

[1] Import Pandas Library


INPUT:
import pandas as pd
# Example: Create a simple DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [24, 27, 22],
'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)
print(df)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

[2] Create a series from a list, numpy array and dict


INPUT:

print("Python program to create a series from a list, numpy array and


dictionary!\n") import pandas as pd
import numpy as np
print('Series')
lst = ['A','B','C','D','E']
s = pd.Series(lst)
print(s)
print('')
print('Dictionary')
dct = {'G':2,'O':2,'A':1,'L':1}
s = pd.Series(dct)
print(s)
print('')
print('Numpy')
arr = np.array(['F','O','C','U','S'])
s = pd.Series(arr)
print(s)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

[3] Convert the index of a series into a column of a dataframe

INPUT:
# Python program to convert the index of a series into a column of a dataframe!
print("Python program to convert the index of a series into a column of a dataframe!\n")

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
'Name': ['ABC', 'DEF', 'GHI', 'XYZ'],
'Grade': ['A', 'A', 'C', 'B'],
'Subject': ['Python', 'Microprocessor', 'Java', 'Mathematics 4']
})
# Display the original DataFrame
print("Original DataFrame:")
print(df)
# Convert the index of the DataFrame into a column
df_reset = df.reset_index()
# Display the DataFrame after resetting the index
print("\nDataFrame after converting the index into a column:")
NAME: HARSH S SURYAVANSHI ROLL NO.67

print(df_reset)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

[4] Combine many series to form a dataframe


INPUT:

print("Python program to combine many series to form a dataframe!\n")


import pandas as pd
def createSeries (series_list):
series_list = pd.Series(series_list)
return series_list
students = createSeries(['ABC', 'DEF',
'GHI', 'JKL',
'MNO', 'PQR'])
subject = createSeries(['C++', 'C#',
'RUBY', 'SWIFT',
'GO', 'PYTHON'])
marks = createSeries([90, 30,
50, 70,
80, 60])
data = {"students": students,
"subject": subject,
"marks": marks}
df = pd.concat(data, axis = 1)
print(df)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

[5] Assign name to the series’ index


INPUT:
# Python program to assign name to the series' index!
import pandas as pd
# Create a pandas Series with some data
sr = pd.Series([10, 25, 3, 45])
# Assign custom index to the series
index_ = ['ABC', 'DEF', 'XZA', 'CDW']
sr.index = index_
# Display the series
print("Original Series:")
print(sr)
# Rename the series
result = sr.rename('Details')
# Display the renamed series
print("\nRenamed Series:")
print(result)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

[6] Get the items of series A not present in series B


INPUT:
# Python program to get the items of series A not present in series B!

import pandas as pd

# Create two Pandas Series


psA = pd.Series([2, 4, 8, 20, 10, 47, 99])
psB = pd.Series([1, 3, 6, 4, 10, 99, 50])

# Display Series A and B


print("Series A:")
print(psA)

print("\nSeries B:")
print(psB)

# Find items in Series A not present in Series B


print("\nItems of Series A not present in Series B:")
res = psA[~psA.isin(psB)]
print(res)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

[7] Get the minimum, 25th percentile, median, 75th, and max of a numeric series
INPUT:
# Python program to get the minimum, 25th percentile, median, 75th, and max of a numeric series!
import pandas as pd
import numpy as np
# Generate a random series of 20 numbers with a normal distribution
num_state = np.random.RandomState(100)
num_series = pd.Series(num_state.normal(10, 4, 20))
# Display the original series
print("Original Series:")
print(num_series)
# Calculate percentiles (0th, 25th, 50th, 75th, and 100th percentiles)
result = np.percentile(num_series, q=[0, 25, 50, 75, 100])
# Display the result
NAME: HARSH S SURYAVANSHI ROLL NO.67
print("\nMinimum, 25th percentile, median, 75th, and maximum of the given series:")
print(result)

OUTPUT:

[8] Explore various useful methods of Data series


INPUT:
# Python program to explore various useful methods of Data series!
import pandas as pd
import numpy as np
# Create a numpy array and convert it to a pandas Series
data = np.array(['Q', 'W', 'E', 'R', 'T', 'Y', 'A', 'S', 'D', 'F'])
ser = pd.Series(data, index=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
# Retrieve the first 5 elements
print("Retrieve the first 5 elements:")
print(ser[:5])
# Retrieve the element at the 5th location (index 5)
print("\nRetrieving the element at 5th location (index 5):")
NAME: HARSH S SURYAVANSHI ROLL NO.67
print(ser[5])
# Retrieve the last 3 elements
print("\nRetrieve the last 3 elements:")
print(ser[-3:])

OUTPUT:

EXPERIMENT NO: 09

1. Import Pandas Library


INPUT:

import pandas as pd

2. Import tips.csv file


INPUT:
import pandas as pd

# Importing the tips.csv file


df = pd.read_csv('tips.csv')
# Display the first few rows of the dataset
NAME: HARSH S SURYAVANSHI ROLL NO.67
print(df.head())
3. Display dataframe
INPUT:

print("Python program to display dataframe!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

4. Display total_bill & tips Column


INPUT:

print("Python program to display total_bill & tips Column!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df[['total_bill','tip']])

OUTPUT:

5. Calculate tip percent over total bill


INPUT:

print("Python program to calculate tip percent over total bill!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
df['tip_percent'] = df['tip'] / df['total_bill'] * 100
print(df)

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

6. Create a new column having tip percent


INPUT:

print("Python program to create a new column having tip percent!\n")

import
pandas as pd import csv
df = pd.read_csv('tips.csv')
df['tip_percent'] = df['tip'] / df['total_bill'] * 100
print(df)

OUTPUT:

7. Set new index Payment_ID of df


INPUT:

print("Python program to set new index Payment_ID of df!\n")


import pandas as pd
import csv
data = pd.read_csv("tips.csv")
data.set_index("tip", inplace = True)
NAME: HARSH S SURYAVANSHI ROLL NO.67

data.head()
print(data)
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

8. Display first 3 rows of df using numerical index


INPUT:

print("Python program to display first 3 rows of df using numerical index!\n")


import pandas as pd
import csv
df =
pd.read_csv('tips.csv')
print(df[:3])

OUTPUT:

9. Drop row having ID ‘Sun2959’


INPUT:

print("Python program to drop row having ID ‘Sun2959’!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df[df['Payment ID']=='Sun2959'])

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

10. Drop first two rows from df


INPUT:

print("Python program to drop first two rows from df!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.drop(index= df[:2].index))

OUTPUT:

11. Find records where total_bill is more than $40 and Day is ‘Sun’
INPUT:

print("Python program to find records where total_bill is more than $40 and Day is ‘Sun’!\n")
import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.loc[(df['total_bill'] > 40) & (df['day']=="Sun")])

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

12. Find records where tip>5 and Gender =’Female’


INPUT:

print("Python program to find records where tip>5 and Gender =’Female’!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.loc[(df['tip'] > 5) & (df['sex'] == 'Female')])

OUTPUT:

13. Apply useful methods on df


01. INPUT:

print("Python program to apply useful methods on df!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.nunique())

OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67

02. INPUT:

print("Python program to apply useful methods on df!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.groupby(by='sex')['total_bill'].max())

OUTPUT:

03. INPUT:

print("Python program to apply useful methods on df!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.describe())

OUTPUT:

04. INPUT:
print("Python program to apply useful methods on df!\n")
import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.sort_values(by='tip',ascending=False))

OUTPUT:
NAME: HARSH S SURYAVANSHI
ROLL NO.67

EXPERIMENT NO: 10
Menu driven program for data structure using built in function for link list,
stack and queue.

INPUT:

print("Python Menu driven program for data structure using built-in function for linked
list, stack, and queue!\n")

# Queue operations
queue = []

def enqueue(data):
queue.insert(0, data)

def dequeue():
if len(queue) > 0:
return queue.pop()
return "Queue Empty!"

def display_queue():
print("Elements in the queue are:")
for item in queue:
print(item)

# Stack operations
def is_empty_stack(stk):
return len(stk) == 0

def push(stk, item):


stk.append(item)

def pop(stk):
if is_empty_stack(stk):
print("Underflow")
else:
item = stk.pop()
print(f"Popped item is {item}")

def display_stack(stk):
if is_empty_stack(stk):
print("Stack is empty")
else:
print("Elements in the stack are:")
for item in reversed(stk):
print(item)

# Linked List operations


class Node:
NAME: HARSH S SURYAVANSHI
ROLL NO.67
def __init__(self, data=None, next=None):

self.data = data
self.next = next

class LinkedList:
def __init__(self):
self.head = None

def insert(self, data):


new_node = Node(data)
if self.head:
current = self.head
while current.next:
current = current.next
current.next = new_node
else:
self.head = new_node

def print_linked_list(self):
current = self.head
print("Elements in the linked list are:")
while current:
print(current.data)
current = current.next

# Menu driven function to interact with the user


def menu():
stk = []
ll = LinkedList()

while True:
print("\nMenu:")
print("1. Queue Operations")
print("2. Stack Operations")
print("3. Linked List Operations")
print("4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
print("\nQueue Operations")
print("1. Enqueue")
print("2. Dequeue")
print("3. Display Queue")
queue_choice = int(input("Enter your choice: "))
if queue_choice == 1:
data = int(input("Enter data to enqueue: "))
enqueue(data)
elif queue_choice == 2:
NAME: HARSH S SURYAVANSHI
ROLL NO.67
print(f"Popped Element: {dequeue()}")
elif queue_choice == 3:

display_queue()
else:
print("Invalid choice!")

elif choice == 2:
print("\nStack Operations")
print("1. Push")
print("2. Pop")
print("3. Display Stack")
stack_choice = int(input("Enter your choice: "))
if stack_choice == 1:
item = int(input("Enter item to push: "))
push(stk, item)
elif stack_choice == 2:
pop(stk)
elif stack_choice == 3:
display_stack(stk)
else:
print("Invalid choice!")

elif choice == 3:
print("\nLinked List Operations")
print("1. Insert into Linked List")
print("2. Display Linked List")
ll_choice = int(input("Enter your choice: "))
if ll_choice == 1:
data = int(input("Enter data to insert into Linked List: "))
ll.insert(data)
elif ll_choice == 2:
ll.print_linked_list()
else:
print("Invalid choice!")

elif choice == 4:
print("Exiting program.")
break
else:
print("Invalid choice!")

# Run the menu


if __name__ == "__main__":
menu()
NAME: HARSH S SURYAVANSHI
ROLL NO.67

OUTPUT:
NAME: HARSH S SURYAVANSHI
ROLL NO.67

EXPERIMENT NO: 11
Create a python multithreading environment that calculates volume of cube
and square
INPUT:
import time
import threading

# Function to calculate the square of each number in the list


def cal_sqre(num):
for n in num:
time.sleep(0.3)
print('Square is:', n * n)

# Function to calculate the cube of each number in the list


def cal_cube(num):
for n in num:
time.sleep(0.3)
print('Cube is:', n * n * n)

# Main function
if __name__ == "__main__":
arr = [4, 5, 6, 7, 2] # List of numbers

# Start the timer


t1 = time.time()

# Create threads for square and cube calculations


thread1 = threading.Thread(target=cal_sqre, args=(arr,))
thread2 = threading.Thread(target=cal_cube, args=(arr,))

# Start both threads


thread1.start()
thread2.start()
NAME: HARSH S SURYAVANSHI
ROLL NO.67

# Wait for both threads to finish

thread1.join()
thread2.join()

# Calculate and print the total time taken


print("Total time taken by threads is:", time.time() - t1)

OUTPUT:
NAME: HARSH S SURYAVANSHI
ROLL NO.67

EXPERIMENT NO: 12
Program to demonstrate CRUD (create, read, update and delete)
operations on database (SQLite/ MySQL) using python.

CREATE
INPUT:

# CREATE
print("Python Program to demonstrate CRUD (create, read, update and delete)
operations on database (SQLite/ MySQL) using python!\n")
import sqlite3

# Connect to SQLite database (creates a new database if it does not exist)


conn = sqlite3.connect('test.db')
print("Opened database successfully")

# Create a table in the database if it does not exist


conn.execute('''
CREATE TABLE IF NOT EXISTS team_data(
team TEXT,
country TEXT,
season INTEGER,
total_goals INTEGER
);''')
conn.commit()
print("Table created successfully")

# INSERT
print("\nInserting data into the table...")
conn.execute('''INSERT INTO team_data VALUES('Real Madrid','Spain',20,5);''')
conn.execute('''INSERT INTO team_data VALUES('Chelsea','UK',15,9);''')
conn.execute('''INSERT INTO team_data VALUES('FCB','Spain',10,15);''')
conn.commit()
print("Values inserted")

# READ
print("\nReading data from the table...")
print("Team Country Seasons Goals")
cursor = conn.execute('''SELECT * FROM team_data;''')
for i in cursor:
print(i[0] + " " + str(i[1]) + " " + str(i[2]) + " " + str(i[3]))

# UPDATE
print("\nUpdating data in the table...")
conn.execute('''UPDATE team_data SET team='Barca' WHERE team='FCB';''')

# Verify the update


cursor = conn.execute('''SELECT * FROM team_data;''')
print("\nAfter Updation")
NAME: HARSH S SURYAVANSHI
ROLL NO.67
for i in cursor:
print(i[0] + " " + str(i[1]) + " " + str(i[2]) + " " + str(i[3]))

# DELETE
print("\nDeleting data from the table...")
conn.execute('''DELETE FROM team_data WHERE season > 15;''')

# Verify the deletion


cursor = conn.execute('''SELECT * FROM team_data;''')
print("\nAfter Deletion")
for i in cursor:
print(i[0] + " " + str(i[1]) + " " + str(i[2]) + " " + str(i[3]))

# Close the database connection


conn.close()

OUTPUT:

Python Program to demonstrate CRUD (create, read, update and delete) operations on
database (SQLite/ MySQL) using python!

Opened database successfully


Table created successfully

Inserting data into the table...


Values inserted

Reading data from the table...


Team Country Seasons Goals
Real Madrid Spain 20 5
Chelsea UK 15 9
FCB Spain 10 15

Updating data in the table...

After Updation
Real Madrid Spain 20 5
Chelsea UK 15 9
Barca Spain 10 15

Deleting data from the table...

After Deletion
Real Madrid Spain 20 5
Chelsea UK 15 9

You might also like