In this Python tutorial, we will learn about functions in Python, how to define a function with def, how to call it, how parameters and arguments work, and how a function can return a value. Functions help you keep Python code reusable, readable, and easier to test.
What are Functions in Python?
A function in Python is a named block of code that performs a specific task. You define a function once, and then call it whenever that task has to be performed. A function may take input values, process them, and may return a result to the caller.
Functions are a way of keeping the code organised in a modular fashion. There are many benefits in doing so. Some of them are:
- Encapsulation – An action that is required to be performed multiple times during the lifetime of application, could be encapsulated as a function for code re-usability, thus reducing the code length and redundancy.
- Maintenance – As functions are the result of an organized code, they help in maintenance and following up with the code easily.
- Readability – A well-named function such as
calculate_total()orsend_email()tells the reader what the code is trying to do. - Testing – A small function with clear inputs and output is easier to test than a long block of repeated code.
Python Function Syntax with def Keyword
def statement is used to define a function.
The syntax for a function is shown in the following.
def function_name ( parameters ):
body
where
def | A Python keyword to define a function. |
function_name | A string. A name that is given to the function, usually that captures what the function does. You may given whatever the function name you would like, but with some rules to name them, which we will discuss in the following. |
| parameters | Comma separated values. These are the inputs to the function, that it can work on, or transform. |
| body | One or more Python statements. The body of the function is the what defines a function does. |
Even though the syntax is small, it gives us the main parts of a Python function: the keyword def, the function name, optional parameters inside parentheses, a colon, and an indented function body.
Since Python is a dynamic language, there is no return type mentioned for a function. However, variables of any type or objects could be returned from a function. And whoever is calling the function should be aware of the variable type that could be returned. For this reason, it is always a good practice to have better and in-detail documentation for functions in your application. This helps in a quick and clear understanding of the task a function can do, when working in teams or making a time travel and revisiting the code that is written by you.
parameters which are inputs for the task done by a function, could become optional if the function is always aware about location of data that is required or if the task doesn’t need any. Multiple parameters could be sent as inputs(arguments) to the functions separated by comma(,).
function_name is the identifier for the function. Rest of the program or another programs could call this function using identifier, the function name.
body is the set of statements that follow the colon(:) symbol in the definition of function. These set of statements collectively make the task(i.e., required action) and is the piece of code that is executed when the function is called.
Python Function Naming Rules and Indentation
A Python function name follows the same basic rules as other Python identifiers. It can contain letters, digits, and underscores, but it cannot start with a digit. It also cannot be a Python keyword such as def, return, for, or class.
Use meaningful lowercase names with underscores when the name has more than one word. For example, calculate_area(), get_student_name(), and print_invoice() are easier to understand than names such as ca() or func1().
Indentation is part of Python syntax. The statements that belong to a function must be indented under the def line. When the indentation ends, the function body ends.
Built-in Functions and User-defined Functions in Python
Python provides many Built-in Functions like print() to print something to output, max() to find the maximum of the numbers passed as arguments to it, and there are many more functions like these which come with the standard python installation. The list of functions may vary from version to version. You may also refer to the official Python documentation for the current list of built-in functions.
Python also provides the programmer or developer the ability to code his/her own functions. These are called user defined functions. By following the syntax of python function that is already mentioned above, you could write your own functions required for the specific problem that you chose to solve.
In regular Python programming, you will commonly work with these function categories:
- Built-in functions, such as
print(),len(),type(),max(), andsum(). - User-defined functions, which you create using the
defkeyword. - Anonymous functions, also called lambda functions, which are small functions created using
lambda. - Recursive functions, which call themselves to solve a problem in smaller steps.
There are many ways you can prepare your user defined function based on the parameters they have been defined with. We cover these scenarios in the following examples.
Python Function Examples with Arguments and Return Values
1. Basic Python Function without Arguments
In this example program, we will define a function with the name welcome and accepts no parameters. The function just prints a string to standard console output.
Python Program
def welcome():
print('Welcome to www.tutorialkart.com for learning Python.')
welcome()
Output
Welcome to www.tutorialkart.com for learning Python.
Please note that when we call the function welcome, we are using parenthesis after the function name. Also, we are not passing any argument(s) inside parenthesis, since function definition says that welcome does not accept any arguments.
2. Python Function with Fixed Number of Parameters
In this example, we will define a function multiplication with two parameters: num1 and num2.
Python Program
def multiplication(num1, num2):
return num1*num2
result=multiplication(12,89)
print(result)
result=multiplication(198,389)
print(result)
result=multiplication(98,56)
print(result)
Output
1068
77022
5488
When we called multiplication function, we passed two arguments, since the function requires two arguments.
In the function definition, num1 and num2 are called parameters. In the function call, values such as 12 and 89 are called arguments. In everyday usage, both words are sometimes used loosely, but this distinction is useful when learning function calls.
3. Python Function with Default Value for Parameter
In this example, we will write a function with with two arguments, and a default value for the second argument.
Python Program
def multiplication(num1,num2=24):
"""num1 takes number
num2 takes number, if nothing is provided, 24 is taken as default
multiplication(num1,num2) returns the multiplication of num1 and num2
Ex: multiplication(2,7) returns 2*7=14
multiplication(2) returns 2*24=28)"""
return num1*num2
result=multiplication(12)#num1=12, num2=24 : as no value provided for num2, 24 is taken as default value
print(result)
result=multiplication(198,389)#num1=198, num2=389
print(result)
result=multiplication(98) #num1=98, num2=24
print(result)
Output
288
77022
2352
Note : default arguments should follow non-default arguments. Failing to do so results in syntax error as shown in the example below :
def multiplication(num1=2,num2):
"""num1 takes number
num2 takes number, if nothing is provided, 24 is taken as default
multiplication(num1,num2) returns the multiplication of num1 and num2
Ex: multiplication(2,7) returns 2*7=14
multiplication(2) returns 2*24=48)"""
return num1*num2
Output
File "/home/arjun/PycharmProjects/PythonTutorial/functions/func_args_default_val_error.py", line 1
def multiplication(num1=2,num2):
^
SyntaxError: non-default argument follows default argument
The correct order is to place required parameters first, and then parameters with default values.
def function_name(required_parameter, optional_parameter=default_value):
# function body
pass
4. Python Function with Arbitrary Number of Arguments
In this example, we will define a function that can accept any number of arguments.
To accept any number of arguments, provide *args as parameter.
Python Program
def multiplication(*args):
"""multiplication functions works with args as list of numbers
multiplication() returns the multiplication of list of numbers in args
Ex: multiplication(2,7,3) returns 2*7*3=42
multiplication(3,4,4,5) returns 3*4*4*5=240)"""
result=1
for i in args:
result=result*i
return result
result=multiplication(12,89, 2, 57)
print(result)
result=multiplication(198, 38, 47)
print(result)
result=multiplication(8, 6)
print(result)
Output
121752
353628
48
Python Function Return Statement
The return statement sends a value back to the place where the function was called. A function can return a number, string, list, dictionary, object, tuple, or any other Python value. If a function does not use return, it returns None by default.
In the following example, the function calculates a value and returns it. The returned value is stored in the variable area.
def rectangle_area(length, width):
return length * width
area = rectangle_area(10, 5)
print(area)
Output
50
A function can also contain more than one return statement. Once Python executes a return statement, the function ends immediately.
Python Positional Arguments and Keyword Arguments
Python allows you to pass arguments by position or by keyword. Positional arguments are matched based on their order. Keyword arguments are matched based on parameter names.
def introduce(name, age):
print(f"{name} is {age} years old.")
introduce("Ravi", 21) # positional arguments
introduce(age=21, name="Ravi") # keyword arguments
Output
Ravi is 21 years old.
Ravi is 21 years old.
Keyword arguments are helpful when a function has several parameters because the function call becomes more readable. After you use a keyword argument in a function call, the following arguments in that call should also be keyword arguments.
Python **kwargs for Arbitrary Keyword Arguments
The *args form collects extra positional arguments into a tuple. The **kwargs form collects extra keyword arguments into a dictionary. Use **kwargs when the function has to accept named values that may vary from call to call.
def print_profile(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_profile(name="Anu", course="Python", level="Beginner")
Output
name: Anu
course: Python
level: Beginner
Use *args for an unknown number of positional values and **kwargs for an unknown number of named values. In many beginner programs, fixed parameters and default parameters are enough. Use arbitrary arguments only when the function really needs that flexibility.
Python Function Docstrings and Type Hints
A docstring is a string written as the first statement inside a function. It explains what the function does. Type hints are optional annotations that describe the expected types of parameters and return value. Python does not require type hints at runtime, but they make code easier to read and maintain.
def add_numbers(a: int, b: int) -> int:
"""Return the sum of two integers."""
return a + b
print(add_numbers(10, 20))
Output
30
Docstrings are useful when you or another developer returns to the code later. They are also used by Python’s help tools and many editors to show function information.
Common Mistakes with Python Functions
- Forgetting parentheses while calling a function: use
welcome(), not justwelcome, when you want to execute the function. - Wrong indentation: all statements inside the function body must be indented consistently.
- Using a value before returning it: if the caller needs the result, use
returninstead of only printing the value. - Placing default parameters before required parameters: required parameters should come first.
- Writing one large function: split long functions into smaller functions when each part performs a separate task.
Editorial QA Checklist for Python Functions Tutorial
- Does the tutorial clearly explain the difference between defining a Python function and calling a Python function?
- Are examples included for no arguments, fixed arguments, default arguments,
*args,**kwargs, andreturn? - Do all Python examples use correct indentation and valid function syntax?
- Are output blocks separated from Python code blocks for easy reading?
- Does the explanation distinguish parameters in the function definition from arguments in the function call?
FAQs on Functions in Python
What are functions in Python?
Functions in Python are reusable blocks of code that perform a specific task. A function is usually defined with the def keyword, may accept parameters, and may return a value using the return statement.
What is an example of a function in Python?
A simple example is def greet(): print("Hello"). After defining it, you can call it using greet(). The function body runs only when the function is called.
What are the main types of functions in Python?
Common types include built-in functions such as print() and len(), user-defined functions created with def, anonymous lambda functions, and recursive functions that call themselves.
What is the difference between parameters and arguments in Python functions?
Parameters are the variable names written in the function definition. Arguments are the actual values passed to the function when it is called.
What happens if a Python function has no return statement?
If a Python function does not have a return statement, it returns None by default after the function body finishes running.
Summary of Python Functions
In this Python Tutorial of Python Functions, we have learnt what a function is, the syntax for defining a function in python, a basic understanding on the elements presented in syntax, example python programs for some of the possible functions with different kinds of arguments.
A good Python function has a clear name, a focused task, well-chosen parameters, and a predictable return value. Start with simple user-defined functions using def, then use default parameters, keyword arguments, *args, and **kwargs when your program needs them.
TutorialKart.com