Machine Learning Prerequisite | Python Basics: Functions in python
Prerequisit Machine Learning Prerequisite | Python Basics: Variables and Datatypes
Again can seems to be very basic please feel free to escape if you know what functions are and how they work
All the code is in Google Colab and Notebook can be found here
Comments in python
a comment is a programmer-readable explanation or annotation in the source code of a program. They are added with the purpose of making the source code easier for humans to understand, and are generally ignored by compilers and interpreters.
anything starting from # is a comment . # is for single line comment . for multiline comment we use """commentt""" triple double quotes
# this is a simple single line comment
""" This is a multi line comment
which can extend to multi lines """
Functions Need
Ok so in that last article we have seen the variables with our small tea stall . Just to recap we have 3 products in our shop they are Tea milk and coffee
tea = {"Name":"Tea","costPrice":8,"sellPrice":10}
coffee = {"Name":"Coffee","costPrice":12,"sellPrice":15}
milk = {"Name":"Milk","costPrice":15,"sellPrice":20}
products = [tea,coffee,milk]
print(products)
# output
[{'Name': 'Tea', 'Price': 10}, {'Name': 'Coffee', 'Price': 15}, {'Name': 'Milk', 'Price': 20}]
Lets say for track record we manage 2 more variables which are Profit (how much we have earned at the day end =sum of all the (sellprice - cost price) of the product sold ) and Revenue total amount collected = sum of all the (sellprice ) of the product sold
Revenue = 0
Profit = 0
print("============First Customer=================")
# first customer buys 1 tea and 2 coffee
for item in products:
if(item["Name"]== "Tea"):
tempRevenue = (1)* (item["sellPrice"] - item["costPrice"]) #1(10-8)
Profit = Profit+tempRevenue
Revenue = Revenue + (1) *(item["sellPrice"])
if(item["Name"]=="Coffee"):
tempRevenue = (2) *(item["sellPrice"] - item["costPrice"]) #1(10-8)
Profit = Profit+tempRevenue
Revenue = Revenue + (2) *(item["sellPrice"])
print(Revenue,Profit)
print("============Second Customer=================")
# second customer buys 3 tea and 2 coffee and 1 milk
for item in products:
if(item["Name"]== "Tea"):
tempRevenue = (3)* (item["sellPrice"] - item["costPrice"]) #1(10-8)
Profit = Profit+tempRevenue
Revenue = Revenue + (3) *(item["sellPrice"])
if(item["Name"]=="Coffee"):
tempRevenue = (2) *(item["sellPrice"] - item["costPrice"]) #1(10-8)
Profit = Profit+tempRevenue
Revenue = Revenue + (2) *(item["sellPrice"])
if(item["Name"]=="Milk"):
tempRevenue = (1) *(item["sellPrice"] - item["costPrice"]) #1(10-8)
Profit = Profit+tempRevenue
Revenue = Revenue + (1) *(item["sellPrice"])
print(Revenue,Profit)
print("============Third Customer=================")
# third customer buys 3 tea and 2 coffee and 1 milk
for item in products:
if(item["Name"]== "Tea"):
tempRevenue = (3)* (item["sellPrice"] - item["costPrice"]) #1(10-8)
Profit = Profit+tempRevenue
Revenue = Revenue + (3) *(item["sellPrice"])
if(item["Name"]=="Coffee"):
tempRevenue = (2) *(item["sellPrice"] - item["costPrice"]) #1(10-8)
Profit = Profit+tempRevenue
Revenue = Revenue + (2) *(item["sellPrice"])
if(item["Name"]=="Milk"):
tempRevenue = (1) *(item["sellPrice"] - item["costPrice"]) #1(10-8)
Profit = Profit+tempRevenue
Revenue = Revenue + (1) *(item["sellPrice"])
#output
============First Customer=================
40 8
============Second Customer=================
120 25
============third Customer=================
120 25
So now you see for every customer we are doing something repetative to get the revenue which is getting the product detail from the products
for item in products:
if(item["Name"]== "Tea"):
Calculating Profit and adding it to the main profit and calculating revenue and adding it to main revenue
tempRevenue = (unitSold) *(item["sellPrice"] - item["costPrice"])
Profit = Profit+tempRevenue
Revenue = Revenue + (unitSold) *(item["sellPrice"])
for three orders we can do it 3 times but lets say we have 100 orders in that case it is not worth to rewrite our code again and again so this is one of the problem which functions solve
Function
function is a group of statment or logic tied together in one unit which can except some input run some group of commands on that input and can give an out put
untill now we have used many function like
print()
id()
hex()

