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

Python Lab Experiments: Bachelor of Technology

The document summarizes 10 Python programming lab experiments conducted by Harsh Shukla. Each experiment demonstrates different Python concepts like data types, operators, strings, lists, tuples, dictionaries, and recursion. The experiments are numbered and signed by Harsh Shukla along with output showing the concepts covered in each experiment.

Uploaded by

study with Harsh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Python Lab Experiments: Bachelor of Technology

The document summarizes 10 Python programming lab experiments conducted by Harsh Shukla. Each experiment demonstrates different Python concepts like data types, operators, strings, lists, tuples, dictionaries, and recursion. The experiments are numbered and signed by Harsh Shukla along with output showing the concepts covered in each experiment.

Uploaded by

study with Harsh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

PYTHON LAB EXPERIMENTS

Bachelor of Technology
By

HARSH SHUKLA

0901IO211023
Under the Supervision of

DR. BHAGAT SINGH RAGHUWANSHI

PYTHON PROGRAMMING LAB(230406)


Department of Informa on
Technology

DEPARTMENT OF INFORMATION TECHNOLOGY


MADHAV INSTITUTE OF TECHNOLOGY &
SCIENCEGWALIOR, INDIA APRIL 2023
INDEX
S.NO PROGRAM SIGN
1. LAB EXPERIMENT 1ST

2. LAB EXPERIMENT 2ND

3. LAB EXPERIMENT 3RD

4. LAB EXPERIMENT 4TH

5. LAB EXPERIMENT 5TH

6. LAB EXPERIMENT 6TH

7. LAB EXPERIMENT 7TH

8. LAB EXPERIMENT 8TH

9. LAB EXPERIMENT 9TH

10. LAB EXPERIMENT 10TH


LAB PROGRAM 1ST
#Q1 - > Write a program to demonstrate different data types in python.
#BY HARSH SHUKLA(0901IO211023)
a=1
print(type(a))
a = 1.3
print(type(a))
a = 1+2j
print(type(a))
a = True
print(type(a))
a = None
print(type(a))
a = 'a'
print(type(a))
a = "Harsh";
print(type(a))
a = [1,2,3,4,5]
print(type(a))
a = (1,2,3,4,5)
print(type(a))
a = {"harsh":1, "aakash": 2 , "Ashish":3}
print(type(a))
a = {1,2,3,4,5}
print(type(a))
a = range(0,1)
print(type(a))
a = [1,"harsh","shukla",2]
a = frozenset(a)
print(type(a))
a = "Harsh shukla"
a = bytes(a , 'utf-8')
print(type(a))
a=5
a = bytes(a)
print(type(a))
a = [1,2,4,5]
a = bytearray(a)
print(type(a))
a = bytearray('XYZ', 'utf-8')
a = memoryview(a)
print(type(a))
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF LAB EXPERIMENT 1ST :

<class 'int'>
<class 'float'>
<class 'complex'>
<class 'bool'>
<class 'NoneType'>
<class 'str'>
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'set'>
<class 'range'>
<class 'frozenset'>
<class 'bytes'>
<class 'bytes'>
<class 'bytearray'>
<class 'memoryview'>

BY HARSH SHUKLA
0901IO211023

LAB EXPERIMENTS 2ND


