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.
def get_commission_amount(sales_amount, commission_pct):
commission_amount = (sales_amount * commission_pct / 100) if commission_pct else 0
return commission_amount
get_commission_amount
<function __main__.get_commission_amount(sales_amount, commission_pct)>
get_commission_amount(1000, 20)
200.0
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
get_commission_amount(1000, 20)
200.0
def get_commission_amount(sales_amount, commission_pct):
return (sales_amount * commission_pct / 100) if commission_pct else 0
get_commission_amount(1000, 20)
200.0