Learn Python

DAY 1

#interpreter - Python, R
#compiler - Java, C C++
print(5-3) #adding 5 and 3
print()
print("5+3=",5+3,"and 5*6=",5*6) #you can use " or '
print(5/0)
print("48578wefoiwefue89guaiuodgjadfgj")

# comments sdjfhasdufasodihs
# mistake
#syntax - grammar
#
#mistake
print('Hello '
'Good evening') #single line text
print("Hi")
print('''How
are
you?''')
print("""I am fine""") #multi line
num1 = 4
print("Data type of num1 is ",type(num1))
'''variable names has to begin with either an alphabet
or with _. It can contain, numbers, alphabets and _ '''

num2 = 3
print(4+3)
print("5+4=",5+4)
''' how
are
you
i am fine'''
# Five basic datatypes in Python
num1 = 4
print("Data type of num1 is ",type(num1))
num1 = 4.0
print("Data type of num1 is ",type(num1))
num1 = 4j
print("Data type of num1 is ",type(num1))
num1 = "4"
print("Data type of num1 is ",type(num1))
num1 = True
print("Data type of num1 is ",type(num1))

cost = 25.897896876;quant = 50;total = cost * quant;
print("Cost of each book is $",cost,"so for",quant,"copies, the total cost is $",total)
print(f"Cost of each book is ${cost:.3f} so for {quant} copies, the total cost is ${total:.1f}")
#format string

pl = "Virat"
count = "India"
position="captain"
print(f"{pl:<15} is {position:.^15} of {count:>15} and plays cricket")
pl = "Bywangengeger"
count = "Zimbabwe"
position="Wicket-keeper"
print(f"{pl:<15} is {position:.^15} of {count:>15} and plays cricket")

#WAP to input l and b of a rectangle and calculate area and perimeter
#WAP to input s of a square and calculate area and perimeter
#WAP to input r of a circle and calculate area and circumference
#\ is called excape sequence
#\n within the quotation will break into different line
#\t - tab space - give tab space
print("Cost of each book is $ 25.897896876 \nso for 50 copies, the total cost is $ 1294.8948438")