#Q2-> Write a program to perform different arithme c operators in python
#BY HARSH SHUKLA ( 0901IO211023)
a = 20
b=5
print("Normal Addi on = ",a+b)
print("Normal Subtrac on = ",a-b)
print("Mul plica on = ",a*b)
print("Division = ",a/b)
print("remainder = ",a%b)
print("Power = ",b**2)
print("whole division = ",a//b)
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF LAB EXPERIMENT 2ND:

Normal Addition = 25
Normal Subtraction = 15
Multiplication = 100
Division = 4.0
remainder = 0
Power = 25
whole division = 4

BY HARSH SHUKLA
0901IO211023

LAB EXPERIMENT 3RD


#Q3-> Write a program to create, concatenate and print a string and accessing substring from a given string.
#BY HARSH SHUKLA(0901IO211023)
a1 = "Harsh "
a2 = "Shukla "
#concatiantion of strings

print("Concatination of two strings = ",a1+a2)


#Replication of strings
print("Replication of strings = ", a1*3)

'''error in concatination and replication of strings


print("Concatination of two strings = ",a1+2)ERROR IN THIS CASE
print("Replication of strings = ",a1*a2)ERROR IN THIS CASE'''

#Slicing of strings
print(a1[1:3])
print(a1[:3])
print(a1[:])#no parameter concept
print(a1[::-1])#reverse string concept
print(a1[0:8])#outof bound concept
print(a1[8:6])#No OUTPUT
print(a1[1:2:2])
print(a1[-6:-1:1])#printing the original name by using negative indexing
print(a1[-9:-9])#no output(empty output)
print(a1[-5:3])
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF LAB EXPERIMENT 3RD :

Concatination of two strings = Harsh Shukla


Replication of strings = Harsh Harsh Harsh
ar
Har
Harsh
hsraH
Harsh
“”
a
Harsh
“”
Ar

BY HARSH SHUKLA
0901IO211023

LAB EXPERIMENT 4TH

#Q4->Write a python program to create , append and remove lists in python


#BY HARSH SHUKLA(0901IO211023)
#lists in python
#List are mutuable datatypes
'''Taking input in list and priting elements in list'''
#through append function
l=[]
d = []
a = int(input("Enter how many elements you want ?? "))
for i in range(0,a):
l.append(int(input()))
print("Printing elements in list")
for i in range(0,a):
print(l[i])
#list functions
'''1. l.append(element to be inserted) -> it appends an element at the last position in the list
2. l.clear() -> it clears all element in the list(whole list is cleared)
3. l.copy() -> returns the copy of the list
4. l.count() -> returns the occurance of element specified in the list
5. l.extend() -> add elements at the last
6. l.index() -> return the index of first occurance of the element with value
7. l.insert() -> insert an element at any postion
8. l.pop() -> it removes the element at the specified position
9. l.remove() -> it removes the element with specified value
10.l.reverse() -> reverse all element of the list
11.l.sort() -> sort all elements of list'''
#1. clear() function
l.clear()
print(l)
print("list cleared successfuly")
#2. copy() function
d = ["harsh",'d',12,1.23,'d',"harsh"]
x = d.copy()
print(x)
#3. count() function
x= d.count('d')
print(x)
#4. extend() function
h = [5,6,8]
d.extend(h)
print(d)
#5. index() function
g = d.index("harsh")
print(g)
#6. insert() function
d.insert(2,"Shukla")
print(d)
#7. pop() function
ele = d.pop(2)
print(ele)
#8.remove() function
d.remove('d')
print(d)
#9.reverse() function
d.reverse()
print(d)
#10. Sort() function
h = [3,2,1]
h.sort()
print(h)
#11. Sort() list in decreasing order
l1 = ['A','a','B','c']
l1.sort(reverse = True)
print(l1)
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF LAB EXPERIMENT 4TH :


Enter how many elements you want ?? 6
1
2
3
4
5
6
Printing elements in list
1
2
3
4
5
6
[]
list cleared successfuly
['harsh', 'd', 12, 1.23, 'd', 'harsh']
2
['harsh', 'd', 12, 1.23, 'd', 'harsh', 5, 6, 8]
0
['harsh', 'd', 'Shukla', 12, 1.23, 'd', 'harsh', 5, 6, 8]
Shukla
['harsh', 12, 1.23, 'd', 'harsh', 5, 6, 8]
[8, 6, 5, 'harsh', 'd', 1.23, 12, 'harsh']
[1, 2, 3]
['c', 'a', 'B', 'A']

BY HARSH SHUKLA
0901IO211023

LAB EXPERIMENT 5TH

#Q5 -> Write a program to demonstrate working with tuples in python.


#BY HARSH SHUKLA(0901IO211023)
'''Tuples in Python are ordered , unchangable and allow duplicates'''
'''to append elements in a tuple their is one problem we can't change the tuple if created means we can't add
or remove
element in tuple if it is created'''
tuple1 = ("Harsh",1,1.23,True,"Harsh",1,2,4)
print(tuple1)
#ex->
#tuple1.append(23) #Error777() '''
l =[]
a = int(input("Enter how many elements you want : "))
for i in range(0,a):
l.append(int(input()))
print(type(l))
tuple2 = tuple(l)
print(tuple2)
print(type(tuple2))
#tuple has only two functions -> count() and index()
tuple3 = ("Harsh",2,8,6,"Shukla","Harsh")
a = input("Enter which element you want to count : ")
print(tuple3.count(a))
print(tuple3.index(2))
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF LAB EXPERIMENT 5TH :

('Harsh', 1, 1.23, True, 'Harsh', 1, 2, 4)


Enter how many elements you want : 5
1
2
3
4
5
<class 'list'>
(1, 2, 3, 4, 5)
<class 'tuple'>
Enter which element you want to count : Harsh
2
1

BY HARSH SHUKLA
0901IO211023

LAB EXPERIMENT 6TH

#Q6 -> Wrrite a program to demonstrate working with dictionaries in python.


#BY HARSH SHUKLA(0901IO211023)
dic = {}
type(dic)
dic = {"key":"harsh"}
print(dic)
dic = {'name':"harsh",'branch':"ITIOT","subject":"DS"}
print(dic)
dic1 = {123 : "harsh",True : 123}
print(dic1)
print(dic1[123])
print(dic1[True])
print(dic1[1])
dic2 = {"name": "Harsh Shukla","branch":"ITIOT","Subject":["hindi","english","CAM","IOT"],"name":"Akanchha
Maam"}
print(dic2["name"])
print(dic2["Subject"][1])
dic3 = {"name":["harsh","shukla","ji"],"branch":("ITIOT","CSE","IT+CSE"),
"Subject no":{101,102,103},"teacherName":{"ITIOT":"Kritika maam","CSE":"Pawan sir ","IT+CSE":"Aku
Maam"}}
print(dic3)
#if i want to access pawan sir
dic3["teacherName"]["IT+CSE"]
#if i want to add key
dic3["Makrs"] = [19,20,18]
print(dic3)
#agr mujhe koi key delete karni hai toh i will use del statement
del dic3["name"]
print(dic3)
#if i want to see all keys
print(dic3.keys())
list(dic3)
#if i want to see all values
print(dic3.values())
#if i want to see all items
print(dic3.items())
#poping teacherName using pop function
dic3.pop("teacherName")
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF LAB EXPERIMENT 6TH :

{'key': 'harsh'}
{'name': 'harsh', 'branch': 'ITIOT', 'subject': 'DS'}
{123: 'harsh', True: 123}
harsh
123
123
Akanchha Maam
english
{'name': ['harsh', 'shukla', 'ji'], 'branch': ('ITIOT', 'CSE', 'IT+CSE'), 'Subject no': {101, 102, 103}, 'teacherName':
{'ITIOT': 'Kritika maam', 'CSE': 'Pawan sir ', 'IT+CSE': 'Aku Maam'}}
{'name': ['harsh', 'shukla', 'ji'], 'branch': ('ITIOT', 'CSE', 'IT+CSE'), 'Subject no': {101, 102, 103}, 'teacherName':
{'ITIOT': 'Kritika maam', 'CSE': 'Pawan sir ', 'IT+CSE': 'Aku Maam'}, 'Makrs': [19, 20, 18]}
{'branch': ('ITIOT', 'CSE', 'IT+CSE'), 'Subject no': {101, 102, 103}, 'teacherName': {'ITIOT': 'Kritika maam', 'CSE':
'Pawan sir ', 'IT+CSE': 'Aku Maam'}, 'Makrs': [19, 20, 18]}
dict_keys(['branch', 'Subject no', 'teacherName', 'Makrs'])
dict_values([('ITIOT', 'CSE', 'IT+CSE'), {101, 102, 103}, {'ITIOT': 'Kritika maam', 'CSE': 'Pawan sir ', 'IT+CSE': 'Aku
Maam'}, [19, 20, 18]])
dict_items([('branch', ('ITIOT', 'CSE', 'IT+CSE')), ('Subject no', {101, 102, 103}), ('teacherName', {'ITIOT': 'Kritika
maam', 'CSE': 'Pawan sir ', 'IT+CSE': 'Aku Maam'}), ('Makrs', [19, 20, 18])])

BY HARSH SHUKLA
0901IO211023

LAB EXPERIMENT 7TH

#Q7-> Write a python program to find the factorial of a number using recursion
#BY HARSH SHUKLA(0901IO211023)
# Factorial of a number using recursion
def fact(n):
if n == 1:
return 1
else:
return n*fact(n-1)

num = int(input("Enter a number to find factorial : "))


if num < 0:
print("factorial of negative number doesn't exists")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", fact(num))
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF LAB EXPERIMENT 7TH :


O–1
Enter a number to find factorial : 5
The factorial of 5 is 120
BY HARSH SHUKLA
0901IO211023
O–2
Enter a number to find factorial : 0
The factorial of 0 is 1
BY HARSH SHUKLA
0901IO211023
O–3
Enter a number to find factorial : -20
factorial of negative number doesn't exists
BY HARSH SHUKLA
0901IO211023

LAB EXPERIMENT 8TH


#Q8 -> WAP to swap two integers without using a thrid varibable. The Swapping must be done in a different
method in a different class.
#BY HARSH SHUKLA(0901IO211023)
class inputs:
def __init__(self, number):
self.num = number

def returns(self):
return self.num

class Swap:
def Swaps(self, num1, num2): #here we use object as input
c = num1.returns()
d = num2.returns()
c= c + d
d= c - d
c=c-d
return c,d
a = int(input("Enter 1st Number : "))
b = int(input("Enter 2nd Number : "))
num1 = inputs(a) #we make two objects num1 and num2
num2 = inputs(b)
print("Varibles before swapping : ",a,b)
obj_Swap = Swap()
print("Variables after swapping :" , obj_Swap.Swaps(num1, num2))
print("BY HARSH SHUKLA")
print('0901IO211023')

OUTPUT OF LAB EXPERIMENT 8TH:


Enter 1st Number : 7
Enter 2nd Number : 8
Varibles before swapping : 7 8
Variables after swapping : (8, 7)

BY HARSH SHUKLA
0901IO211023

LAB EXPERIMENT 9TH

1st Method : (using in same class)

#1ST Method for finding Greater of two numbers in two different classes
#BY HARSH SHUKLA(0901IO211023)
class inputs:
def __init__(self,a,b):
self.a = a
self.b = b
def compare_Num(self):
if(self.a > self.b):
return str(self.a)+" "+"is greater then "+str(self.b)
else:
return str(self.b) + " " + "is greater then " + str(self.a)
a = int(input("Enter 1st Number : "))
b = int(input("Enter 2nd Number : "))
obj_inp = inputs(a,b)
print(obj_inp.compare_Num())
print("BY HARSH SHUKLA")
print('0901IO211023')

OUTPUT OF LAB EXPERIMENT 9TH METHOD 1ST:

Enter 1st Number : 5


Enter 2nd Number : 10
10 is greater then 5

BY HARSH SHUKLA
0901IO211023

2nd Method : (using in different)

#2nd Method for finding Greater of two numbers in two different classes
#BY HARSH SHUKLA(0901IO211023)
class inputs:
def __init__(self, number):
self.num = number

def returns(self):
return self.num

class Compares:
def compare(self, num1, num2): #here we use object as input
if num1.returns() > num2.returns():
return str(num1.returns()) +" "+"is greater then "+str(num2.returns())
else:
return str(num2.returns()) +" "+"is greater then "+str(num1.returns())
a = int(input("Enter 1st Number : "))
b = int(input("Enter 2nd Number : "))
num1 = inputs(a) #we make two objects num1 and num2
num2 =inputs(b)

obj_Compares = Compares()
print(obj_Compares.compare(num1, num2))

print("BY HARSH SHUKLA")


print('0901IO211023')

OUTPUT OF LAB EXPERIMENT 9TH METHOD 2ND :

Enter 1st Number : 4


Enter 2nd Number : 8
8 is greater then 4

BY HARSH SHUKLA
0901IO211023

LAB EXPERIMENT 10TH

#Q10 -> Write a python program to define a module and import a specific function
#in that module to another program
#BY HARSH SHUKLA (0901IO211023)

Calculator.py (Module)

def add(a,b):
return a+b
def sub(a,b):
return a-b
def multiply(a,b):
return a*b
def divide(a,b):
return a/b

main1.py(Module)

#we import Caluclator module.....


import Calculator as calci
result1 = calci.add(2,4)
print(result1)
result2 = calci.sub(5,9)
print(result2)
result3 = calci.multiply(10,9)
print(result3)
result4 = calci.divide(90,5)
print(result4)
print("BY HARSH SHUKLA")
print("0901IO211023")
OUTPUT OF LAB EXPERIMENT 10TH:

6
-4
90
18.0

BY HARSH SHUKLA
0901IO211023

LIST OF EXPERIMENTS COMPLETED


HARSH SHUKLA
0901IO211023
LIST OF MICRO PROGRAMS
MICRO PROGRAM 1ST
#1-> Demonstrate about fundamental Data types in Python Programming. (i.e., int, float, complex, bool and
string types)
#BY HARSH SHUKLA (0901IO211023)

a=1
print(type(a))
a = 1.3
print(type(a))
a = 1+2j
print(type(a))
a = True
print(type(a))
a = 'a'
print(type(a))
a = "Harsh";
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 1ST MICRO PROGRAM :

<class 'int'>
<class 'float'>
<class 'complex'>
<class 'bool'>
<class 'str'>
<class 'str'>

BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 2ND


#2 -> Demonstrate the working of following functions in Python.
# i) id( ) ii) type( ) iii) range( )
#BY HARSH SHUKLA (0901IO211023)

#demonstarting id()
var = 60
print(id(var)) #id function mainly discribes the address(unique id) of varibale

#demonstrarting type()
var1 = 'Harsh'
print(type(var1))
#type() describes the data type of the variable
var2 = 1+2j
print(type(var2))

#demonstarting range()
lst = []
lst = list(range(0,10)) #it give the number specifed from start , end - 1
print(lst)
print("BY HARSH SHUKLA")
print("0901IO211023")
OUTPUT OF 2ND MICRO PROGRAM :

2241509066832
<class 'str'>
<class 'complex'>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 3RD


#3rd->Write a Python program to demonstrate various base conversion functions.
#BY HARSH SHUKLA(0901IO211023)
def decimal_to_binary(decimal_num):
"""Converts decimal number to binary."""
return bin(decimal_num)

def binary_to_decimal(binary_num):
"""Converts binary number to decimal."""
return int(binary_num, 2)

def decimal_to_hex(decimal_num):
"""Converts decimal number to hexadecimal."""
return hex(decimal_num)

def hex_to_decimal(hex_num):
"""Converts hexadecimal number to decimal."""
return int(hex_num, 16)

# Examples
print(decimal_to_binary(9))
print(binary_to_decimal('0b1000'))
print(decimal_to_hex(189))
print(hex_to_decimal('0xfe'))
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 3RD MICRO PROGRAM :

0b1001
8
0xbd
254
BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 4TH


#Write a Python program to demonstrate various type conversion functions.
#BY HARSH SHUKLA (0901IO211023)

# Converting strings to integers


num1 = int('10')
num2 = int('1010', 2) # Convert binary string to integer

# Converting strings to floats


float1 = float('3.14')
float2 = float('2.71828e-3')

# Converting integers to strings


str1 = str(42)
str2 = str(0b1010) # Convert binary integer to string

# Converting floats to strings


str3 = str(3.14159)
str4 = str(2.71828e-3)

# Converting integers to floats


float3 = float(42)

# Converting floats to integers


num3 = int(3.14)

# Examples
print(num1)
print(num2)
print(float1)
print(float2)
print(str1)
print(str2)
print(str3)
print(str4)
print(float3)
print(num3)
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 4TH MICRO PROGRAM :

10
10
3.14
0.00271828
42
10
3.14159
0.00271828
42.0
3
BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 5TH


ARITHMATIC OPERATORS
'''+ , - , * , / , % , ** , //'''
a = 10
b = 20
print(a+b)
print(a-b)
print(a*b)
print(a/b)#it give a/b but in float form
print(a%b)#it give reamainder
print(a**2)# it give the power means a->number 2-> kitna divide karna hai
print(a//b)# it give value a/b in integer form
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.0 :

30
-10
200
0.5
10
100
0
BY HARSH SHUKLA
0901IO211023

INCREMENT/DECREMENT OPERATORS
''' = , += , -='''
#here ++ , -- (increment or decrement operator doesn't work)
a = 20
print(a)
a+=5 #a=a+5
print(a)
a-=5 #a = a - 5
print(a)
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.1 :

20
25
20
BY HARSH SHUKLA
0901IO211023

BITWISE OPERATORS
'''& , | , ^'''
a = 10
b=8
print(a&b) #with bin() we get number in numeric form
print(bin(a)) # bin() is a function to get the binary form of a number in 5 bit form
print(bin(b))
print(bin(a&b)) # ans would be in binary formate becuase we write bin() to convert ans

print(a|b) #with bin() we get number in numeric form


print(bin(a)) # bin() is a function to get the binary form of a number in 5 bit form
print(bin(b))
print(bin(a|b)) # ans would be in binary formate becuase we write bin() to convert ans

print(a^b) #with bin() we get number in numeric form


print(bin(a)) # bin() is a function to get the binary form of a number in 5 bit form
print(bin(b))
print(bin(a^b)) # ans would be in binary formate becuase we write bin() to convert ans
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.2 :


8
0b1010
0b1000
0b1000
10
0b1010
0b1000
0b1010
2
0b1010
0b1000
0b10
BY HARSH SHUKLA
0901IO211023

COMPARISON OPERATORS

'''> , < , >= , <= , == , !='''


x = 10
y = 20
print(x>y)
print(x<y)
print(x>=y)
print(x<=y)
print(x!=y)
print(x==y)
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.3 :


False
True
False
True
True
False

BY HARSH SHUKLA
0901IO211023

IDENTITY OPERATORS

''' is , is not '''


#important concepts about identity and equality operator
'''identity operator works on the address space of a variable but equality operator works on the value of the
variable '''
a = 10
b = 10
print( a is b) #address space of a and b are same because value is same therefore ans will be true
print(a==b) #yes true becasue value of both variables are same

#now for string


a = "hello"
b = "hello"
print(a is b) #true
print(a == b) #true
#now using whitespaces
a = "Hello World"
b = "Hello World"
print(a is b)
print(a == b)
#using multiple assign
a = b = "hello"
print(a is not b)
print(a!=b)
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.4 :

True
True
True
True
True
True
False
False

BY HARSH SHUKLA
0901IO211023

LOGICAL OPERATORS

''' and , or , not'''


a = 10
b = 20
print(a>b or a!=b or a==b) #if one condition from n conditions are true then or returns true and skip other
statements
print(a>b and a==b) #and check all n conditions are true or not if all true then it returns true otherwise false
print ( not a!=b) #reverse the condition true becomes false and false becomes true
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.5 :


True
False
False
BY HARSH SHUKLA
0901IO211023

MEMBERSHIP OPERATORS

''' in and not in'''


'''mainly used in pyhton data types like , string , list , tuples , dictonaries '''
string1 = "Hello"
print('h' in string1)
string1 = "Shukla"
print('h' in string1)
string1 = "JI"
print('j' not in string1)
l = [10,20,30,40] #this is list of numbers
print( 50 in l)
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.5 :


False
True
True
False
BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 6TH

'''Write Python programs to demonstrate the following:


i) input( )
ii) print( )
iii) ‘sep’ attribute
iv) ‘end’ attribute
v) replacement Operator ({ })'''
#BY HARSH SHUKLA
#0901IO211023

#input()
Name = input("Enter your Name : ")

#print()
print("Name Entered : ",Name)

#'sep' attribute
print("This is very costly",sep='!')

#'end' attribute

print("Hello Harsh how are you",end=',')

#replacement operator
name = "Harsh"
age = 18

print("My name is {0} and I am {1} years old.".format(name, age))

print("BY HARSH SHUKLA")


print("0901IO211023")

OUTPUT OF 6TH MICRO PROGRAM :

Enter your Name : HARSH SHUKLA


Name Entered : HARSH SHUKLA
This is very costly
Hello Harsh how are you,My name is Harsh and I am 18 years old.
BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 7TH


'''Demonstrate the following Conditional statements in Python with
suitable examples.
i) if statement
ii) if else statement
iii) if – elif – else statement '''
#BY HARSH SHUKLA (0901IO211023)

#if construct
age = 20

if age >= 18:


print("You are eligible to vote.")

#if else construct


age = 15

if age >= 18:


print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")

#if elif else construct

marks = 75

if marks >= 90:


grade = 'A'
elif marks >= 80:
grade = 'B'
elif marks >= 70:
grade = 'C'
elif marks >= 60:
grade = 'D'
else:
grade = 'F'

print("Your grade is", grade)

print("BY HARSH SHUKLA")


print("0901IO211023")

OUTPUT OF 7TH MICRO PROGRAM :

You are eligible to vote.


You are not eligible to vote yet.
Your grade is C
BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 8TH

'''Demonstrate the following Iterative statements in Python with


suitable examples.
i) while loop ii) for looP'''
#BY HARSH SHUKLA (0901IO211023)

#while loop
count = 0

while count < 5:


print(count)
count += 1

#for loop
fruits = ["apple", "banana", "cherry", "orange"]

for fruit in fruits:


print(fruit)
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 8TH MICRO PROGRAM :

0
1
2
3
4
apple
banana
cherry
orange
BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 9TH


'''Demonstrate the following control transfer statements in Python with
suitable examples.
i) break
ii) continue
iii) pass '''
#BY HARSH SHUKLA(0901IO211023)

#break
numbers = [1, 2, 3, 4, 5]

for num in numbers:


if num == 3:
break
print(num)

print("Loop exited.")

#continue
numbers = [1, 2, 3, 4, 5]

for num in numbers:


if num == 3:
continue
print(num)

print("Loop exited.")

#pass
def hello():
pass
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 9TH MICRO PROGRAM :

1
2
Loop exited.
1
2
4
5
Loop exited.
BY HARSH SHUKLA
0901IO211023
LIST OF MACRO PROGRAMS

MACRO PROGRAM 1ST

'''Write a Python program to demonstrate various ways of


accessing the string.
i) By using Indexing (Both Positive and Negative)
ii) By using Slice Operator '''
#BY HARSH SHUKLA (0901IO211023)

#String Indexing ( +ve and -ve)

my_string = "Harsh Shukla!"

# Accessing the first character of the string using positive indexing


print("First character using positive indexing:", my_string[0])

# Accessing the last character of the string using positive indexing


print("Last character using positive indexing:", my_string[-1])

# Accessing the second character of the string using negative indexing


print("Second character using negative indexing:", my_string[-12])

# Accessing the second last character of the string using negative indexing
print("Second last character using negative indexing:", my_string[-2])

# Accessing a substring using positiv"e indexing


print("Substring using positive indexing:", my_string[6:11])

# Accessing a substring using negative indexing


print("Substring using negative indexing:", my_string[-6:-1])

#String Slicing
st = "Harsh Shukla"
print(st[:3] + st[3:])
print(st[:3],st[3:])
print(st[::-1])
print(st[:-5] + st[-5:])
print(st[11:18])
print(st[12:21])
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 1ST MACRO PROGRAM :

First character using posi ve indexing: H


Last character using posi ve indexing: !
Second character using nega ve indexing: a
Second last character using nega ve indexing: a
Substring using posi ve indexing: Shukl
Substring using nega ve indexing: hukla
Harsh Shukla
Har sh Shukla
alkuhS hsraH
Harsh Shukla
a

BY HARSH SHUKLA
0901IO211023

MACRO PROGRAM 2ND

'''Demonstrate the following functions/methods which operates on


strings in Python with suitable examples:
i) len( ) ii) strip( ) iii) rstrip( ) iv) lstrip( ) v) find( ) vi) rfind( ) vii)
index( ) viii) rindex() ix) count( ) x) replace( ) xi) split( ) xii) join(
) xiii) upper( ) xiv) lower( ) xv) swapcase( ) xvi) title( ) xvii)
capitalize( ) xviii) startswith() xix) endswith() '''
#BY HARSH SHUKLA (0901IO211023)
# Define a sample string
my_string = " Hello World! "

# len()
print("Length of the string:", len(my_string))

# strip()
print("String after stripping whitespace:", my_string.strip())

# rstrip()
print("String after stripping whitespace from the right:", my_string.rstrip())

# lstrip()
print("String after stripping whitespace from the left:", my_string.lstrip())

# find()
print("Index of 'World' in the string:", my_string.find("World"))

# rfind()
print("Index of last 'o' in the string:", my_string.rfind("o"))

# index()
print("Index of 'World' in the string:", my_string.index("World"))

# rindex()
print("Index of last 'o' in the string:", my_string.rindex("o"))

# count()
print("Number of 'l' characters in the string:", my_string.count("l"))

# replace()
print("String after replacing 'World' with 'Universe':", my_string.replace("World", "Universe"))

# split()
print("List of words in the string:", my_string.split())

# join()
list_of_words = ["Hello", "World"]
print("String after joining the list of words:", " ".join(list_of_words))

# upper()
print("Uppercase version of the string:", my_string.upper())

# lower()
print("Lowercase version of the string:", my_string.lower())

# swapcase()
print("String with swapped case:", my_string.swapcase())

# title()
print("Titlecased version of the string:", my_string.title())

# capitalize()
print("Capitalized version of the string:", my_string.capitalize())

# startswith()
print("Does the string start with 'Hello'?", my_string.startswith("Hello"))

# endswith()
print("Does the string end with 'World!'?", my_string.endswith("World!"))
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 2ND MACRO PROGRAM :

Length of the string: 17


String a er stripping whitespace: Hello World!
String a er stripping whitespace from the right: Hello World!
String a er stripping whitespace from the le : Hello World!
Index of 'World' in the string: 9
Index of last 'o' in the string: 10
Index of 'World' in the string: 9
Index of last 'o' in the string: 10
Number of 'l' characters in the string: 3
String a er replacing 'World' with 'Universe': Hello Universe!
List of words in the string: ['Hello', 'World!']
String a er joining the list of words: Hello World
Uppercase version of the string: HELLO WORLD!
Lowercase version of the string: hello world!
String with swapped case: hELLO wORLD!
Titlecased version of the string: Hello World!
Capitalized version of the string: hello world!
Does the string start with 'Hello'? False
Does the string end with 'World!'? False

BY HARSH SHUKLA
0901IO211023
MACRO PROGRAM 3RD

'''Examples of map() , reduce() , and filter() and using map() , reduce() and filter() with lambda function'''
#BY HARSH SHUKLA (0901IO211023)
#map()
l = [1,2,3,4,5] #square of each element of list
def sqr(l):
l1 = []
for i in l:
l1.append(i**2)
return l1
print(sqr(l))

#map(fun(kuch bhee ho skta hai) , iterable(string , list , dic))


def sqr1(x):
return x**2
print(list(map(sqr1 , l)))

#we can also use lambda function in map()


print(list(map(lambda x : x**2 , l)))

#another example of map() with lambda function


print(list(map(lambda x : x , l)))

#adding of two lists


l11 = [2,4,5,7,8]
l22 = [4,7,9,1,3]
print(list(map(lambda x,y : x+y , l11, l22)))

#covert whole string into upper cased list


s = "harsh shukla"
print(list(map(lambda x : x.upper(),s)))

#reduce()
from functools import reduce
ll = [1,2,3,4,5,6]
print(reduce(lambda x,y : x + y , ll))

#more example of reduce()


print(reduce(lambda x,y : x*y , ll))

#to find maximum using reduce function


print(reduce(lambda x,y : x if x > y else y , ll))

#filter()
#to find even number from list
print(list(filter(lambda x : x%2==0 , ll)) )#even number

#to find negative number


print(list(filter(lambda x : x<0 , ll)))

#more example of filter function


l21 = ["harsh","shukla", "is ","my","name"]
print(list(filter(lambda x : len(x)<4 , l21)))
print("BY HARSH SHUKLA")
print("0901IO211023")
OUTPUT OF 3RD MACRO PROGRAM :

[1, 4, 9, 16, 25]


[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
[1, 2, 3, 4, 5]
[6, 11, 14, 8, 11]
['H', 'A', 'R', 'S', 'H', ' ', 'S', 'H', 'U', 'K', 'L', 'A']
21
720
6
[2, 4, 6]
[]
['is ', 'my']
BY HARSH SHUKLA
0901IO211023

MACRO PROGRAM 4TH

Numpy Array ( Pandas Library )

#introduction program of NumpyArray


#we are creating a 1-D Numpy Array and checking its type
#BY HARSH SHUKLA (0901IO211023)
import numpy as np
Array_1d = np.array([1,2,3,4,5])
print(Array_1d)
print(type(Array_1d))
#to check our array is 1D,2D or 3D so for this we use ndim parameter
print(Array_1d.ndim)
#now we are creating 2-D Numpy Array is the list of list
Array_2d = np.array([[1,2,3],[4,5,6]])
print(Array_2d)
print(Array_2d.ndim)
#to check the size of Array(kitne no of elements hai hamare array)
print(Array_1d.size)
print(Array_2d.size)
#to check the size of array ( means kitne no of rows hai or kitne no of columns)
#so we use shape function
#ka output tuple ke form me ata hai (row , column)
print(Array_1d.shape) #(1-d Array me sirif rows hoti hai toh column wala parameter khali hoga)
print(Array_2d.shape)
#now if we have to check the data type of array
#so we use dtype function
#output:mutlb array me jo values thi unka type integer hai or unko 32 bits ke form me represent kiya hai
print(Array_1d.dtype)
print(Array_2d.dtype)
print("BY HARSH SHUKLA")
print("0901IO211023")
OUTPUT OF 4TH MACRO PROGRAM - > 1.0:

[1 2 3 4 5]
<class 'numpy.ndarray'>
1
[[1 2 3]
[4 5 6]]
2
5
6
(5,)
(2, 3)
int32
int32

BY HARSH SHUKLA
0901IO211023

Numpy Array - > 2

#2nd Program of NumpyArray using more functions


#if we have an identity matrix means an array having all one's like ,
#BY HARSH SHUKLA (0901IO211023)
import numpy as np
Array_1s = np.array([[1,1,1],[1,1,1],[1,1,1]])
print(Array_1s)
#so we can see that we created a 3*3 identity matrix but if we have to create a identity matrix having many
rows and columns
#so for this we have to use ones()-> ones((row,column))-> rows is not compulsory by default single row
Arr_1s = np.ones(5)
#ones ka syntax important hai iske liye humko rows , columns ko tuple ke andar likhna hoga
#so, ones((row,column))
#important note -> ones() me jo matrix banegi uska type float hoga you can check the type of matrix by using
dtype function
print(Arr_1s)
#another example of ones
Arr_1es = np.ones((3,4))
print(Arr_1es)
#agr me chahata hun ki mujhe integer type ka matrix mile toh uske liye mujhe dtype change karna padega
Arr_1ss = np.ones((3,4),dtype = int)
print(Arr_1ss)
#if we have to create a matrix that contains all zeros
#so for this we use zeros() functions , iska sytanx same hai as ones() ka
Arr_0s = np.zeros((5,8), dtype = int)
print(Arr_0s)
#me iska dtype change karke bool me convert kar skta hun
Arr_0es = np.zeros((5,8),dtype = bool)
print(Arr_0es)
#agr me iska str me convert karta hun toh mujhe " "(empty) string milegi

#so agr mujhe numpy me empty matrix create karna hai toh iske liye hum empty() ka istemaal karenge but
empty matrix kuch nhi
#hota hai numpy me agr me empty() ka istemaal karta hun toh voh random value generate kar dega.........
Arr_emp = np.empty((3,5))
print(Arr_emp)
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 4TH MACRO PROGRAM - > 1.1:

[[1 1 1]
[1 1 1]
[1 1 1]]
[1. 1. 1. 1. 1.]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]
[[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]]
[[False False False False False False False False]
[False False False False False False False False]
[False False False False False False False False]
[False False False False False False False False]
[False False False False False False False False]]
[[6.23042070e-307 3.56043053e-307 1.60219306e-306 2.44763557e-307
1.69119330e-306]
[1.78022342e-306 1.05700345e-307 1.24610383e-306 8.45590539e-307
9.34607074e-307]
[6.89805151e-307 1.78020169e-306 1.42410974e-306 3.23796840e-317
2.02369289e-320]]

BY HARSH SHUKLA
0901IO211023

Numpy Array - > 3

#3rd Program of More Numpy Functions


#1st is arange functions
#so if we break arange -> then a + range() so it is like a range function giving starting , ending and step value
#so syntax will be -> arange(start,end,step)
#through arange function we can create a 1-D array
#BY HARSH SHUKLA (0901IO211023)
import numpy as np
arr = np.arange(1,13)
print(arr)
#printing even array upto 12
arr_1 = np.arange(0,13,2)#giving step value as 2
print(arr_1)

#linspace()
#is function me hame ek range deni padti hai or us range me humko kitne numbers chahiye voh bhee batana
hota hai
#or jo numbers ate hai voh random ate hai us given range me jo exits karte hai
arr_2 = np.linspace(1,6,5)
#iska mutlb 1 se 6 ke beech me mujhe 5 numbers chahiye voh 5 numbers kuch bhee ho skte hai
print(arr_2)

#reshape()
#important function is respace function hai because iske through hum 1-D array ko 2-D , or 3-D array me
convert kar skte hai
#Conversion of 1-D array to 2-D array
arr_3 = arr.reshape(3,4) #(row,column)
#reshape function me dhiyan ye rakhna hai ki jo product hoga row * column ka voh hamare total no of
elements ke equal hona
#chahiye
print(arr_3)
#Coversion of 1-D array to 3-D array
arr_4 = arr.reshape(3,2,2)#(3-D array kitne parts me divide hoga,row,column)
#sub ka multiplication 12 ke equal hona chahiye
print(arr_4)

#now using both arange() and reshape function we can create a 2-D array
arrd = np.arange(1,13).reshape(2,6)
print(arrd)

#ravel function
#agr hame 2-d ya 3-D array ko 1-D me convert karna hai toh iske liye hum reval function ka istemaal karenge
ar = arrd.ravel()
print(ar)

#flatten function
#flatten function me bhee hum 2-d ya 3-d array ko 1-D me convert kar skte hai but phir ravel or flatten me
difference kiya hai
#so flatten me hum ek paramter bhee de skte hai or mujhe iske bare me jankari nhi dhekna padega
are = arrd.flatten()
print(are)

#transpose function
#transpose function ke through hum rows ko column me interchange kar skte hai or vise versa
#ex-> (2,6) so it will change to (6,2)
ares = arrd.transpose()
print(ares)

#shortcut method for transpose function that is simply using T


ared = arrd.T #same kaam karega jaise hamara transpose function kar rha tha
print(ared)
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 4TH MACRO PROGRAM - > 1.2:

[ 1 2 3 4 5 6 7 8 9 10 11 12]
[ 0 2 4 6 8 10 12]
[1. 2.25 3.5 4.75 6. ]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[[ 1 2]
[ 3 4]]

[[ 5 6]
[ 7 8]]

[[ 9 10]
[11 12]]]
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
[ 1 2 3 4 5 6 7 8 9 10 11 12]
[ 1 2 3 4 5 6 7 8 9 10 11 12]
[[ 1 7]
[ 2 8]
[ 3 9]
[ 4 10]
[ 5 11]
[ 6 12]]
[[ 1 7]
[ 2 8]
[ 3 9]
[ 4 10]
[ 5 11]
[ 6 12]]

BY HARSH SHUKLA
0901IO211023

Numpy Array - > 4


#4th program of Mathmetical operations using numpy array
#we can add,subtract,multiply , divide two multidimensional array
#BY HARSH SHUKLA (0901IO211023)
import numpy as np
arr_1 = np.arange(1,13).reshape(3,4)
arr_2 = np.arange(1,13).reshape(3,4)
print(arr_1)
print(arr_2)
#for addition(two methods)
print(arr_1 + arr_2) #yaha 1st element of arr_1 is added with 1st element of arr_2 and so on
print(np.add(arr_1,arr_2))

#for subtraction(two methods)


print(arr_1 - arr_2) #yaha 1st element of arr_1 is subtracted with 1st element of arr_2 and so on
print(np.subtract(arr_1,arr_2))

#for multiplication(two methods)


print(arr_1 * arr_2) #yaha 1st element of arr_1 is Multiplied with 1st element of arr_2 and so on
print(np.multiply(arr_1,arr_2))

#for division( two methods)


print(arr_1 / arr_2) #yaha 1st element of arr_1 is Multiplied with 1st element of arr_2 and so on
print(np.divide(arr_1,arr_2)) #output float me ayega

#max() -> if we have to find the max value in an array


print(arr_1.max())
#if we have to find at which index maximum value exists ......
#so for this we use argmax()
print(arr_1.argmax())

#agr hame har row/column me maximum value find karni hai toh iske liye hum max(axis) parameter denge
#for axis = 0 -> for column
#for axis = 1 -> for row
print(arr_1.max(axis = 0))
print(arr_1.max(axis = 1))

#same for minimum ............ min() , argmin(), min(axis - 0 or axis = 1)

#to sum all elements of matrix we use sum function


print(arr_1.sum())
#ab agr mujhe column ke across sum chahiye ya phir row ke across toh iske liye me sum me axis parameter ka
istemaal karunga
print(arr_1.sum(axis = 0 )) #for sum of columns
print(arr_1.sum(axis = 1))# for sum of rows

#we can find the mean/average of matrix using mean()


print(np.mean(arr_1))

#if we have to find the square root of each and every element of matrix we use sqrt function
print(np.sqrt(arr_1))

#to find the standard division of matrix


print(np.std(arr_1))

#to find the exponent of each element of matrix -> e^x


print(np.exp(arr_1))

#to find the log base e of each element of matrix


print(np.log(arr_1))

#to find the log base 10 of each element of matrix


print(np.log10(arr_1))
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 4TH MACRO PROGRAM - > 1.3:

[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ 2 4 6 8]
[10 12 14 16]
[18 20 22 24]]
[[ 2 4 6 8]
[10 12 14 16]
[18 20 22 24]]
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
[[ 1 4 9 16]
[ 25 36 49 64]
[ 81 100 121 144]]
[[ 1 4 9 16]
[ 25 36 49 64]
[ 81 100 121 144]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
12
11
[ 9 10 11 12]
[ 4 8 12]
78
[15 18 21 24]
[10 26 42]
6.5
[[1. 1.41421356 1.73205081 2. ]
[2.23606798 2.44948974 2.64575131 2.82842712]
[3. 3.16227766 3.31662479 3.46410162]]
3.452052529534663
[[2.71828183e+00 7.38905610e+00 2.00855369e+01 5.45981500e+01]
[1.48413159e+02 4.03428793e+02 1.09663316e+03 2.98095799e+03]
[8.10308393e+03 2.20264658e+04 5.98741417e+04 1.62754791e+05]]
[[0. 0.69314718 1.09861229 1.38629436]
[1.60943791 1.79175947 1.94591015 2.07944154]
[2.19722458 2.30258509 2.39789527 2.48490665]]
[[0. 0.30103 0.47712125 0.60205999]
[0.69897 0.77815125 0.84509804 0.90308999]
[0.95424251 1. 1.04139269 1.07918125]]

BY HARSH SHUKLA
0901IO211023

Numpy Array - > 5

#5th pro of NumpyArray Slicing


#BY HARSH SHUKLA (0901IO211023)
import numpy as np
mx = np.arange(1,101).reshape(10,10)
#if i want to access 1 element
print(mx[0,0]) #[row,column]
#and if we check dimension
print(mx[0,0].ndim) #if ndim is zero then the quantity is scalar

#if we want single row


print(mx[0])
#if we want single column
#[:,0] -> we want whole row of which column that is zero
print(mx[:,0]) #but ye column 1-D me aya
#hame ye 2-D me chahiye toh
print(mx[:,0:1]) #this is in 2-D how??
#check
print(mx[:,0:1].ndim)
#if we want 1,2,3 rows and 2,3,4 columns
print(mx[1:4,2:5])
#if we want all rows but only two colums
print(mx[:,0:2])
#if we want to access whole matrix
print(mx[:])
#two more methods to access whole matrix
print(mx[::])
print(mx[:,:])

#matrix me harek element ko store karne me kitna bit laga hai for this we use itmesize
print(mx.itemsize)#the output is 4 but how ??
#so phele hum dtype ke through ye dhek lete hai ki total kitne bit le rha hai ye matrix
print(mx.dtype) #so the output is 32
#so me divide 32/8 and ans is 4
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 4TH MACRO PROGRAM - > 1.4:

1
0
[ 1 2 3 4 5 6 7 8 9 10]
[ 1 11 21 31 41 51 61 71 81 91]
[[ 1]
[11]
[21]
[31]
[41]
[51]
[61]
[71]
[81]
[91]]
2
[[13 14 15]
[23 24 25]
[33 34 35]]
[[ 1 2]
[11 12]
[21 22]
[31 32]
[41 42]
[51 52]
[61 62]
[71 72]
[81 82]
[91 92]]
[[ 1 2 3 4 5 6 7 8 9 10]
[ 11 12 13 14 15 16 17 18 19 20]
[ 21 22 23 24 25 26 27 28 29 30]
[ 31 32 33 34 35 36 37 38 39 40]
[ 41 42 43 44 45 46 47 48 49 50]
[ 51 52 53 54 55 56 57 58 59 60]
[ 61 62 63 64 65 66 67 68 69 70]
[ 71 72 73 74 75 76 77 78 79 80]
[ 81 82 83 84 85 86 87 88 89 90]
[ 91 92 93 94 95 96 97 98 99 100]]
[[ 1 2 3 4 5 6 7 8 9 10]
[ 11 12 13 14 15 16 17 18 19 20]
[ 21 22 23 24 25 26 27 28 29 30]
[ 31 32 33 34 35 36 37 38 39 40]
[ 41 42 43 44 45 46 47 48 49 50]
[ 51 52 53 54 55 56 57 58 59 60]
[ 61 62 63 64 65 66 67 68 69 70]
[ 71 72 73 74 75 76 77 78 79 80]
[ 81 82 83 84 85 86 87 88 89 90]
[ 91 92 93 94 95 96 97 98 99 100]]
[[ 1 2 3 4 5 6 7 8 9 10]
[ 11 12 13 14 15 16 17 18 19 20]
[ 21 22 23 24 25 26 27 28 29 30]
[ 31 32 33 34 35 36 37 38 39 40]
[ 41 42 43 44 45 46 47 48 49 50]
[ 51 52 53 54 55 56 57 58 59 60]
[ 61 62 63 64 65 66 67 68 69 70]
[ 71 72 73 74 75 76 77 78 79 80]
[ 81 82 83 84 85 86 87 88 89 90]
[ 91 92 93 94 95 96 97 98 99 100]]
4
int32

BY HARSH SHUKLA
0901IO211023

Numpy Array - > 6

#8th pro of working with random data in NumpyArray


#so for working with random data first we have to import random library
#BY HARSH SHUKLA (0901IO211023)
import numpy as np
import random #me iska alias name nhi de skta hun
#this creates a 1-D array
print(np.random.random(1)) #random() -> (1 se 0 se beech me koi bhee value de dega)
#2-d array
print(np.random.random((3,3)))
#if i want only integer value between a particular range
print(np.random.randint(1,5)) #ek se 5 ke beach me koi bhee 1 value a jayegi but voh integer hogi
#2-D array of random integers
print(np.random.randint(1,5,(4,4)))
#3-d array of randome integers
print(np.random.randint(1,5,(3,3,4)))
#ab dikkat ho ye rhi hai ki bar bar radom array generate ho rha hai but agr me chahta hun ki jo random array
generate
#hua hai usko me vapas use karu
#toh uske liye hamare pass seed() function hota hai jo 2**32-1 values tak value la skta hai
np.random.seed(10)
print(np.random.randint(1,5,(4,4)))
np.random.seed(10)
print(np.random.randint(1,5,(4,4)))
#so agr hum dekho toh vapas vohi same random array a rha hai

#rand function
print(np.random.rand(3)) #so 1-d array create ho jayega or range (1,0) ke beech me koi bhee 3 numbers
print(np.random.rand(3,3)) #2-d array of size 3*3
print(np.random.rand(2,3,3)) #3-d array of size (3*3) * 2

#randn function
#ye humare random value deta hai (0,1) ke beech me but ye (+,-) values dono deta hai
print(np.random.randn(3)) #it returns the samples of standard normal distribution

#choice function
#ye hamare diye gaye sequence me se koi bhee ek value return kar dega
lst = [1,2,3,4]
print(np.random.choice(lst))
#clearing the concept of choice()
for i in range(20):
print(np.random.choice(lst))

#permutaion function
print(np.random.permutation(lst))# it returns the random permutation of given sequence
#clearing the concept of permutation()
for i in range(20):
print(np.random.permutation(lst))
print("HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 4TH MACRO PROGRAM - > 1.5:

[0.38656949]
[[0.15817412 0.60901665 0.87186768]
[0.3439397 0.05934477 0.6286641 ]
[0.76638949 0.32837078 0.66510341]]
4
[[3 2 2 3]
[1 3 2 4]
[4 3 1 3]
[2 1 4 2]]
[[[1 4 1 2]
[1 3 4 3]
[1 2 3 1]]

[[2 1 2 4]
[3 4 1 2]
[1 4 2 1]]

[[3 3 4 3]
[3 1 3 4]
[2 4 1 1]]]
[[2 2 1 4]
[1 2 4 1]
[2 2 1 2]
[2 3 1 2]]
[[2 2 1 4]
[1 2 4 1]
[2 2 1 2]
[2 3 1 2]]
[0.16911084 0.08833981 0.68535982]
[[0.95339335 0.00394827 0.51219226]
[0.81262096 0.61252607 0.72175532]
[0.29187607 0.91777412 0.71457578]]
[[[0.54254437 0.14217005 0.37334076]
[0.67413362 0.44183317 0.43401399]
[0.61776698 0.51313824 0.65039718]]

[[0.60103895 0.8052232 0.52164715]


[0.90864888 0.31923609 0.09045935]
[0.30070006 0.11398436 0.82868133]]]
[ 0.1327083 -0.47614201 1.30847308]
1
1
2
1
4
1
1
3
1
3
3
1
4
2
1
4
2
3
3
2
3
[2 4 1 3]
[2 3 4 1]
[1 4 2 3]
[2 3 1 4]
[1 4 2 3]
[3 1 2 4]
[3 4 1 2]
[3 1 4 2]
[4 1 2 3]
[2 4 3 1]
[4 1 2 3]
[3 1 4 2]
[4 2 3 1]
[4 3 2 1]
[3 4 2 1]
[2 4 3 1]
[3 1 4 2]
[3 2 4 1]
[3 1 4 2]
[2 3 4 1]
[2 1 4 3]
HARSH SHUKLA
0901IO211023

MACRO PROGRAM 5TH

Pandas Series - > 1

#1st program of Pandas Series (introduction)


#to convert list data structure into pandas Series
import pandas as pd
lst = [1,2,3,6,9]
var = pd.Series(lst)
print(var)
print(type(var))
print("HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 5TH MACRO PROGRAM - > 1.0:

0 1
1 2
2 3
3 6
4 9
dtype: int64
<class 'pandas.core.series.Series'>
HARSH SHUKLA
0901IO211023

Pandas Series - > 2

#6th program of Pandas Series


#to convert different data types into pandas Series like dictionary , single integer and so on

#doubt how to change the index of dictonary ............... ??


import pandas as pd
dic = {"J":"January","F":"Feburary","M":"March"}
var = pd.Series(dic,index = [1,2,3]) #if we have mixed data types then dtype field gives object as data type
print(var)
var = pd.Series(12,index = ["a"]) #if we have mixed data types then dtype field gives object as data type
#index paramter me humne list ke form me pass karna hai jp bhee index aap pass karoge.....
print(var)
print("HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 5TH MACRO PROGRAM - > 1.1:

1 NaN
2 NaN
3 NaN
dtype: object
a 12
dtype: int64
HARSH SHUKLA
0901IO211023

Pandas DataFrames - > 3

#9th program in pandas DataFrame


#to insert column in Pandas DataFrame using insert function which have 3 parameters
#1st parameter -> kis index pr rakhna hai naye column ko
#2nd paramter -> name of column
#3rd parameter -> data in that column
import pandas as pd
dic = {"A":[1,2,3,4],"B":[5,6,7,8]}
var = pd.DataFrame(dic)
var.insert(2,"C",[1,9,8,10])
var.insert(3,"D",[1.2,1.4,2.4,3])
print(var)
print("HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 5TH MACRO PROGRAM - > 1.2:

0
0 1
1 3
2 4
3 5
4 6
<class 'pandas.core.frame.DataFrame'>
HARSH SHUKLA
0901IO211023

Pandas DataFrames - > 4

#7th program of Python Pandas DataFrame


#using Arithmatic Operators in pandas DataFrame like additon , subtracion , multiplication and division , floor
division
#exponential
#if we add two data frames then the result of integer will be integer
import pandas as pd
dic = {"A":[1,2,3,4],"B":[5,6,7,8]}
var = pd.DataFrame(dic)
var["C"] = var["A"] + var["B"] #synatax to add two columns and generate thrid column(result)
print(var)

#8th program of python pandas dataFrame


#to use logical operators in DataFrame
import pandas as pd
dic = {"A":[1,2,3,4],"B":[5,6,7,8]}
var = pd.DataFrame(dic)
var["C"] = var["A"] != 2
var["D"] = var["B"] > 6
print(var)
#9th program in pandas DataFrame
#to insert column in Pandas DataFrame using insert function which have 3 parameters
#1st parameter -> kis index pr rakhna hai naye column ko
#2nd paramter -> name of column
#3rd parameter -> data in that column
import pandas as pd
dic = {"A":[1,2,3,4],"B":[5,6,7,8]}
var = pd.DataFrame(dic)
var.insert(2,"C",[1,9,8,10])
var.insert(3,"D",[1.2,1.4,2.4,3])
print(var)

print("HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 5TH MACRO PROGRAM - > 1.3:

A B C
0 1 5 6
1 2 6 8
2 3 7 10
3 4 8 12

A B C D
0 1 5 True False
1 2 6 False False
2 3 7 True True
3 4 8 True True

A B C D
0 1 5 1 1.2
1 2 6 9 1.4
2 3 7 8 2.4
3 4 8 10 3.0

HARSH SHUKLA
0901IO211023

Pandas DataFrames - > 5

#1st program of merging of two data frames


#for merging of DataFrames 1 common id should be their
#means a common part that can be used to merge both DataFrames
import pandas as pd
# var1 = pd.DataFrame({"A":[1,2,3],"B":[3,4,5]})
# var2 = pd.DataFrame({"A":[1,2,3],"C":[6,7,8]})
# print(pd.merge(var1,var2,on="A"))
#agr me common data nhi deta hun toh
#so jitna data common hoga uske according merging hogi
var1 = pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]})
var2 = pd.DataFrame({"A":[1,2,3],"C":[6,7,8]})
print(pd.merge(var1,var2))#on is not compulsory
#how parameter NaN value ko bhee batata hai jo chut gai hai
print(pd.merge(var2,var1,how = "left", indicator= True))
print(pd.merge(var2,var1,how = "right",indicator = True))
#ab agr mere dono data frames de same keys hai means i am not talking about value of key only name of key is
same
#then if i merge their will no output reflected then what to do for this we use left_index = Ture and right_index
= True
var12 = pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]})
var23 = pd.DataFrame({"A":[1,2,3,5],"B":[6,7,8,9]})

print(pd.merge(var12,var23,left_index = True , right_index = True,suffixes = ["Name","id"])) #isse hoga ye ki


har key ki value reflect hogi
#but aisa karne se hamari key ka name ajjeb se ho jayega for this we will use suffixes to change the name of
key

#Concat -> common part nhi dhekte hai bus do Series or data frames ko join kar deta hai
#first we concat two series
s1 = pd.Series([1,2,3,4])
s2 = pd.Series([5,6,7,8])
print(pd.concat([s1,s2]))#ek khas bat ki jab hum do Series ko add kar rhe honge toh humme unko list ke
through pass karna hai
#we can also concat two DataFrames
var11 = pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]})
var22 = pd.DataFrame({"A":[1,2,3,5],"C":[6,7,8,9]})
print(pd.concat([var11,var22],join = "outer")) #outer by default hota hai inner se sub NaN hut jayega
print(pd.concat([var11,var22],join = "inner",axis = 1)) #axis 1 dene se column wise a raha hai or axis 0 dene se
row wise ata
#agr mujhe NaN wala data hatana hai toh uske liye hum join kar istemaal karenge

#join two data Frames


d1 = pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]})
d2 = pd.DataFrame({"C":[2,8,9,5],"D":[10,20,30,50]})
#join karrate vakat hum do data frames me same key nhi de skte hai
print(d1.join(d2))
d11 = pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]},index = ["a","b","c","d"])
d22 = pd.DataFrame({"C":[2,8],"D":[10,20]},index = ["a","b"])
print(d11.join(d22,how= "left"))
print(d11.join(d22,how= "inner"))
#hum join de saath how ka bhee istemaal kar skte hai
#how ke parameters -> left , right, inner(intersection ) , outer(union)
#agr hamari column ki value same ho jati hai join me toh toh ek error de dega toh iske liye hame left suffix or
right suffix ka use
#karna padega
d12 = pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]},index = ["a","b","c","d"])
d21 = pd.DataFrame({"A":[2,8],"D":[10,20]},index = ["a","b"])
print(d12.join(d21,rsuffix = "_21"))

