Writing codes can be more exciting when you realize that there's a way in which you can well organize your codes and make them reusable. This can be made possible by functions.
Functions are building blocks in python. A function is a sequence of well-organized reusable statements (codes) that perform a specific task.
A function can be modified and called by other functions, assigned to a variable, passed as an argument, returned from a function.
A function may take input and perform logical operations/ series of tasks and may return a response when called.
Benefits of using a function.
1.) A large program can be divided into functions where each function performs a specific task.
(Modularization).
2.) Splitting programs into functions makes them easier to manage, maintain and debug.
3.) Functions improve the understandability and readability of a large program.
4.) Functions enable code reusability.
Types of a function
1.) Built-in functions
2.) User defined functions.
Defining a function
A function is defined in order to provide the required functionality using the def keyword . The definition consists of the function name, the function parameters, the function body and the return value.
The syntax is as follows:
def functionName( arguments):
block of statements to be executed
return value
The pass statement – can be used as a place holder in a function when a function is declared but the codes constituting its body isn’t stated. This creates a function that is syntactically correct but has no performs no action.
def service(studentName):
pass # Remember to implement this!
Parameters and arguments
A parameter is the variable defined within the parentheses during function definition while an argument the value passed to the function when it is called. The value may be a variable, and object or another function.
# Here x and y are the function parameters
def add(x,y):
return x+y
# Here 8 and 3 are arguments
add(8,3)
Calling a function
A function may be called by stating its name and passing arguments to the parameter space in its parenthesis.
# Function definition is here
def displayName (name):
"This prints a passed string into this function"
print (name)
return
# To call the displayName function
displayName ("Marty")
displayName ("Stephen")
The output is as follows
Marty
Stephen
Function Arguments.
You can call a function by using the following types of formal arguments-
- Required arguments Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.
def displayName (name):
"This prints a passed string into this function"
print (name)
return
# To call the displayName function
displayName ()
When the above code is executed it produces an error since it lacks a positional argument
However, when given the required positional argument, it runs smoothly.
def displayName (name):
print (name)
return
displayName('Annabelle') # Gives an error
The output is:
Annabelle
- Keyword arguments Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.
def roomArea(width, length):
return length * width
# Now you can call roomArea function
Print(roomArea(length = 50, width = 40))
- Default arguments Creates a function that can be called with fewer arguments than it is defined to allow i.e the it assumes the default value if a value is not provided in the function call for that argument.
An example is as shown below:
# Function definition is here
def displayInfo(city,address = 40400):
"This prints a passed info into this function"
print ("city: ", city)
print ("Address: ", address)
return
# To call the displayName function
displayInfo('Nairobi', address = 1020)
displayInfo('Paris' )
The output is as shown:
city: Nairobi
Address: 1020
city: Paris
Address: 40400
- Variable-length arguments Sometimes one may need to pass a function of more arguments than specified in the definition. These arguments are called variable-length arguments and are unnamed in the function definition.
Syntax for a function with non-keyword variable arguments is given below
def functionname(formal_argument, *variable_tuple ):
"Code statements"
return [expression]
An asterisk (*) is placed before the variable name that holds the value of all the non keyword arguments.
For example:
def matchScores(roundNo, *score):
print('Current Round: ', roundNo)
for i in score:
print('Score: ',i)
return
matchScores(5)
matchScores(9,20,40,30)
The output is:
Current Round: 5
Current Round: 9
Score: 20
Score: 40
Score: 30
-
Anonymous Function
The
def
andreturn
keywords are not used when declaring this type of function. Small functions may be implicitly created usinglambda
keyword.Lambda
forms takes any no of arguments but only returns one type of value and cannot contain multiple expressions or commands. It requires an expression and parameters just like any other function. A lambda function may shorten the normal function to a single line expression as shown:
# To add two variable values
def add(x, y)
return x + y
# Using lambda function
lambda x, y : x + y
# To double the value of a variable
def double(x):
return x * 2
# Using lambda function
lambda x, y : 2 * x
lambda
can also be used with conditional statements
minimum = lambda x, y : x if x < y else y
print(minimum(3,9))
This produces an output of 3 which is the smallest amongst the given parameters.
Away from function arguments, there are various amazing ways of applying functions to get a given task handled and have a minimized codes as well.
The Map Function
The map
function applies a given function to each element of a sequence and returns a modified list.
It's syntax is:
map(function, input_list)
def square(list1):
myList = []
for i in list1:
myList.append(i**2)
return myList
print(square([2,3,4,5,6]))
This produces an output of:
[4, 9, 16, 25, 36]
The same output can be achieved by the following function:
myList = [2,3,4,5,6]
print(list(map(lambda x : x**2, myList)))
The Filter Function
From the name, it filters items out of a sequence in relation to the given conditions.
It's syntax is:
filter(function, input_list)
def myFunc(list1):
myList = [x for x in list1 if x > 2]
return myList
print(myFunc([0,2,5,3,7,9]))
The output is:
[5, 3, 7, 9]
On applying the filter function to obtain the same result:
myList = [0,2,5,3,7,9]
print( list( filter( lambda x: x > 2, myList)))
Functions support various support operations such as being passed as an argument, returned from a function, modified and assigned to a variable. This is a fundamental concept to understand before delving into creating python decorators (A decorators is a design pattern in python that allows a user to add new functionalities to an existing object without modifying it’s structure).
Being passed as an argument
A function can take in other functions as it’s arguments. This enables the argumented function to input data into the defined function.
def stringFunction():
return "Hello World!"
def worldSplit(stringFunction):
func = stringFunction()
return func.split()
print(worldSplit(stringFunction))
Output
['Hello', 'World!']
The above function worldSplit(stringFunction):
takes in stringFunction():
as an argument and returns a list composed of stringed words from the argument function.
Returned from a function
A function can as well return another function and the ultimate output will be code executed from the returned function as shown below.
def print_function():
def helloWorld():
return "Hello World"
return helloWorld()
output = print_function()
print(output)
Output is
Hello World
From the above code we get to see that a function can also be assigned to a variable:
output = print_function()
That’s it for now. Stay tuned as we’ll get to learn about python decorators in my next article.
If you guys found this post helpful then save it so you can refer anytime 😊.
Happy Coding! 👨💻 👩💻
Top comments (0)