In this article we want to learn How to Return a Function in Python, as we already know that functions in Python are one of the important concept, but first of all let’s talk simply about function itself and after we are going to talk about return a function in Python.
What are Functions in Python?
In Python, functions are blocks of reusable code designed to perform a specific task. Using functions you can encapsulate code into a single unit that can be executed by calling the function’s name. Functions helps in organizing code, and makes it more readable, and reducing redundancy.
How to Define a Function in Python?
You can define a function by using def keyword, followed by the function name and parentheses (). Inside the parentheses, you can include parameters that the function will take as input.
This is an example of function in Python
1 2 |
def sayHello(name): print(f"Hello, {name}") |
How to Call a Function in Python?
For executing a function, we need to call that function by its name followed by parentheses. If the function takes parameters, you pass arguments inside these parentheses.
This is an example of calling a function in Python
1 |
sayHello("Codeloop") |
Run the code and this will be the result
Python function returns
When it comes to Python return, one important note that you should remember is that in Python return value can be anything. while most functions return some specific value or object, like string or list, Python functions can return almost any type of data. for example a function can return a complex data structure like dictionary or set, a custom object that you have defined, or even an instance of builtin Python class like int or float.
This is an example of function that demonstrates this idea.
1 2 3 4 5 6 7 8 9 10 11 |
import random def random_return(): rand_int = random.randint(1, 100) rand_float = random.uniform(1.0, 100.0) rand_bool = random.choice([True, False]) rand_str = ''.join(random.choices('codeloopcodeloopcodeloopcodeloop', k=10)) return rand_int, rand_float, rand_bool, rand_str print(random_return()) |
This function uses random module to generate random integer, random floating point number, random boolean value and random string. after that it returns all of these values as a tuple.
This will be the result
Subscribe and Get Free Video Courses & Articles in your Email