so lets see it in action
what we want is a function which takes the name of the product and quantity purchased and can update the revenue and profit variables for us so lets create one
to create a function thier is a syntax in python
def functionname( parameters ):
"function_docstring"
function_body
return [expression]
# function_docstring is the description of the function what it is doing
# function_body is the commands or logic of our function
# return [expression] any thing we want to return from our function
ok so for understanding we will create 2 3 function
def UpdateRevenueandProfit(name , qty , Profit,Revenue):
# the description of of our function
"Calculate the Profit and revenue based on item and quantity passed and updates it "
for item in products:
# loop through all the products to find the product which we have passed
if(item["Name"]== name):
tempRevenue = (qty) *(item["sellPrice"] - item["costPrice"])
Profit = Profit+tempRevenue
Revenue = Revenue + (qty) *(item["sellPrice"])
print("============Summary Start=================")
print("Revenue Update after order :"+ str(Revenue) )
print("Profit Update after order :"+ str(Profit) )
print("============Summary End=================")
print()
print()
lets execute it to excute a function we pu () at the end with peramaters in it
Profit = 0
Revenue = 0
# one cusomer purchases 20 Tea
UpdateRevenueandProfit('Tea',20 ,Profit,Revenue)
# one cusomer purchases 20 Milk
UpdateRevenueandProfit('Milk',20 ,Profit,Revenue)
# one cusomer purchases 30 Coffee
UpdateRevenueandProfit('Coffee',30 ,Profit,Revenue)
the output you will get is
============Summary Start=================
Revenue Update after order :200
Profit Update after order :40
============Summary End=================
============Summary Start=================
Revenue Update after order :400
Profit Update after order :100
============Summary End=================
============Summary Start=================
Revenue Update after order :0
Profit Update after order :0
============Summary End=================
Use of docstring
when we hover on the function it shows a small help box like below with doc staring which makes it easier for us on what the functtion is doing

Lets now make our functtion a bit more realworld . so lets say a customer can purchase multiple items . so our function should calculate Revenue and profit for each order correctly
now our function will take a list of products which will be a dictionary with product name and quantity as the key and it should now return a totalamount which the customer has to pay lets see it by example
# lets say one customer byus 2 Tea and 4 Coffee
productsPurchased = [{"Name":"Tea","quantity":2},{"Name":"Coffee","quantity":2}]
So lets make the change in our function
def ProcessOrder(productsPurchased, Profit,Revenue):
# the description of of our function
"""Calculate the Profit and revenue based on purchasedproducts list and updates it also return the total bill of the customer
"""
TotalAmount = 0 # the amount customer needs to pay
for product in productsPurchased:
# loop through all the products customer has purchased
for item in products:
# loop through all the products to find the product
if(item["Name"] == product["Name"]):
tempRevenue = (product["Quantity"]) *(item["sellPrice"] - item["costPrice"])
Profit = Profit+tempRevenue
TotalAmount = TotalAmount + (product["Quantity"]) *(item["sellPrice"])
Revenue = Revenue + (product["Quantity"]) *(item["sellPrice"])
print("============Summary Start=================")
print("Revenue Update after order :"+ str(Revenue) )
print("Profit Update after order :"+ str(Profit) )
print("============Summary End=================")
print()
print()
return TotalAmount;
Lets test our function
Profit = 0
Revenue = 0
# A customer purchases 20 Tea and 10 Coffee and 5 Milk then
purchasedProducts = [{"Name":"Tea","Quantity":20},{"Name":"Coffee","Quantity":10},{"Name":"Milk","Quantity":5}]
orderAmount = ProcessOrder(purchasedProducts,Profit,Revenue)
print("=========Amount Due :" + str(orderAmount))
# output
============Summary Start=================
Revenue Update after order :450
Profit Update after order :95
============Summary End=================
=========Amount Due :450
Google Colab Notebook can be found here