#Append
#join me agr do column ke name same ho ja rhe the toh error a rha tha ya phir usko humko suffix ke through
solve karna pad rha tha
#but append me agr do column ka name bhee same hai toh koi dikkat nhi hai
a1= pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]})
a2 = pd.DataFrame({"A":[2,8],"D":[10,20]})
print(a1.append(a2,ignore_index = True))#ignore_index se hamari index sequence me ayegi........
print("HARSH SHUKLA")
print("0901IO211023")
OUTPUT OF 5TH MACRO PROGRAM - > 1.4:

A B C
0 1 3 6
1 2 4 7
2 3 5 8
A C B _merge
0 1 6 3 both
1 2 7 4 both
2 3 8 5 both
A C B _merge
0 1 6.0 3 both
1 2 7.0 4 both
2 3 8.0 5 both
3 4 NaN 6 right_only
AName BName Aid Bid
0 1 3 1 6
1 2 4 2 7
2 3 5 3 8
3 4 6 5 9
0 1
1 2
2 3
3 4
0 5
1 6
2 7
3 8
dtype: int64
A B C
0 1 3.0 NaN
1 2 4.0 NaN
2 3 5.0 NaN
3 4 6.0 NaN
0 1 NaN 6.0
1 2 NaN 7.0
2 3 NaN 8.0
3 5 NaN 9.0
A B A C
0 1 3 1 6
1 2 4 2 7
2 3 5 3 8
3 4 6 5 9
A B C D
0 1 3 2 10
1 2 4 8 20
2 3 5 9 30
3 4 6 5 50
A B C D
a 1 3 2.0 10.0
b 2 4 8.0 20.0
c 3 5 NaN NaN
d 4 6 NaN NaN
A B C D
a 1 3 2 10
b 2 4 8 20
A B A_21 D
a 1 3 2.0 10.0
b 2 4 8.0 20.0
c 3 5 NaN NaN
d 4 6 NaN NaN
C:\Users\hs081\PycharmProjects\Merging and Joining of DataFrames\main.py:59: FutureWarning: The
frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat
instead.
print(a1.append(a2,ignore_index = True))#ignore_index se hamari index sequence me ayegi........
A B D
0 1 3.0 NaN
1 2 4.0 NaN
2 3 5.0 NaN
3 4 6.0 NaN
4 2 NaN 10.0
5 8 NaN 20.0

