Defining Functions¶
Let us understand how to define functions in Python. Here are simple rules to define a function in Python.
- Function blocks begin with the keyword
def
followed by the function name and parentheses (). - While defining functions we need to specify parameters in these parentheses (if applicable)
- The function specification ends with
:
– (example:def add(a, b):
) - We typically have return statement with expression in function body which results in exit from the function and goes back to the caller.
- We can have document string in the function.
In [1]:
def get_commission_amount(sales_amount, commission_pct):
commission_amount = (sales_amount * commission_pct / 100) if commission_pct else 0
return commission_amount
In [2]:
get_commission_amount
Out[2]:
<function __main__.get_commission_amount(sales_amount, commission_pct)>
In [3]:
get_commission_amount(1000, 20)
Out[3]:
200.0
In [4]:
def get_commission_amount(sales_amount, commission_pct):
if commission_pct:
commission_amount = (sales_amount * commission_pct / 100)
else:
commission_pct = 0
return commission_amount
In [5]:
get_commission_amount(1000, 20)
Out[5]:
200.0
In [6]:
def get_commission_amount(sales_amount, commission_pct):
return (sales_amount * commission_pct / 100) if commission_pct else 0
In [7]:
get_commission_amount(1000, 20)
Out[7]:
200.0