Python - Functions

 Functions

Function in python it's same as the functions in any other programming language. Concept is same the syntax is differ.
As we all know function is a block of code that perform some task.

There are 3 types of function in python.
  1. In-built function - for e.g:- min(),  print(), add().
  2. User defined function - That will be defined or created by the user.
  3. Anonymous function - is also known as lambda function because they are not declared with the def keyword.

How to define a function in python

  1. use def statement.
  2. followed by function name.
  3. Add parameter to the function.
  4. All the parameter should enclosed with the parenthesis or bracket and at the end of the function used 'colon' :

When to use a function.

  1. Function should use when there is duplication of a task.
  2. It increase readability of the program.

Return Statement 

A return statement is used to return something from the function. It's only work for the function. If any other want to work with it. It's said I can't work with you.
The statement after the return statement is not executed.
Without the return statement your function will return an object None.

Types of arguments in python

  1. Position
  1. Keyword : - When you pass the variable name itself. 


  1. Default
Imagine you just want to pass the first argument. And you don't want to pass the value of second argument.


  1. Variable length Arguments
Sometime we want to subtract more than two numbers. So, the question is how can we pass multiple values if we have defined or created a function for two parameters only. For this we used Variable length arguments.

The *arg variable will return output in a tuple format.




Keyword variable length arguments.

If you want to pass multiple data that to be help of the keyword than we have to use keyword variable length argument.

Example

Creating a function which will take two parameter and do subtraction.


Now, when calling the function min(), it's giving us output as 1. But what happened if you try to store the value of min in a variable.

When we print value of a, get the output as None. Because we are not using return statement inside the function.




Comments