Python functions

Most of the time, when you find yourself copy and pasting some pieces of code, you should break it up into a self-contained chunk into functions. This practice allows for better modularity, is easier to maintain, and allows for code reuse. Python functions are defined using the def keyword with the function name, followed by the function parameters. The body of the function consists of the Python statements that are to be executed. At the end of the function, you can choose to return a value to the function caller, or by default, it will return the None object if you do not specify a return value:

def name(parameter1, parameter2):
statements
return value

We will see a lot more examples of function in the following chapters, so here is a quick example:

>>> def subtract(a, b):
... c = a - b
... return c
...
>>> result = subtract(10, 5)
>>> result
5
>>>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.241.98