HARSH SHUKLA
0901IO211023

Pandas DataFrames - > 6

#reshaping of pandas file ..(data Frame)


#means agr horizontal hai toh vertical bana denge ....
import pandas as pd
dic = {"days":[1,2,3,4,5,6],"eng":[12,14,15,17,13,10],"maths":[17,19,20,19,18,19]}
var = pd.DataFrame(dic)
print(var)
#abhi ye var horizontal me hai agr mujhe is var ko reshape karna hai means horizontal ko vertical me convert
karna hai toh
#uske liye me melt function ka istemaal karunga
print(pd.melt(var))
#here id acts as a key
print(pd.melt(var,id_vars = ["days"],var_name = "subject",value_name= "marks"))

#pivot function -> used for data arrangment and reshaping


#isme 2 paramters is must hai
#1st -> index and 2nd-> columns
dic1 =
{"days":[1,2,3,4,5,6],"Stu":["a","b","a","c","b","c"],"eng":[12,14,15,17,13,10],"maths":[17,19,20,19,18,19]}
var1 = pd.DataFrame(dic1)
print(var1.pivot(index = "days",columns = "Stu"))
#agr mujhe ek particular data chahiye toh iske liye me value keyword ka istemaal karunga
print(var1.pivot(index = "days",columns = "Stu",values = "eng"))
#agr mujhe koi arithmatic operation perform karna hai toh iske liye hum pivot_table function ka istemaal
karenge
#aggfun ke through me koi bhee operation perform karva skta hun
print(var1.pivot_table(index = "Stu",columns = "days",aggfunc = "min"))
#max,mean,sum etc.
print("HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 5TH MACRO PROGRAM - > 1.5:


days eng maths
0 1 12 17
1 2 14 19
2 3 15 20
3 4 17 19
4 5 13 18
5 6 10 19
variable value
0 days 1
1 days 2
2 days 3
3 days 4
4 days 5
5 days 6
6 eng 12
7 eng 14
8 eng 15
9 eng 17
10 eng 13
11 eng 10
12 maths 17
13 maths 19
14 maths 20
15 maths 19
16 maths 18
17 maths 19
days subject marks
0 1 eng 12
1 2 eng 14
2 3 eng 15
3 4 eng 17
4 5 eng 13
5 6 eng 10
6 1 maths 17
7 2 maths 19
8 3 maths 20
9 4 maths 19
10 5 maths 18
11 6 maths 19
eng maths
Stu a b c a b c
days
1 12.0 NaN NaN 17.0 NaN NaN
2 NaN 14.0 NaN NaN 19.0 NaN
3 15.0 NaN NaN 20.0 NaN NaN
4 NaN NaN 17.0 NaN NaN 19.0
5 NaN 13.0 NaN NaN 18.0 NaN
6 NaN NaN 10.0 NaN NaN 19.0
Stu a b c
days
1 12.0 NaN NaN
2 NaN 14.0 NaN
3 15.0 NaN NaN
4 NaN NaN 17.0
5 NaN 13.0 NaN
6 NaN NaN 10.0
eng maths
days 1 2 3 4 5 6 1 2 3 4 5 6
Stu
a 12.0 NaN 15.0 NaN NaN NaN 17.0 NaN 20.0 NaN NaN NaN
b NaN 14.0 NaN NaN 13.0 NaN NaN 19.0 NaN NaN 18.0 NaN
c NaN NaN NaN 17.0 NaN 10.0 NaN NaN NaN 19.0 NaN 19.0

HARSH SHUKLA
0901IO211023

You might also like