Functions
A function in programming is a self-contained chunk of code that
encapsulates a single job or combination of duties. They are only activated
when expressly requested by the software. The primary benefit of functions is
the ability to reuse and manage code.
Built in Functions in Python
In earlier sessions of this course, you were exposed to several of
Python's built-in functions. For example, print() takes five parameters, only
the first of which is often used, and shows the provided string or object on
the screen unless it is specified to be written to a file. The input() function
allows you to introduce values into the application. The code that executes the
work is abstracted away from you in these built-in functions, and you only need
to know the function arguments and the values it returns every time you use it.
User Defined Functions
You can define your own functions to manage and reuse the lines of
code you may need within the program.
Function Calls and Definition
The usual syntax for defining a Python function is as,
def <function_name>([<parameters>]):
<statement(s)>
def is the keyword that we use to inform Python of the new
function we're creating. The function name is the identifier, and this should
also follow the naming conventions that we learned in the variables tutorial.
The component named "parameter/s" is optional. It is there that we
provide the parameters to be passed to the function, if any are needed. The
indented <statement/s> compose the function body defining the
functionality. We include the statements we need executed when the function is
called , there.
The syntax for calling a Python function is as,
<function_name>([<arguments>]):
Calling this function as my_function() would execute the function
body statements and print a line on the screen as "Hello from a
function!"
>>> def my_function():
print("Hello from a function")
>>> my_function()
Hello from a function
Even if you define a function that does not need to take any
arguments, the parentheses are a must.
#Function definition
def my_function():
print("Hello from a
function")
#Function invocation
my_function()
Empty Functions
Sometimes you may need to define a function with an empty body,
one that does nothing. This is usually to act as a placeholder until the
function is implemented at a later level. Anyhow, when you define empty
functions you must use the pass statement.
def empty_func():
pass
empty_func()
Passing Arguments
Most of the functions you will be defining need data to be passed
into them in the form of parameters. In Python, there are varied ways of
invoking functions.
Positional
Arguments
Positional arguments are the most popular and easy technique of
sending arguments to functions. Within parentheses, you give the list of
arguments that the function takes during the function declaration.
#Function definition
def calc(qty, item, price):
print("The"+
item + " cost/s" , (qty*price), "rupees")
#Function Call
calc(2,'Apples', 20)
The Apples cost/s 40 rupees
This function calc() is called here with the inputs 2, Apples, and
20 to correspond to the provided parameters quantity, item, and price. Keep in
mind that with positional arguments, the arguments passed in the function call
and the parameters declared in the function must be in the same order and
number.
Although positional arguments are the most straightforward way to
pass data to a function, You are not allowed to leave any out or specify extra
ones when calling the function, as shown in the following:
def calc(qty, item, price):
print("The "+ item + " cost/s"
. (qty*price), "rupees")
calc(2,'Apples', 20,50)
TypeError: calc() takes 3 positional arguments but 4
were given
#Function definition
def calc(qty, item, price):
print("The"+
item + "cost/s" , (qty*price),
"rupees")
#Function Call
calc(2,'Apples', 20)
#Function call with incorrect number of arguments.
#calc(2,'Apples', 20,50)
#calc("a",'Apples',20)
Keyword Arguments
Another way to call the functions is with Keyword arguments where
you can specify the passed arguments in <keyword>=<value> format. The
"keyword" is what you have provided as the parameter, and the
"value" is the actual parameter value you want to pass to the
function.
The previous function calc() can also be called with keyword
arguments as shown below.
def calc(qty, item, price):
print("The "+ item + " cost/s",
(qty*price), "rupees")
calc(qty=5, item="Oranges",price=10)
The advantage of using Keyword arguments is that you don't have to
worry about the argument order like you did previously. Python can recognize
the values even if the order is messed up since each argument you supply is
described with the parameter or keyword name.
However, here too, the number of arguments should be equal to what
is defined in the function.
def calc(qty, item, price):
print("The "+
item + " cost/s", (qty*price), "rupees")
calc(qty=5, item="Oranges",price=10)
Default
Parameters
If no argument is supplied during the function call in functions
specified with default parameters, a predetermined default parameter is passed
as the function's value. Such arguments are supplied in the name>=value>
format in Python function definitions. This value> becomes the parameter's
default value.
def greet(name, msg="How are you?"):
print(name + ", " msg)
greet("John")
greet("John", "Good Evening")
greet("Good Evening")
John, How are you?
John, Good Evening
Good Evening, How are you?
You can see in the above examples that when any arguments are left
out, the function assumes its default value.
def greet(name, msg="How are you?"):
print(name + ",
" + msg)
greet("John")
greet("John", "Good Evening")
greet("Good Evening")
Arbitrary
Arguments
In some function definitions, you will not know the exact number
of arguments that need to be passed to the function during its call. In such
situations, you can use the *args syntax with the function definition.
def add(*args):
#sum() is an inbuilt function to sum up a list
total=(sum(args))
print("The sum : " ,total)
def greet(msg, *names):
for name in names:
print(msg + ", " + name)
#Calling add() function
add(1,4,5)
#Calling greet() function
greet("Hello","John","Maggie","Lucy")
The sum:10
Hello, John
Hello, Maggie
Hello, Lucy
>>>
The return
Statement
A return statement in a Python function can either stop the
function immediately and return control to the caller, or it can return any
needed data to the function caller.
In the first case, we just include the return statement, but if we
are returning a specific value or values from the function, we must include
that along with the return statement. These returned values can then be grabbed
by another function or a variable, as desired by the application.
Any type of object can be returned by a Python function. Python
also supports delivering multiple values separated by commas. They are really
returned as a tuple there.
def calc(quantity,
price):
return quantity*price
print("The
Price is " , calc(10,750))
The Price is 7500
>>>
Docstrings
The docstrings are intended to offer comprehensive documentation
for a function. It can include the function's purpose, a list of parameters,
return values, and any other information that the programmer deems relevant to
provide.
The first statement in the body of a Python function contains a
docstring. These must be enclosed in quotation marks, and the suggested
standard is to use triple quotation marks (in double quotes) as "docstring
standard is to use triple quotation marks (in double quotes) as
"docstring." These might be on a single line or many lines. If the
docstring can be contained on a single line, the opening and closing quotations
should also be on the same line.
We can also view the docstrings of built-in and user defined
functions using the __doc___ attribute.
def calc(quantity, price):
"""Returns the product of
quantity and price"""
return quantity*price
print (calc.__doc__)
Returns the prodcut of quantity and price
>>>
Docstrings seem to be similar to commenting. But the difference is
that comments are not accessible for viewing during the program's execution.
And the purpose that docstrings serve is different; they are in fact a more
useful way of commenting.
>>> print(print.__doc__)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object
(stream); defaults to the current sys.stdout.
sep: string inserted
between values, default a space.
end: string appended after
the last value, default a newline.
flush: whether to forcibly flush the stream.

0 Comments