3) Python Functions

Function in python is defined by def with open and close parenthesis with a colon. Python uses a colon and next line indented generally four spaces. But it can be any.

Output:

I am a function
I am a function
None

  • When a function is called print statement is executed.
  • In the second case as the function is not returning anything it will print none and its string representation.
  • In last case, the function is not executed.

Function That takes an argument

A function that returns a value

Function with the default value for an argument

Output:

36
8
8

Case 1: When no value is passed function will take a default value of 2.

Case 2: When both values passed it will take the values passed.

Case 3: Reverse the order in which parameters are called.  There is no need to remember the order of variable passed if you are passing a variable name as python remembers the name of an argument.

Function with a variable number of arguments

Here we pass any number of argument to a function the function then loops over all the argument passed and calculates its sum.