Function in Python

In this python tutorial, you will learn about function in python with a few examples. Here we will check:

  • What is a function in Python?
  • How to create a function in python
  • How to call a function in python
  • Arguments in a python function
  • Python arbitrary arguments
  • Python keyword arguments
  • Default parameter value
  • Passing a list as an argument in python
  • The return value in python
  • Return vs print in python
  • Function vs method in python
  • Yield vs return python
  • Function inside a function in python
  • Python nested function variable scoping

What is a function in Python?

What is a function in Python? Function in python provides reusability, organized, and modular code to perform a specific action. The function makes the code easier by breaking the program into smaller chunks and it avoids repetition and makes the code reusable. A function only runs when it is called.

Python has many built-in functions. We can also create our own function to do more specific jobs, and it is called a user-defined function. You can check out Python built-in functions with examples.

How to create a function in Python

Let us see how to create a function in Python?

Using the def statement is the most common way to define a function in python. Here, the parameter is an optional list of identifiers that gets bound to the value supplied as arguments separated by commas.

Example:

def function(parameters):
print("Welcome to function")

How to call a function in Python

Now, let us see how to call a function in Python? To call a function Python, we will use the function name followed by a parenthesis.

Example:

def new_function():
print("Welcome to function")
new_function()

After writing the above code (calling a function in python), Ones you will call “new_function()” then the output will appear as a “ Welcome to function “. Here, we call the function by its function name with parameters.

You can refer to the below screenshot for calling a function in python.

Calling a function in python
Calling a function in python

Python function arguments

In python, information is passed into functions as arguments. Arguments are passed inside the parenthesis and we can add as many arguments, but it should be separated with commas. Here, will see a single argument “ stu_name “.

Example:

def new_function(stu_name):
print(stu_name + " good ")
new_function("James")
new_function("Kavish")

After writing the above code (arguments in python), Ones you will call “new_function()” then the output will appear as a “ James good Kavish good “. Here, when the function is called we pass the student name which is used inside the function and it will print with “good”.

You can refer to the below screenshot arguments in python.

Arguments in python
Arguments in python

Here, we will see the function with two arguments and the function must be called with the correct number of arguments to avoid an error.

Example:

def new_function(name, behaviour):
print(name + " " + behaviour)
new_function("James", "good")

After writing the above code (function with two arguments in python), Ones you will call “new_function()” then the output will appear as a “ James good “. Here, the function is called with two arguments as it expects two arguments.

You can refer to the below screenshot function with two arguments in python.

python function arguments
python function arguments

Python arbitrary arguments

In python, if we don’t know in advance that how many numbers of arguments will be passed into the function then we use the asterisk “(*)” before the parameter name in the function.

Example:

def new_function(*food):
for foods in food:
print("Favorite", foods)
new_function("pizza", "pasta", "maggi")

After writing the above code (python arbitrary arguments), Ones you will call “new_function()” then the output will appear as a “ Favorite pizza Favorite pasta Favorite maggi “. Here, we called the function with multiple arguments and inside the function, we used the for loop to retrieve all arguments.

You can refer to the below screenshot python arbitrary arguments.

Python arbitrary arguments
Python arbitrary arguments

Python keyword arguments

A keyword argument is an argument passed to a function with “keyword = value”. Here, the keyword is the keyword argument and value is the object passed.

Example:

def new_function(student1, student2):
print("Highest marks is obtained by " + student2)
new_function(student1 = "John", student2 = "Kavish")

After writing the above code (python keyword arguments), Ones you will call “new_function()” then the output will appear as a “ Highest marks is obtained by Kavish “. Here, the keyword argument is passed to the function and the order of the argument does not matter.

You can refer to the below screenshot python keyword arguments.

Python keyword arguments
Python keyword arguments

Default parameter value in Python functions

In python, if a function is called without an argument then the arguments gets its default value is called default parameter.

Example:

def new_function(fruits = "apple"):
print("My favorite is " + fruits)
new_function("orange")
new_function()

After writing the above code (default parameter value in python), Ones you will call “new_function()” then the output will appear as a “My favorite is orange My favorite is apple“. Here, the default argument is passed automatically and it appears in the output of the function call.

You can refer to the below screenshot on Python default function parameter value.

Default parameter value in python
python default function parameter value

Python pass list as arguments to function

In python it is possible to send any data types of arguments to a function and it treat them as a same data type inside the function.

Example:

