Sunday, October 27, 2019

Python: Function Calls

Function in Python is defined by the "def " statement followed by the function name and parentheses ( () )

There are set of rules in Python to define a function.

Any args or input parameters should be placed within these parentheses
The function first statement can be an optional statement- docstring or the documentation string of the function
The code within every function starts with a colon (:) and should be indented (space)
The statement return (expression) exits a function, optionally passing back a value to the caller. A return statement with no args is the same as return None.

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. Here we take a simple example with "print" command. When we write "print" function right below the def func 1 (): It will show an "indentation error: expected an indented block".

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. For example, in below screen shot when we call another statement "still in func1" and when it is not declared right below the first print statement it will show an indentation error "unindent does not match any other indentation level."


Return statement is as usual.

Argument can have default value also. Like

def multiply(x,y):
   print(x*y);

multiply(2,8);

Great that we can also change the order of the variable in a function
 You can also change the order in which the arguments can be passed in Python. Here we have reversed the order of the value x and y to x=4 and y=2.


Below is how a variable argument function can be declared

def multiply(*args)
  print(args)

multiply(1,2,3,4)

References:
https://www.guru99.com/functions-in-python.html

No comments:

Post a Comment