As a beginner, we write very small programs. When a program is small enough, we can keep all of the details of the program in our heads at once. Real application programs are 100 to 10000 times larger than any program you have likely written (or maybe even worked on); they are simply too large and complex to hold all their details in our heads.
One key solution to managing the complexity of large software is modular programming: the code is composed of many different code modules commonly known as developed functions. This allows different developers to take on discrete pieces of the system and design and implement them without having to understand all the rest. In this article, we’ll look into different types of functions in Python.
What is a Function?
A function is a block of code that performs some specific task. It can be called and reused multiple times. You can pass information and it can send information back. Many programming languages have two types of functions:
- Built-In Functions: A function that is built into an application or programming language and can be accessed by end-users. For example, most spreadsheet applications support a built-in SUM function that adds up all cells in a row or column. Similarly, in C printf() and scanf() are built-in functions that are used to print and read values.
- User-Defined Functions: A user can define functions to do a task relevant to their programs. Such functions are called user-defined functions. The main() function in which we write all our programs is a user-defined function.
When you call a function, the program will pause the current program and execute the function. The function will be read from top to bottom. Once the function is complete, the program continues to run where it had paused. If the function returned a value, that value will be used where the function was called.
Types of Functions in Python
As mentioned above you use functions in programming to bundle a set of instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a sub-program and called when needed. That means that a function is a piece of code written to carry out a specified task. To carry out that specific task, the function might or might not need multiple inputs. When the task is carried out, the function can or can not return one or more values.
There are three types of functions in Python:
- Built-in functions: These are the functions built-in in Python such as help() to ask for help, min() to get the minimum value, print() to print an object to the terminal.
- User-Defined Functions (UDFs): These are the functions created by the user according to their programming needs.
- Anonymous functions: These functions are also called lambda functions because they are not declared with the standard def keyword.
Functions vs Methods
A function is a block of code to carry out a specific task, contains its own scope, and is called by its name. All functions may contain zero (no) arguments or more than one argument. On exit, a function can or can not return one or more values.
Basic Function Syntax
def functionName( arg1, arg2,….): ……. # Function_body ……..
Following is an example of a function greet which prints a greeting message for a name passed in the function.
def greet(name): """ This function greets to the person passed in as a parameter """ print("Hello, " + name + ". Good morning!") >>> greet('Paul') Hello, Paul. Good morning!
A method in Python is somewhat similar to a function, except it is associated with objects/classes. Methods in Python are very similar to functions except for two major differences.
- The method is implicitly used for an object for which it is called.
- The method is accessible to data that is contained within the class.
Basic Method Syntax
class ClassName: def method_name(): ………….. # Method_body ………………
Let’s understand the method through the following simple code:
class Pet(object): def my_method(self): print("I am a Cat") cat = Pet() cat.my_method()
I am a Cat
In the above code, we first defined the class Pet, then we created an object cat from this blueprint. Next, we call our custom method called my_method with the object (i.e., cat).
Parameters vs Arguments
The terms parameter and argument are used interchangeably by many programmers, but they both have different meanings.
A parameter is a special kind of variable used in a function to refer to one of the pieces of data provided as input to the function. These data are the values of the arguments with which the function will be called/invoked.
In simpler terms, the argument is the actual value supplied to a function, whereas the parameter is the variable inside the definition of the function. We can say that a parameter is a type that appears in function definitions, while an argument is an instance that appears in the function calls. In the above example name is called parameter and Paul is called an argument.
How To Define a User-Defined Function (UDF) in Python?
The four steps in defining a function in Python are the following:
- Use the keyword def to declare the function and follow this up with the function name.
- Add parameters to the function. These should be written within the parentheses of the function. End your line with a colon.
- Add statements that the function should execute.
- End your function with a return statement if the function should output something. Without the return statement, your function will return an object None.
Function Arguments in Python
Above you learned about the difference between the parameters and arguments. In short, arguments are the things that are given to any function all, while the function code refers to the arguments by their parameter names. There are four types of arguments that Python UDFs can take:
- Default arguments
- Required arguments
- Keyword arguments
- Variable number of arguments
Default arguments are those that take a default value if no argument value is passed during the function call. You can assign this default value by with the assignment operator =, just like in the following example:
# Define `plus()` function def plus(a,b = 2): return a + b # Call `plus()` with only `a` parameter plus(a=1) # Call `plus()` with `a` and `b` parameters plus(a=1, b=3)
As the name suggests, the required arguments of a UDF are those that have to be there. These arguments need to be passed during the function call and in precisely the right order, just in the following example:
# Define `plus()` with required arguments def plus(a,b): return a + b
You need arguments that map to the a as well as the b parameters to call the function without getting any errors. If you switch around a and b, the result won’t be different, but it might be if you change the function plus() to the following:
# Define `plus()` with required arguments def plus(a,b): return a/b
If you want to make sure that you call all the arguments in the right order, you can choose the keyword arguments in your function call. You use these to identify the arguments by their parameter name. Let’s take the example from the above to make it clear.
# Define `plus()` function def plus(a,b): return a + b # Call `plus()` function with parameters plus(2,3) # Call `plus()` function with keyword arguments plus(a=1, b=2)
Note that by using the keyword arguments, you can also switch around the order of the parameters and still get the same result when you execute your function:
# Define `plus()` function def plus(a,b): return a + b # Call `plus()` function with keyword arguments plus(b=2, a=1)
Variable number of arguments
In cases where you don’t know the exact number of arguments that you want to pass to a function, you can use the following syntax with *args:
# Define `plus()` function to accept a variable number of arguments def plus(*args): return sum(args) # Calculate the sum plus(1,4,5) plus(5,6,7,8,4)
The asterisk (*) is placed before the variable name that holds the values of all non-keyword variable arguments. Note here that you might as well have passed *varint, *var_int_args, or any other name to the plus() function. Try replacing *args with another name that includes the asterisk. You’ll see that the above code keeps working!
Global vs Local Variables
In general, variables that are defined inside a function have a local scope, and those defined outside have a global scope. That means that local variables are defined within a function block and can only be accessed inside that function, while global variables can be accessed by all the functions that might be there in your script.
# Global variable `init` init = 1 # Define `plus()` function to accept a variable number of arguments def plus(*args): # Local variable `sum()` total = 0 for i in args: total += i return total # Access the global variable print("this is the initialized value " + str(init)) # (Try to) access the local variable print("this is the sum " + str(total))
You’ll see that you’ll get a NameError that says that the name ‘total’ is not defined when you try to print out the local variable total that was defined inside the function body. The init variable, on the other hand, can be printed out without any problems.
Anonymous Functions in Python
Anonymous functions are also called lambda functions in Python because instead of declaring them with the standard def keyword, you use the keyword lambda.
double = lambda x: x*2 double(5)
lambda x: x*2 is the anonymous or lambda function. x is the argument, and x*2 is the expression or instruction that gets evaluated and returned. What’s special about this function is that it has no name, like the examples that you have seen in the above example functions.