Function in Python : Details Defining and Calling the function



Function in Python:
Most of us know the function.. whether its JAVA or any other language , functions are used to return some data as a result. When its called then the specific function is executed; Data , known parameters are passed into the function. and in return some data is returned by these function.

Today, I am going thru functions in Python and found it is so interesting to use them.

How to create a Function:
    This is now I created using the def keyword - function is defined:

def new_function ():
print ("hello from new_function")

Define Function in Python:



How to call the function in Python: 
To call the function; we need to use function name followed by parenthesis: 
Here is:

Calling the Function in Python:
The Result of this call is returned as :




The function print new_function () calls our def new_function () and print the command " hello from new_function."

Indenting (Space) before the function:

While writing at first time I made mistake by keeping space before the function, then I came to know that I left the indent which showed me following error:






Python follows a particular style of indentation to define the code, since Python functions don't have any explicit begin or end like curly braces to indicate the start and stop for the function, they have to rely on this indentation.

Now, when I added the indent (space) in front of "print" function, it printed as expected:

Indenting for function
At least, one indent is enough to make your code work successfully. But as a best practice it is advisable to leave about 3-4 indent to call your function.

It is also necessary that while declaring indentation, you have to maintain the same indent for the rest of your code.
Now, when I apply same indentation for both the statements and align them in the same line, it gives the expected output.

Same Indent for both statements

So Key Notes from my experience are :

  • def is used to define the function
  • The code block within every function starts with a colon (:) and has to be indented (space)
  • Any arguments or input parameters has to be placed within these parentheses, etc.
  • At least one indent should be left before the code after declaring function
  • Same indent style should be maintained throughout the code within def function
  • Three or four indents are considered best before the statement






    



Comments

Post a Comment