print("\\n is for newline")
#Arithemtic operations - mathematical operations: + - * / //  **  %
num1 = 10 #Assignment operator
num2 = 20
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
print(num1 / num2)
print(num1 // num2) #integer division
print(num1 ** num2) # exponent-power
print(num1 % num2) # modulus - remainder

#Comparison operators - can take any value but output is always bool
# == != < > <= >=
num1 = 10
num2 = 20
print(num1 == num2) #F
print(num1 != num2) #T
print(num1 > num2) #F
print(num1 < num2) #T
print(num1 >= num2) #F
print(num1 <= num2) #T

#logical operators: input is boolean and output is also bool
## and or not
##and will give False even if one value is False rest everything True
##or will give True even if one value is True rest everything False
print(True and False)
print(True or False)

print(num1 == num2 or num1 != num2 and num1 > num2 or num1 < num2 and num1 >= num2 or num1 <= num2)
#T
# 2 +8 +21+10 = 41

avg=4
if avg>=50:
print("Result: PASS")
print("i m still in if")
else:
print("Result: FAIL")

num1 = -99
if num1 >0:
print("Its a positive number")
elif num1<0:
print("Its a negative number")
else:
print("Its a zero")

print("Thank you")

avg = 65
'''
avg>=90: Grade A
avg>=80: Grade B
avg>=70: Grade C
avg>=60: Grade D
avg>=50: Grade E
avg<50: Grade F

'''
a,b,c = 10,12,8
if a>=b:
#either a is greater or equal
if a>=c:
print(f"{a} is greatest value")
else:
print(f"{c} is greatest value")
else:
#b is greater
if b>=c:
print(f"{b} is greatest value")
else:
print(f"{c} is greatest value")
#Assignmnt : Modify the above program to display 3 number is descending order

#loops - repeating
#FOR - how many times
#range(a,b,c) - generates value from a upto b and increasing by c
#range(5,19,4) - 5, 9,13,17
#range(4,19,5) - 6,11,17
#WHILE - repeating based on condition
#IF ELIF ELSE
avg = 78

'''
>90 - Grade A, 80-90: B, 70-80: C, 60-70: D 50-60: E 40-50: F
<40: Failed
'''
if avg>=90:
print("Grade A")
elif avg>=80:
print("Grade B")
elif avg>=70:
print("Grade C")
elif avg>=60:
print("Grade D")
elif avg>=50:
print("Grade E")
elif avg>=40:
print("Grade F")
else:
print("Grade: Fail")

#if you get more than 40: print - Pass
avg=55
if avg>=40:
print("Pass")
if avg >= 90:
print("Grade A")
if avg>=95:
print("You win President's medal!")
elif avg >= 80:
print("Grade B")
elif avg >= 70:
print("Grade C")
elif avg >= 60:
print("Grade D")
elif avg >= 50:
print("Grade E")
else:
print("Grade F")
else:
print("Grade: Fail")


# LOOPS - repeating same statements more than once
print("Hello")
# print(), type(), input(), int()- str(), bool(),float()

sum = 5+3
print(type(sum))
sum = str(sum)
print(type(sum))

#range(a,b,c) = a:start number (including) b:ending (excluding) c:increment
range(3,9,2) # 3,5,7
range(3,7) # c is default =1: 3,4,5,6
range(4) #a=0, c=1 (default): 0,1,2,3

#For: exactly how many times
for i in range(3,9,2):
print(i, 'hello')
for i in range(3, 6):
print(i, 'hello')
for i in range(3):
print(i, 'hello')
for i in range(1,6,2):
print(i)

for i in range(5):
print("*",end=" ")
print()
'''
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
for j in range(5):
for i in range(5):
print("*",end=" ")
print()

'''
*
* *
* * *
* * * *
* * * * *
'''
for j in range(5):
for i in range(j+1):
print("*",end=" ")
print()

#While: dont know how many times but you the condition
for counter2 in range(5):
for counter in range(5):
print("*",end=" ")
print()

'''
*
* *
* * *
* * * *
* * * * *
'''
for counter2 in range(5):
for counter in range(counter2+1):
print("*",end=" ")
print()

'''
* * * * *
* * * *
* * *
* *
*
'''
for counter2 in range(5):
for counter in range(5-counter2):
print("*",end=" ")
print()
'''
*
* *
* * *
* * * *
* * * * *
'''
for counter2 in range(5):
for counter in range(5-counter2):
print(" ",end="")
for counter3 in range(counter2+1):
print("*",end=" ")
print()

for j in range(1,11):
for i in range(1,11):
print(f"{i:<2} * {j:<2} ={j*i:>3}", end=" ")
print()
for j in range(1,11):
for i in range(1,11):
print(f"{i:>2} * {j:>2} = {j*i:>3}", end=" ")
print()

#While loop:
#print values from 1 to 10
i=1
while i<=10:
print(i)
i+=1 #i=i+1

i=1
ch="y"
while ch=="y":
print(i)
i+=1 #i=i+1
ch=input("Hit y to continue or anyother key to stop: ")

total = 0
for i in range(3):
marks = int(input("Enter marks: "))
total+=marks

print("Total marks = ",total,"and average is: ",total/3)

#

ch="y"
total=0
counter = 0
while ch=="y":
marks =int(input("Enter the marks: "))
counter+=1
total+=marks
ch=input("Enter y to continue")

print("Total marks = ",total,"and average is: ",total/counter)

#

total=0
counter = 0
while True: #infinite
marks =int(input("Enter the marks: "))
counter+=1
total+=marks
ch=input("Enter y to continue")
if ch!='y':
break

print("Total marks = ",total,"and average is: ",total/counter)

#

total=0
counter = 0
while True: #infinite
marks =int(input("Enter the marks: "))
if marks<0:
continue
counter+=1
total+=marks
ch=bool(input("Enter anykey to stop"))
if ch:
break

print("Total marks = ",total,"and average is: ",total/counter)

#Strings

str1 = "Hello"
str2 = 'hi there'
print(str1)
print(str2)
str3 = '''good evening
how are you?
hows going?
are you alright?'''
str4 = """take care"""

print(str3)
print(str4)

str2 = 'hi there'
print(str1 + str2)
print(str1*4)
#read a portion of the text
print(str2[3])
print(str2[0:4])
print(str2[:4])
print(str2[-1])
print(str2[-3])
print("Total: ", len(str2))
print(str2[-3:])

for i in str1:
print(i)

str1 = "I am DOing well"
print(str1.lower())
print(str1.upper())
print(str1.title())

#strings are immutable - you cant edit them, you can overwrite
#str1[1] = "K"

str1 = "hello"
print(str1.islower())
print(str1.isdigit())

num1 = input("Enter a number: ")
if num1.isdigit():
num1 = int(num1)
print(num1)
else:
print("Invalid number")
txt1 = "hello123"
print(txt1.isalnum())

#split, search, join
str1 = 'HELLO How ARE YOU'
str2 = "hello"
#Strings are immutable - they cant be edited
print(str1.lower())
print(str1.upper())
print(str1.title())
print(str2.isalnum())
num1 = input("Enter your age: ")
if num1.isdigit():
num1 = int(num1)
else:
print("Invalid number, try again!")

val2=" a "
print(val2.isspace())
print(val2.isalpha())

# islower(), isupper(), istitle()
print(val2[1])
#val2[1]="A" - not possible as strings are immutable
str3 = "how are you oops I mean you yOu"
print("check: ", 'w a' in str3)
print(str3.count('you'))
print(str3.index('you'))

#
res=str3.split("o")
print("split: ",res)
txt = "o".join(res)
print(txt)
# List - store multiple values -
# they need not be of same datatype

l1 = [5,10,15,"Hello", False, [4,5,6]] #list
print(type(l1))
print(l1[1]) #second member
print(l1[3][1])

print([1,2,3] + [4,5,6])
print([3,6,9] * 3)
print("Length of List = ",len(l1))
for i in l1:
print(i)

l2 = [12,34,23,54,89,76,49,29]
sum=0
for i in l2:
sum+=i
print("Sum of the values in the list = ",sum)
l2 = [12,34,23,54,55,76,55,29]
l2[1]=55
print(l2)

print(l2.count(55))

ind=0
print("Indices: ",end=" ")
for i in range(l2.count(55)):
index = l2.index(55,ind)
print(index,end=" , ")
ind = index+1
print()
l3 = l2 # copy by = DEEP COPY
l4 = l2.copy() #copy by copy method - SHALLOW COPY
print("1. Copying")
print("L2: ",l2)
print("L3: ",l3)
print("L4: ",l4)
l2.append(99) #append adds element at the end
l2.insert(0,9) #insert adds element at the given position (pos,element)

print("2. Copying")
print("L2: ",l2)
print("L3: ",l3)
print("L4: ",l4)

l2.pop(2)
l2.remove(54)
print("After remove: ",l2)
l2.reverse()
print(l2)
l2.sort()
print("Sorted: ",l2)
l2.sort(reverse=True)
print("Sorted: ",l2)

l2.clear()
print(l2)

## TUPLES - immutable version of list
t1 = (2,)
print(type(t1))
l1 = ['hello',25,45,False,[2,4,6], 45]
l9 = [False,[2,4,6], 45,'hello',25,45]
# TUPLE - linear ordered immutable collection
t1 = ('hello',45,False,[2,4,6])
print(type(t1))
t2 = tuple(l1)
l2 = list(t1)

print(t2)
print(type(t2))

print(t2.count(45))
print(t2.index(45))

t3 = ()
print("first t3: ",type(t3))

t3 = (3,)
print("second t3: ",type(t3))

t3 = (3,5)
print("third t3: ",type(t3))
print(t2[2])
#Dictionary - key:value mutable collection

d1 = {}
print("Type of d1 is ",type(d1))
d1={"First":10, 5:"Hello", "Completed":False}
print(d1[5])

t={"City":"Hyderabad"}
d1.update(t)
print(d1)
t1={5:"Learn Python"}
d1.update(t1)
print(d1)

####
emp_id = [1001,1002,1009,1015]
incentive = [30,32,35,39]

emp_incentive = {1001:30, 1002:32,1009:35,1015:39}

#How much incentive should be given to emp with id 1009
print(emp_incentive[1009])
print(incentive[emp_id.index(1009)])

pos = emp_id.index(1009)
print(incentive[pos])

#keys, values, items
print(d1.values())
print(d1.keys())
print(d1.items())
print("Printing values")
for i in d1.values():
print(i)
print("Printing keys")
for i in d1.keys():
print(i)
print("Printing items")
for i,j in d1.items():
print("Key:",i," and value: ",j)
# SET - sets - linear unordered mutable collection - doesnt allow duplicate
set1 = {'Apple','Grapes','Banana','Orange'}
print(type(set1))
set1.add('Cherry')
set2 = {"Pineapple","Mango","Apple","Orange"}
# two ways to remove
set1.remove("Banana")
set1.discard("Apple")
#set1.remove("Rose") - if value isnt there throws error
set1.discard("Rose") #doesnt throw error
print("1. Set1: ",set1)
set1.pop()
set1.update(set2) #union
print("2. Set1: ",set1)
set1.clear()
print("3. Set1: ",set1)
### SET FUNCTIONS ####
set1 = {'Apple','Grapes','Banana','Orange'}
set2 = {"Pineapple","Mango","Apple","Orange"}
#UNION
print("UNION")
print(set1 | set2)
print(set1.union(set2))
print("INTERSECTION")
print(set1 & set2)
print(set1.intersection(set2))
print("DIFFERENCE")
print(set1 - set2)
print(set1.difference(set2))
print(set2 - set1)
print(set2.difference(set1))

print("SYMMETRIC DIFFERENCE")
print(set1 ^ set2)
print(set2 ^ set1)
print(set1.symmetric_difference(set2))
#update() will update the values of main set
# set1.union(set2) - this gives a new set as output
# set1.update(set2) - set1 is updated with the values
# union - update()
set1.update(set2)
print(set1)
# intersection: intersection_update()
set1.intersection_update(set2)
print(set1)
# difference_update()
set1.difference_update(set2)
print(set1)
#symmetric_difference_update()
set1.symmetric_difference_update(set2)
print(set1)

# set, list, tuple => they are inter-convertible
list1 = [3,6,9,12,3,6,9,3,6,3]
list1 = list(set(list1))
print(list1)
set1 = {'Apple','Grapes','Banana','Orange'}
set1 = list(set1)
set1.index("Grapes")
set1 = set(set1)
set1 = tuple(set1)
set1 = set(set1)
print(set1.issubset(set2))

#
list1 = [3,6,9,12,3,6,9,3,6,3]
list2 = [3,6,9,12,15]
#does all the elements of list2 present in list1?
t_list1 =set(list1)
if set(list1).issuperset(set(list2)):
print("yes, list2 value exists in list1")
else:
print("No, list2 has additional elements")
# Basic data types (stores only 1 value) - int, float, str,bool and complex
# Collections (stores multiple values - 1D) - list, tuple,dictionary, set
# functions - own functions - user defined functions
# print(), input(), type(), int(), str(), len() : in-built functions (developers of python have already written for us)
# we will learn to write our own functions

#first part of writting function is to Define the meaning- function
def mytext(val1, val2,val3):#required positional argument
print("Hello How are you today?")
print("Where are you going?")
print("I am fine.",val1)

def mytext2(val1=0, val2=0,val3=9):#default positional argument
print("Hello How are you today?")
print("Where are you going?")
print("I am fine.",val1)
print("Values are: ",val1,val2,val3)
#demo keyword (non-positional) arguments
def mytext3(val1, val2,val3):#default positional argument
print("Hello How are you today?")
print("Where are you going?")
print("I am fine.",val1)
print("Values are: ",val1,val2,val3)


#default argument (non-required) & keyword argument (non-positional)
mytext(5,10,0)
print("Done with one time calling now calling second time")
mytext2(20,4,10)
mytext2(20,4)
mytext2(10,5,1)
mytext3(val3=10,val1=9,val2=8)
mytext3(100, val3=9,val2=8)
#print()
# numpy, pandas (Multi-D)

def isPositive(val1):
#result = "Positive" # "+ve" / 1
if val1 >0:
return 1
else:
return 0 #print("Its not Positive")

res = isPositive(100)
if res==1:
print("Its positive, now lets go ahead building our logic")
else:
print("STOP! STOP! STOP!")

isPositive(-100)
isPositive(90)
#Functions with input arguments, return values
#Input arguments - required positional arguments, default, keywords arguments
def fun1(a,b):
pass

a=fun1(b=3,a=2)

#variable length arguments
def myfun2(*a, **c):
print("A has: ",a)
print("C has: ",c)

myfun2(5,6,100,8,11,"Hello",name="Sachin",city="Mumbai",Sports="Cricket")

#lambda, annoynomous or one-line - functions

a=lambda n1,n2,n3:n1*n2+n3
print(a(2,3,4))

#map, filter, reduce - special properties for LIST
list_ft = [20000,29000,30000,32000,30000,25000,33000,18000,11000,19000]
list_mt=[]
for i in list_ft:
list_mt.append(i/3.1)
print(f"Data in metres = {list_mt}")

list_mt_2 = list(map(lambda i:i/3.1,list_ft))
print(f"Data in metres = {list_mt_2}")

#Filter
list_filter = list(filter(lambda i:i%10000==0,list_ft))
print("Filtered values: ",list_filter)

#Filter 2
list_filter = list(filter(lambda i:i<20000,list_ft))
print("Filtered values: ",list_filter)

# reduce
import functools
list1 = [5,10,15,20,25,30,35] #140
val = functools.reduce(lambda a,b:a+b,list1)
print(“Result = “,val)

#functions – they are independent: print(), len(), input(), int()
#methods – they are part of a class: list (append,sort..), dictionary(copy…),string()
#in class, you have to first create an object
list1 = [] # create an object
#list1.append()

#function, you dont have to create any object – object of what??

# function
def onename():
print(“I am fine”)
print(“I am here”)
print(“I will stay here”)
def somename():
print(“Whats your name?”)
print(“What are you doing here?”)
print(“How are you?”)
return 100,200,300
x,y=2,3
def adding(x,y): # required positional arguments
print(“X = “,x,“y=”,y)
return x+y
def subtracting(a,b):
return a-b
result = adding(5,7)

result = subtracting(result,5)
#print(“Result is”,result)

b = somename()
print(“b = “,b)
a = print(“Hello”)
print(“a = “,a)
somename()

print()

def mycalc1(x,y,z): #required positional arguments
add = x+y+z
sub = z-x+y
print(“X, Y, Z are “,x,y,z)
return add,sub

r1,r2 = mycalc1(5,10,20)
print(“Result are”,r1,r2)

def mycalc2(x,y,z=15): # (x & y) are required, z is default (non-required): all of them are positional arguments
add = x+y+z
sub = z-x+y
print(“X, Y, Z are “,x,y,z)
return add,sub

r1,r2 = mycalc2(5,10,20)
print(“Result are”,r1,r2)

r1,r2 = mycalc2(5,10)
print(“Result are”,r1,r2)
#Function declaration for Required positional arguments
def myfun1(a,b,c):
print(f”A = {a}, B={b}, C={c} )
return a+b+c

def myfun2(a,b,c=25): #c is default, a and b are required, all are positional
print(f”A = {a}, B={b}, C={c} )
return a+b+c

myfun1(50,100,15) #calling required positional
myfun2(10,20) # c is default
#for non positional (keyword arguments) – depends upon the way we call
myfun1(c=50,a=100,b=15)

myfun2(b=23,a=54)

# function that will return true if a number is prime or else False
def isPrime(num):
prime = True
for i in range(2,num):
if num %i==0:
prime = False
break
return prime
result = isPrime(15)
if result:
print(“Number is Prime”)
else:
print(“Number is not a Prime”)

# generate range of prime numbers
start, end = 5000,6000
for j in range(start,end+1):
result = isPrime(j)
if result:
print(j,end=“, “)
print()

#variable length arguments
def mySum1(*var,**var2): # * to accept variable number of arguments
”’
This is a demo function to show the working of variable number of arguments
:param var: will read as tuple
:param var2: will read as dictionary
:return: sum of elements in the tuple
”’
print(var2) #read as dictionary
# *var would be a tuple
sum=0
for i in var: #(5,2,1,3,8,6,4)
sum+=i # sum = sum+i
return sum

output = mySum1()
print(“Output = “, output)
output = mySum1(2,3)
print(“Output = “, output)
output = mySum1(5,10,0,10,15,20,25,30,35,40,10,20,name=“Sachin”,game=“Cricket”,fame=“Batsman”)
print(“Output = “, output)

print(mySum1.__doc__) #doc string (documentation)
print(print.__doc__)
print(input.__doc__)

#
def try_recur(n):
print(“Hello”)
if n>2:
try_recur(n-1)

try_recur(50)

##function to find factorial of a number
def myFactorial(num):
prod = 1
for i in range(1,num+1):
prod *=i # prod = prod * i
return prod

fact = myFactorial(5)
print(“Factorial = “,fact)

def myRFacto(num):
if num==1:
return 1
else:
return num*myRFacto(num-1)

fact = myRFacto(5)
print(“Factorial = “,fact)

Filename: P5.py

#recursive functions
def facto(n):
if n==1:
return 1
return n * facto(n-1) # 10 * 9!

#decorators
def myfunc1():
print(“This is my func1”)

def myfunc2():
print(“This is my func2”)

def myfunc3(abc):
print(“This is my func3 line 1”)
abc()
print(“This is my func3 line 2”)

if __name__ ==“__main__”:
val = facto(5)
print(“Factorial is “,val)
myfunc3(myfunc1)

Filename: P6.py

# import option 1
import MyPack1.modul1
import p5

val = p5.facto(5)
print(val)
# import option 2: with alias
import p5 as MyTopChoices
MyTopChoices.myfunc3(MyTopChoices.myfunc1)

# import option 3
from p5 import myfunc3,myfunc2,myfunc1
myfunc2()

# importing package
import MyPack1.modul1 as p1m1
p1m1.myfunc3(10)

from MyPack1 import *
MyPack1.modul1.myfunc2(2,5,8)

## using random module
import random
print(“Random val = “,random.random())
print(“Random integer = “,random.randint(1,100))
#Object Oriented Programming
#class & objects
#apple – class, hold it, eat it -object

# create a class – define some properties
# to use a class – you have to create an object
# object will have properties of the class and few more

class Book:
num_of_books = 0 #class variable
publisher = “Eka Publishers”
def __init__(self,book_title, pages=100,book_author=“”): #object function
self.pages = pages #object variables
self.title = book_title
self.author = book_author
Book.num_of_books +=1

def display_details(self):
print(“Title: “,self.title)
print(“Author: “,self.author)
print(“Pages: “,self.pages)
print(“Total books = “,Book.num_of_books)

@classmethod
def total_count(cls):
print(“Total books = “,cls.num_of_books)

b1 = Book(“Python Programming”, 350,“Swapnil Saurav”) #object is created – __init__() is called automatically
b2 = Book(“Machine Learning”, 550,“Swapnil Saurav”)
b3 = Book(“Data Visualization”, 250,“Swapnil Saurav”)
#b1.create_book(“Python Programming”, 350,”Swapnil Saurav”) #object function is called
b2.display_details()
print(type(b1))
class MyMathOps:
def __init__(self,n1,n2):
self.n1 = n1
self.n2 = n2
self.add = –1
self.subtract = –1
self.multiply = –1
self.divide = –1

def myadd(self):
self.add= self.n1 + self.n2
return self.add
def mysubtract(self):
self.subtract = self.n1 – self.n2
def mymultiply(self):
self.multiply = self.n1 * self.n2
def mydivide(self):
self.divide = self.n1 / self.n2

class SpecialOps:
def __init__(self,num):
self.number = num
print(“Num = “,num)


def isPrime(self):
prime = True
for i in range(2,self.number//2 + 1):
if self.number % i ==0:
prime = False
break
return prime

if __name__ ==“__main__”:
op1 = MyMathOps(5,15)
#

op2 = MyMathOps(5,10)
print(op1.myadd()) #1. class Abstraction
print(op1.mymultiply())
op2.mydivide()
print(op1.divide)

l1 = [4,5,6,7]
l1.append(5)
sp1 = SpecialOps(11)
print(“Prime: “,sp1.isPrime())
import p3
from p3 import MyMathOps as mp

c1 =mp(10,20)
c1.myadd()
print(“Add = “,c1.add)

class ShoppingCart:
def __init__(self):
self.myshoppingcart = []

#add product to the cart
def add_prod(self,item):
self.myshoppingcart.append(item)

sc1 = ShoppingCart()
while True:
print(“1. View my cart \n2. Add to my cart\n3. Remove from my cart\n4. Exit”)
ch=input(“Enter your option: “)
if ch==“1”:
if len(sc1.myshoppingcart)==0:
print(“Your shopping cart is empty!”)
else:
print(“Products in your cart are: “,sc1.myshoppingcart)
elif ch==“2”:
item = input(“Enter the product you want to add: “)
sc1.add_prod(item)
elif ch==“3”:
pass
elif ch==“4”:
break
else:
print(“Invalid option”)
class ShoppingCart:
def __init__(self):
self.myshoppingcart = []

#add product to the cart
def add_prod(self):
each_item = {}
item_name = input(“Enter the product Name: “)
item_size = input(“Enter the product Size: “)
item_color = input(“Enter the product Color: “)
each_item ={“Item”:item_name,“Size”:item_size,“Color”:item_color}
self.myshoppingcart.append(each_item)
#print(self.myshoppingcart)
def display_prod(self):
print(“Item Size Color”)
for i in self.myshoppingcart:
for k,j in i.items():
if k==“Item”:
print(f”{j:<10}, end=” “)
else:
print(j,end=” “)
print()


sc1 = ShoppingCart()
while True:
print(“1. View my cart \n2. Add to my cart\n3. Remove from my cart\n4. Exit”)
ch=input(“Enter your option: “)
if ch==“1”:
if len(sc1.myshoppingcart)==0:
print(“Your shopping cart is empty!”)
else:
sc1.display_prod()
elif ch==“2”:
sc1.add_prod()
elif ch==“3”:
pass
elif ch==“4”:
break
else:
print(“Invalid option”)
MASTERLIST = [{“ItemCode”: 101,“Item”:“Shirt”,“Price”:28.2},
{“ItemCode”: 102,“Item”:“Bag”,“Price”:18.2},
{“ItemCode”: 103,“Item”:“Book1”,“Price”:38.2},
{“ItemCode”: 104,“Item”:“Watch”,“Price”:58.2},
{“ItemCode”: 105,“Item”:“Shoes”,“Price”:128.2},
{“ItemCode”: 106,“Item”:“Laptop”,“Price”:1028.2}]
class ShoppingCart:
def __init__(self):
self.myshoppingcart = []

#add product to the cart
def add_prod(self):
each_item = {}
item_name = input(“Enter the product Name: “)
not_in_list = True
for items in MASTERLIST:
if item_name==items[“Item”]:
not_in_list = False
if not_in_list:
print(“Sorry, That Item is Out of Stock!”)
else:
item_size = input(“Enter the product Size: “)
item_color = input(“Enter the product Color: “)
item_quantity = int(input(“Enter the product Quantity: “))
each_item ={“Item”:item_name,“Size”:item_size,“Color”:item_color,“Quantity”:item_quantity}
self.myshoppingcart.append(each_item)
#print(self.myshoppingcart)
def display_prod(self):
print(“Item Size Color Quantity”)
for i in self.myshoppingcart:
for k,j in i.items():
print(f”{j:<10}, end=” “)
print()

def remove_prod(self):
item_name = input(“Enter the product name to remove: “)
not_in_list = True
for items in self.myshoppingcart:
if item_name == items[“Item”]:
self.myshoppingcart.remove(items)
not_in_list = False

if not_in_list:
print(“Sorry, That Item is not in your shopping cart!”)
else:
print(“Item is now removed from your shopping cart!”)

def generate_receipt(self):
print(“Item Size Color Quantity Price”)
print(“=======================================================”)
item_cost = 0
price = 0
grand_total = 0
for i in self.myshoppingcart:
for k,j in i.items():
for master_list in MASTERLIST:
if j==master_list[“Item”]:
price=master_list[“Price”]

print(f”{j:<10}, end=” “)
if k==“Quantity”:
item_cost = j*price
grand_total+=item_cost
print(f”{round(item_cost):<10}, end=” “)
print()
print(“——————————————————-“)

print(” TOTAL: $”+str(round(grand_total)))
print(“=======================================================”)

if __name__==“__main__”:
sc1 = ShoppingCart()
sc2 = ShoppingCart()
while True:
print(“1. View my cart \n2. Add to my cart\n3. Remove from my cart\n4. Generate My Receipt\n5. Exit”)
ch=input(“Enter your option: “)
if ch==“1”:
if len(sc1.myshoppingcart)==0:
print(“Your shopping cart is empty!”)
else:
sc1.display_prod()
elif ch==“2”:
sc1.add_prod()
elif ch==“3”:
sc1.remove_prod()
elif ch==“4”:
if len(sc1.myshoppingcart)==0:
print(“Your shopping cart is empty!”)
else:
sc1.generate_receipt()
elif ch==“5”:
break
else:
print(“Invalid option”)
”’
WAP to implement Stack properties:
add, delete: LIFO
”’
class MyStack:
def __init__(self):
self.mystack=[]
def add(self,val):
self.mystack.append(val)
def delete(self):
self.mystack.pop()
def display(self):
print(“Values in the stack are:\n,self.mystack)

# create the object
stack1 = MyStack()
stack1.add(40)
stack1.add(10)
stack1.add(20)
stack1.add(60)
stack1.add(50)
stack1.add(80)
stack1.display()
stack1.delete()
stack1.display()
stack1.delete()
stack1.delete()
stack1.display()