By Hemanta Sundaray on 2021-08-18
We define a function with the keyword def, followed by the name of the function.
If the function accepts any parameters, the name of the function must be followed by a parameter or a list of parameters enclosed in parentheses.
The parenthesized list of parameters is followed by a colon (:).
The statements that make up the body of the function start in the next line.
Examples:
def greeting ():
print(f"Hello world!")
greeting()
# Hello world!
def greeting (name):
print(f"Hello {name}")
greeting("World!")
# Hello World!
We can assign default values to function parameters by following the name of the parameter with an equal sign (=) followed by a value.
In the code example below, we have assigned the default value of Stranger to the name parameter. So, when we call the greeting function without passing in any argument (which we have done on line 4), the default value Stranger is used.
def greeting (name = "Stranger"):
print(f"Hello {name}")
greeting()
# Hello Stranger
Below, we have a function named add that receives two numbers as arguments and returns their sum.
def add (numOne, numTwo):
return numOne + numTwo
print(add(10, 20))
# 30
What if we want the add function to have the capability to add an arbitrary number of arguments that we pass to it?
We can do so by prepending the name of the parameter with an asterisk (*) as shown below. By convention, the parameter name is args.
Note that the arguments will be wrapped up in a tuple.
def add (*args):
return sum(args)
print(add(10, 20, 30, 25, 50))
# 135
On line 2, we use the built-in sum function in Python to add all our arguments.
Consider the following scenario:
numbers = [10, 20, 30, 40, 20]
def add (*args):
return sum(args)
The numbers that we want to pass as arguments to the add function are in a list named numbers.
In order to pass these numbers to the add function call, we must unpack them from the list. We can do so by writing the function call with the * operator as shown below:
numbers = [10, 20, 30, 40, 20]
def add (*args):
return sum(args)
print(add(*numbers))
# 120