Thursday, July 2, 2020

Functions


In Python, functions come from at least three ways.

1.      From preinstalled modules in Python.
2.      From built-in functions in Python.
3.      From directly in code.

Given below the format of a function.

def functionName():
     functionBody


·         It always starts with the keyword “def” (for define)
·         Next after “def” goes the name of the function (the rules for naming functions are exactly the same as for naming variables)
·         After the function name, there's a place for a pair of parentheses (they contain nothing here, but that will change soon)
·         The line has to be ended with a colon ( ; )
·         The line directly after “def” begins the function body - a couple (at least one) of necessarily nested instructions, which will be executed every time the function is invoked; note: the function ends where the nesting ends, so we have to be careful.


Consider the below example.









Output is




When the moment of the invocation of the function, there are two important factors to consider.

Firstly,

You mustn’t invoke a function which is not known at the moment of invocation.

Python reads your code from top to bottom. It’s not going to look ahead in order to find a function we forgot to put in the right place (right means “before invocation”).

Consider the below example.










Here we get the error message like this.



Secondly,

You mustn’t have a function and a variable of the same name.

Consider the below example. This is the erroneous snippet.







Assigning a value to the name message causes Python to forget its previous role. The function named “message” becomes unavailable.

We’re free to mix the code with functions. But we’re not obliged to put all the functions at the top of the source file.

Look at the snippet below.











This is also completely correct and works as intended.

No comments:

Post a Comment