def new_function(flower):
for a in flower:
print(a)
flowers = ["rose", "lily", "tulip"]
new_function(flowers)

After writing the above code (passing a list as an argument in python), Ones you will call “new_function()” then the output will appear as a “rose lily tulip“. Here, we send the list as an argument and it will treat the same when it reaches to function.

You can refer to the below screenshot passing a list as an argument in python.

Passing a list as an argument in python
python pass list as arguments to function

Return value in Python function

We use return statement in python so that, a function return value in python.

Example:

def new_function(value)
return 10*value
print(new_function(5))

After writing the above code (return value in python), Ones you will call “new_function()” then the output will appear as a “50“. Here, the return statement follows the expression which is evaluated and it returns the value.

You can refer to the below screenshot for return value in python.

Return value in Python function
Return value in Python function

Return vs print in python

  • returnreturn is a keyword. When the return statement is reached, python will stop the current execution of a function, and it will send a value out to where the function was called. Use return when you want to send a value from one point in your code to another.
  • print print is a function you call. When we call to print it will immediately make your program write and you can see the text. We use print when we want to show value or any message to humans.

Function vs method in python

Function:

  • It is basically used for code re-usability.
  • A function is of two types:
    1. Built-in functions
    2. User-define functions
  • Functions can be used inside the class as well as outside the class.
  • A function can be called by its name.
  • The function can have different parameters or may not have any at all.

Example of Built-in function:

a = sum([10,5,15])
print(a)

You can refer to the below screenshot for Built-in function in python

Built-in function in python
Built-in function in python

Example of User-define functions:

def add(x,y):
    return x+y
print (add(10,15))

You can refer to the below screenshot for User-define function in python

Example of User-define functions
Example of User-define functions:

Methods:

  • Methods are similar to the function and the main task of the method is code re-usability.
  • Methods are defined by the user.
  • Methods always use the object-oriented programming language.
  • A method is defined inside the class.
  • A method is called by its name, but it is associated with an object.

Example of User-defined method:

class info:
    def method_s(self):
        print("This is method_s of info class.")
obj = info()
obj.method_s()

You can refer to the below screenshot for User-define method in python

User-defined method in python
User-defined method in python

Yield vs return python

YieldReturn
Yield is used for converting a regular python function into a generator Return is generally used for the end of the execution and returns the result.
It can run multiple times.Return only runs single time
Code written after yield statement execute in next function callWhile code written after the return statement will not execute
Yield is used when the generator returns the result to the caller.Return is used when the function is ready to send a value.

Function inside a function in python

A function inside a function is an inner function or a nested function. Nested functions are able to access variables and the inner function is used to protect from everything happening outside the function.

Example:

def outer_function(msg):
    msg = msg
    def inner_function():
        print(msg)
    inner_function()
if __name__ == '__main__':
    outer_function('Welcome to Python!')

After writing the above code (function inside a function in python), Once you will print then the output will appear as a “Welcome to Python!“. Here, the inner_function() is defined inside the outer_function(). So, to call inner_function we have to call first outer_function and then inner_function can execute.

You can refer to the below screenshot for function inside a function in python.

Function inside a function in python
Function inside a function in python

Let’s see what happens if we try to call inner_function() instead of outer_function(). You can refer to the below example –

Example:

def outer_function(msg):
    msg = msg
    def inner_function():
        print(msg)
    inner_function()

Once you will execute the code then it will return nothing. This is because we are not calling the outer_function(). So, to call inner_function() we have to call outer_function() first.

Python nested function variable scoping

The location where we can find a variable and to access it if required is called variable scope. A nested function can access a variable of the enclosing scope.

Example:

def fun1():
    v = 'PythonGuides'
    def fun2():
        print(v)
    fun2()
fun1()

After writing the above code (python nested function variable scoping), Once you will print then the output will appear as a “PythonGuides“. Here, we can see that it is similar to accessing the global variable from the function.

You can refer to the below screenshot for python nested function variable scoping.

Python nested function variable scoping
Python nested function variable scoping

You may like the following Python tutorials:

In this Python tutorial, we learned about python functions and also how to use it like:

  • What is a function in Python
  • Creating a function in python
  • Calling a function in python
  • Arguments in python
  • Python arbitrary arguments
  • Python keyword arguments
  • Default parameter value
  • Passing a list as an argument in python
  • The return value in python
  • Return vs print in python
  • Function vs method in python
  • Yield vs return python
  • Function inside a function in python
  • Python nested function variable scoping