By: Rajendra Gupta | Updated: 2024-06-12 | Comments | Related: > Python
Problem
Using Python functions allows you to solve the problem of having to write repeated code, make code easier to understand, and reduce code complexity. In this tip, we look at how to create Python functions.
Solution
Functions are an excellent way to divide large programs into small pieces of code that perform a specific task. You can reuse these functions without rewriting the code inside them. Suppose you create a function to validate input values. Now, while executing the main program, you can call this function to perform that specific task.
We can divide Python functions into two categories:
- Built-in functions
- User-defined functions
Let's explore these Python functions in detail.
Built-in Functions
Python has several pre-defined functions that you can use without writing any code. These functions are known as built-in functions. A few built-in functions are listed below:
- Print(): prints message to the console.
- len(): checks an object's length or number of items.
- range(): generates a sequence of numbers.
- type(): returns the object or data type in Python.
- input(): takes user input for the given parameter.
User-defined Functions
Any function created by a developer to execute code is known as a user-defined function. We need to define a function with the def keyword.
The following diagram shows a basic Python function:
def myfunction(): print("Welcome to python functions") myfunction()
![basic Python function](/tipimages2/8014_explore-python-functions-1.png)
As explained above, we created a function, myfunction(), to print a message using the print built-in function. You can call this function anywhere in the code to print this message.
Indentation is a must for defining code in Python functions. If you try to run the code without indentation, it gives an error:
![Error](/tipimages2/8014_explore-python-functions-2.png)
Functions with Arguments
You can have a user-defined function with or without the argument. In the earlier defined myfunction(), we used no argument.
Suppose we want to calculate the sum of two numbers using a Python function. We need to have two argument values passed to the function.
In the following function, we define the function with parameters as sum(a,b). We can pass the argument's value by calling the function a sum(10,20).
def sum(a,b): result = a + b print(f"The sum of numbers {a} and {b} is: {result}") sum(10,20)
![Functions with arguments](/tipimages2/8014_explore-python-functions-3.png)
Types of Arguments in a Function
We can have the following types of arguments in a function.
Default Argument
We can specify a default value for an argument in the function. If we call the function without any explicit argument value, the function executes with the default argument; otherwise, the explicit argument will take precedence.
The following code defines the default argument values as a=0 and b=0. If we directly call the function sum(), it returns 0; if we pass the explicit value sum(1,5), it returns 6.
def sum(a=0,b=0): result = a + b print(f"The sum of numbers {a} and {b} is: {result}") sum() sum(1,5)
![Default argument](/tipimages2/8014_explore-python-functions-4.png)
Arbitrary Arguments
We can use the * keyword in the function to accept n number of arguments. For example, let's convert the sum function for the arbitrary argument.
In the function below, we specify the argument as *numbers and the logic for adding the numbers. Now, we can specify the number of arguments, and the function does the addition. For example, I have called the function with 2, 4, and 12 input values.
def addition(*numbers): sum = 0 for n in numbers: sum = sum + n print("Sum:", sum) addition(10,20) addition(10,20,30,50) addition(1,2,3,4,5,6,7,8,9,10,11,12)
![Arbitrary Arguments](/tipimages2/8014_explore-python-functions-5.png)
Keyword Arguments
If you have multiple parameters defined in a function, you need to pass the arguments value in the same order as it is defined. However, what if you want to mix the order of arguments? Let's look at below example:
def emp(first_name,last_name,age): print("Employee:" + first_name + ' '+ last_name, age) emp(first_name='John',last_name='Wick',age=35)
In this example, we pass the argument name while calling the function. Therefore, the position of the argument does not matter. All Python functions below return the same output irrespective of keyword positioning.
emp(first_name='John',last_name='Wick',age=35) emp(last_name='Wick',first_name='John',age=35) emp(age=35,last_name='Wick',first_name='John')
![Keyword Arguments](/tipimages2/8014_explore-python-functions-6.png)
However, the positioning matters if you do not use argument names. By default, the first argument is mapped to the first value, the second argument is mapped to the second value, and so on.
emp('John','Wick',35) emp('Wick','John',35)
![positioning matters](/tipimages2/8014_explore-python-functions-7.png)
What if you mix the keyword argument and positional argument? In the example below, we defined the last_name and age argument names but did not specify the first_name. Therefore, Python maps the positioning argument first and then takes the keyword argument.
emp('John',last_name='Wick',age=35)
![](/tipimages2/8014_explore-python-functions-8.png)
However, if you change the code to specify a positional argument after a keyword argument, Python generates an error, as shown below.
emp(first_name='John',last_name='Wick',35)
![Error](/tipimages2/8014_explore-python-functions-9.png)
The Return and Pass Statement in Python Functions
Return Statement
A Python function uses the RETURN keyword to return a single or multiple values from the function. By default, the function does not return any values.
In the below Python function, we use the return keyword to return the value of the variable sum.
def addition(a,b,c): sum = a+b+c return sum addition(1,2,3)
Similarly, we can return multiple values from a function. For example, in the code below, we calculate addition, subtraction, and multiplication from inputs n1 and n2. It returns the values of the variable add, sub, and multiply.
While executing the function, we can assign these multiple return values to the different variables and use them in subsequent code. For example, the first return value add is assigned to a, and the second return value sub is assigned to b.
def maths(n1,n2): add = n1 + n2 sub = n1 - n2 multiply = n1 * n2 return add, sub, multiply a, b, c = maths(10, 2) print("Addition: ", a) print("Subtraction: ", b) print("Multiplication: ", c)
![The Return and Pass Statement in Python Functions](/tipimages2/8014_explore-python-functions-10.png)
Pass Statement
We can use the pass statement to skip executing the code.
In the example below, we want to print a message if the number is positive; otherwise, skip the code execution. Therefore, we specify the pass keyword in the else condition.
def passexample(input_value): if input_value>0: print("positive number") else: pass passexample(1) passexample(-1)
![Pass Statement](/tipimages2/8014_explore-python-functions-11.png)
Recursive Function in Python
If a function calls itself repeatedly, it is called a recursive function. Suppose we need a Fibonacci sequence that generates a pattern where each number has a sum of the two preceding numbers.
The following code takes the input for num and recalls the function repeatedly until its value is less than or equal to 1.
def fibonacci_series(num): if num <= 1: return num else: return fibonacci_series(num - 1) + fibonacci_series(num - 2) for i in range(10): print(fibonacci_series(i))
![Recursive Function in Python](/tipimages2/8014_explore-python-functions-12.png)
Next Steps
- Stay tuned for more Python tutorials in upcoming tips.
- Explore existing Python tips on MSSQLTips.com.
About the author
![MSSQLTips author Rajendra Gupta](/images/Rajendra-Gupta-20220116.png)
This author pledges the content of this article is based on professional experience and not AI generated.
View all my tips
Article Last Updated: 2024-06-12