Python Experiments.HARSH[1]
Python Experiments.HARSH[1]
67
EXPERIMENT NO. 1
1) Write a python program to input student details and display welcome message to newly added
student record.
INPUT:
print("\nWELCOME,",name+"!!")
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
INPUT:
print("Arithmetic Operations!\n")
# Arithmetic operations
add = num1 + num2
sub = num1 - num2
mul = num1 * num2
div = num1 / num2
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
INPUT:
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
INPUT:
# 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.'''
# 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)
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
INPUT:
# Create sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 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)
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
INPUT:
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:
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:
# Given list
given_list = ['a', 'b', 'c', 'a', 'a', 'b', 'd']
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
INPUT:
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
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")
printDict()
OUTPUT:
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
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
CONCEPT : METHODS
INPUT:
# 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)
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
CONCEPT : INHERITANCE
INPUT:
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
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
INPUT:
def sell(self):
print("Selling Price: {}".format(self. maxprice))
def setMaxPrice(self,
price): self. maxprice =
price
c = Computer()
c.sell()
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
CONCEPT : POLYMORPHISM
INPUT:
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()
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
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 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
# 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
number_lines = 0
number_words = 0
number_characters = 0
line = line.strip("\n") # Remove the newline character at the end of each line
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()
OUTPUT:
INPUT:
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
EXPERIMENT NO. 06
INPUT:
import smtplib
from_email = '[email protected]'
to_email = '[email protected]'
# Message content
msg['From'] = from_email
msg['To'] = to_email
# Login credentials (use an app password instead of your actual Gmail password)
# Confirmation message
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:
import numpy as np
NAME: HARSH S SURYAVANSHI ROLL NO.67
OUTPUT:
OUTPUT:
array=np.ones(10)*5
print("An array of 10 fives:")
print(array)
OUTPUT:
OUTPUT:
# 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:
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
OUTPUT:
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:
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
OUTPUT:
import numpy as np
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:
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
OUTPUT:
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
OUTPUT:
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
NAME: HARSH S SURYAVANSHI ROLL NO.67
EXPERIMENT NO. 08
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
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
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
import pandas as pd
print("\nSeries B:")
print(psB)
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:
OUTPUT:
EXPERIMENT NO: 09
import pandas as pd
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
OUTPUT:
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
import
pandas as pd import csv
df = pd.read_csv('tips.csv')
df['tip_percent'] = df['tip'] / df['total_bill'] * 100
print(df)
OUTPUT:
data.head()
print(data)
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
OUTPUT:
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
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
OUTPUT:
OUTPUT:
NAME: HARSH S SURYAVANSHI ROLL NO.67
02. INPUT:
OUTPUT:
03. INPUT:
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 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)
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def print_linked_list(self):
current = self.head
print("Elements in the linked list are:")
while current:
print(current.data)
current = current.next
while True:
print("\nMenu:")
print("1. Queue Operations")
print("2. Stack Operations")
print("3. Linked List Operations")
print("4. Exit")
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!")
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
# Main function
if __name__ == "__main__":
arr = [4, 5, 6, 7, 2] # List of numbers
thread1.join()
thread2.join()
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
# 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';''')
# DELETE
print("\nDeleting data from the table...")
conn.execute('''DELETE FROM team_data WHERE season > 15;''')
OUTPUT:
Python Program to demonstrate CRUD (create, read, update and delete) operations on
database (SQLite/ MySQL) using python!
After Updation
Real Madrid Spain 20 5
Chelsea UK 15 9
Barca Spain 10 15
After Deletion
Real Madrid Spain 20 5
Chelsea UK 15 9