How to Define a Function in Python?
What is a Function?
In programming, a piece of code that executes a specific task or a group of related operations is known as a function.
What does Python Functions Do?
If you frequently reuse the same code block, it is preferred to write a comparable function. Next time when you require this piece of code, call the function.
User-defined functions have several significant advantages:
- When you need to complete the same task regularly, functions come in handy. Instead of repeatedly entering or copying and pasting the same code snippet, you may just call a function once it has been defined. Additionally, if you choose to alter a code block, you must alter the portion where the function is defined. Anywhere the function is invoked, this modification will take effect.
- You can divide complicated programs into smaller steps by defining and using functions. Each stage may serve a distinct purpose in solving a particular job.
- Finally, your code is typically simpler to understand when using user-defined functions. Each code block's function is readily visible, indicating which task it completes. This is especially true if functions are defined in accordance with the best practises later in the article.
Python Function Definition: Syntax and Samples
The following is the syntax for declaring a function in Python.
def function_name(arguments) block of code
The syntax is described as follows:
- To tell Python that a new function is being defined, we begin by using the def keyword.
- Next, we give our function a name that makes sense.
- The function's required arguments or parameters are then listed within parentheses. There is no restriction on how many factors you can use. By creating a function without parameters, the parentheses may also be omitted.
- The colon character indicates a transition from the function's header to its body ":"
- We write the code block required to complete the task after the indentation.
- We leave an empty line after the code block to indicate that the function definition is complete.
You should practice function definition now that you are familiar with the syntax.
Works With Just One Parameter
Let us start with a straightforward function that accepts a name as an argument and prints out the first line of the introduction. How to define this function is as follows:
def introduction(name): “ “ “ Introduces a person given their name” “ “ print('Hello! My name is, name)
The introduction is a function that takes a single argument, name. Only one line in the function's body prints the message along with the name. Additionally, we added a note that outlines the goal of our function.
Let's call it now and evaluate the results:
Hello! My name is, rohan
Because the name is a string, we must supply it to our function in quotation marks. The output is the welcome message.
If a function is used frequently, even a simple one-line function can save us time. So, consider the advantages of lengthier code blocks!
Without Parameter Functions
You should define functions without any arguments in various circumstances. Creating a function that displays a message telling the user if their passwords is incorrect will serve as an example.
def error_message_password(): "Prints out an error message about the incorrect password" print('Sorry. We couldn’t log you in. The password you entered didn’t match our records.')
There are no parameters necessary for this function. Therefore, we define it without using any parenthesis. This function is invoked by writing its name followed by a pair of empty parentheses:
Sorry. We couldn’t log you in. The password you entered didn’t match our records
Multiple Parameter Functions
Let's now define a function with more parameters that are more complicated. This time, depending on a person's birth date, we want to develop a function that would estimate their age in years (birth year, birth month, and birthday).
From datetime import date def get_age(birth_year, birth_month, birth_day): "Calculates age (in years) based on birth year, birth month, and birthday.""" birth_date = date(birth_year, birth_month, birth_day) age = date.today() - birth_date age_years = age.days / 365.2425 return age_years
We begin by importing the date class from the datetime module to work with dates conveniently.
The definition of our get age function is now complete. Be aware that the birth year, birth month, and birthday inputs are all required for this function. The birth date is initially defined in the get age function's body using the supplied data.
The age in days is then determined by deducting the birthdate from the current date. The age in years is finally determined by dividing the age in days by 365.2425, the typical number of days in a year.
The function specification ends with a return statement. In the previous instances, the print() function, which let us see each function's output in our earlier examples, was used. But most of the time, you need the function to return a specific value rather than necessarily print it out.
The return statement is then applicable. Use the return keyword to specify the return value, that can be nearly any Python object (such as an integer, text, list, tuple, dictionary, set, etc.).
Let's now invoke our get age() function with several inputs. Regarding passing the arguments, we have two choices:
Positional justifications. This entails passing the arguments in the order that the function definition's parameters appear:
get_age(1987, 9, 2)
Keyword Arguments: The arguments are passed in an arbitrary order, and each parameter is specified by name:
get_age(birth_day=2, birth_month=9, birth_year=1987)
The order of the arguments is not important when using keyword arguments, but you must type the exact names of every parameter.
Also, remember that the number of arguments and parameters in the function definition must match regardless of the option you select.
You can see from the output above that the getting age() function responds to the return statement's request for the age in years. But perhaps we should assign this value to a variable rather than just print it out.
kate_age = get_age(1987, 9, 2) print(kate_age)
The number produced by the getting age() function is now stored in the Kate age variable.
Functions That Produce No Output
Every Python function produces a value. If you don't use the return statement explicitly in Python, it will be provided implicitly with nothing at all as the return value.
In some cases, you might like your function to perform certain tasks without returning any data.This was evident in the first two instances. We were printing the function's output without explicitly returning a value.
Let's now assign the output of our error message password() method to a variable and examine its value:
error = error_message_password() print(error)
As you've seen, the error variable actually stores the value None instead of the error message that you might expect. This is due to the fact that we printed the following error rather than explicitly returning its value in our password() function's error message.
Therefore, pay great attention and make sure the return statement is always present if you would like your procedure to return a value other than None.
Best Practices for Developing Python Functions
Let’s see some best practices for Python function definition:
- Give your function names some meaning. Your functions ought to be named in a way that accurately describes the expected duties. This makes your code easier for you to read when you return to it later, as well as for other programmers who are working with it. Additionally, adhere to the Python conventions for function names, which only allow lowercase letters and underscores between words.
- Give each function just one job to do. One task should ideally be handled by one function. This promotes clean code organization and increases readability.
- Specify your thoughts on the function task. Right beneath the heading, add a succinct description of what the function does. This comment should be included in triple-double quotes ("") and is known as a docstring.
- You should follow these guidelines to make your code look neat and polished.