Python Functions (with Examples)

Functions in Python are used when we need to execute some block of code multiple times. The block of statements written inside a function only gets executed when the function is called. For example:

def myFunction():
    print("Hey,")
    print("It is easy to code in Python")

myFunction()

The output is:

Hey,
It is easy to code in Python

A function in Python is basically a block of code that performs a specific task.

The def Keyword in Python | Python def function

The "def" keyword is used when we need to create or define a function in Python. The syntax of the def keyword in Python is:

def function_name(arg1, arg2, arg3, ..., argN):
   // definition of function

Here "function_name" refers to the name of the function, whereas "arg1," "arg2," and so on are the list of arguments.

Create a Function in Python

Create a Function in Python To create a function in Python, use the "def" keyword followed by the function name, then arguments separated by commas, all arguments enclosed within a round bracket, and then a colon. Now, starting from the next line and keeping the indentation, write the code that defines the function's task. For example:

def greet():
    print("Have a good day!")

Steps to Create a Function in Python

Call a function in Python

To call a function in Python, just write that function as a statement. Provide the argument(s), if any. For example:

greet()

because the function "greet()" doesn't take any arguments, I've only written the function. The value of "greet()" is basically equal to the block of code written inside this function. As a result, the following program is required:

def greet():
    print("Have a good day!")

greet()

prints:

Have a good day!

on the output console. Whenever we call a function in Python, all the statements written in that function will get executed.

What are arguments in a function?

Arguments are used in a function when we need to transfer information between the function call and definition. Or, in simple words, arguments are information passed to a function.

For example, if a function called add() takes two arguments, say x and y, and returns the addition of x and y, Therefore, here the transfer of information is taking place. Let's consider the following program:

def add(x, y):
    return x+y

print(add(10, 40))

The output is:

50

Here, the values 10 and 40 get transferred to x and y. After that, x + y is returned.Therefore, add (10, 40) is evaluated as 50.

Note: While defining the function, variables inside parentheses are parameters of the function. When the function is called, the values passed to it refer to the arguments of the function.

Function with No Parameters in Python

Functions with no parameters in Python are most often used to print some message to the user. For example, in an application that requires the user to create a password, the direction message can be displayed using the following function:

def toFollow():
    print("1. The password length should be 12 characters long")
    print("2. The password should be the combination of alphabets and numbers.")
    print("3. Try to create a random password, that doesn't match anything related to you")

toFollow()

Now, whenever you want to display the direction message while creating a password, just write toFollow() to execute all three lines of statements available in the toFollow()  function.

Python Function with a Single Argument

The following program demonstrates the function in Python with a single argument:

def square(x):
    return x*x

print("Enter a Number to Find its Square: ", end="")
num = int(input())

print("\nSquare =", square(num))

The snapshot given below shows the sample run, with user input 13:

python function with single argument

Note: The end= parameter skips insertion of an automatic newline using print().

In the above program, while writing the code square(num) inside the print() function, the function square() gets called, and the value of num gets initialized to x, the function's argument. And the value x*x is returned using the return keyword or statement. Therefore, square (13) gets evaluated as 169.

The following statement appears in the preceding program:

return x*x

can also be written as:

res = x*x
return res

Also, the above program can be written in this way:

def square(x):
    res = x*x
    print("\nSquare =", res)

print("Enter a Number to Find its Square: ", end="")
num = int(input())

square(num)

Function with Multiple Arguments in Python

The following program demonstrates the function in Python, with multiple arguments:

def large(x, y, z):
    if x > y:
        if y > z:
            return x
        else:
            if z > x:
                return z
            else:
                return x
    else:
        if y > z:
            return y
        else:
            return z

print("Enter any Three Numbers: ", end="")
a = int(input())
b = int(input())
c = int(input())

print("\nLargest =", large(a, b, c))

The sample run with user input of 10, 6, and 8 as three numbers is:

python function with multiple arguments

Note: At the time of calling a function, the number of arguments must match the number of arguments used when the function is defined.

Python Function: Arbitrary Arguments (*args)

In Python, functions with arbitrarily named arguments are also allowed. A function can be created with "arbitrary" arguments when we do not know the number of arguments that will be passed to the function.

The way to create a function with arbitrarily named arguments in Python is:

def functionName(*argumentName):
   // definition of function

The * before "argumentName" indicates that it is the Arbitrary arguments.

When arbitrary arguments are passed to a function, the function will receive a tuple of arguments. Therefore, the first argument can be accessed using argumentName[0], the second argument can be accessed using argumentName[1], and so on. For example:

def fresherearth(*args):
    print("Addition =", args[0] + args[1] + args[2] + args[3])

fresherearth(4, 32, 13, 430)

The output is:

Addition = 479

just like variables in Python. That is, there is no need to declare a variable before using it; instead, simply initialize a variable whenever and whatever the value you require. In a similar way, in the above program too, while defining a function named fresherearth(), I have not declared all the parameters. The only argument, *args, or whatever name you use, is used, and using the tuple like indexing, any number of arguments can be used while defining the function.

Python Function: Keyword Arguments (kwargs)

Arguments in the form of "key=value" pairs can also be sent to a function in Python. For example:

def fresherearth(schoolName, nickName, socialName):
    print("Nickname =", nickName)

fresherearth(schoolName="Felix", nickName="Finn", socialName="Ben")

The output is:

Nickname = Finn

Of course, the order of the arguments doesn't matter. For example, the above program can also be created in this way:

def fresherearth(schoolName, socialName, nickName):
    print("Nickname =", nickName)

fresherearth(nickName="Finn", schoolName="Felix", socialName="Ben")

The output will be identical to the previous one.

Arbitrary keyword arguments in Python (**kwargs)

Because there is only one asterisk (*) before the name of the parameter in the case of arbitrarily generated arguments. Therefore, in the case of arbitrarily chosen keyword arguments, there will be two asterisks (**) before the name of the parameter. For example:

def fresherearth(**kwargs):
    print("Nickname =", kwargs["nickName"])

fresherearth(schoolName="Felix", nickName="Finn", socialName="Ben")

Still, the output will be the same, i.e., Nickname = Finn.

Using the Default Parameter Value in a Python Function

Python also allows you to set the default value of a parameter in a function. So that, if no parameter is passed to the function, the default value will be used. For example:

def myfun(val = 3):
    print("The value is:", val)

myfun(1)
myfun(2)
myfun()
myfun(4)

The output is:

The value is: 1
The value is: 2
The value is: 3
The value is: 4

Passing an iterable as an argument to a function in Python

We can also pass an iterable, such as a list, tuple, etc., as an argument to a function in Python. For example:

def myFunction(x):
    print(x)

myList = [1, 2, 3, 4, 5]
myTuple = (6, 7, 8, 9)
mySet = {10, 11, 12, 13, 14, 15}

myFunction(myList)
myFunction(myTuple)
myFunction(mySet)

The output is:

[1, 2, 3, 4, 5]
(6, 7, 8, 9)
{10, 11, 12, 13, 14, 15}

Therefore, we can pass multiple values, with a single variable, to a function by using an iterable. For example:

def cube(x):
    for val in x:
        print("Cube of", val, "=", val*val*val)

myList = [1, 2, 3, 4, 5]
cube(myList)

The output is:

Cube of 1 = 1
Cube of 2 = 8
Cube of 3 = 27
Cube of 4 = 64
Cube of 5 = 125

Recommended Keywords Related to Function in Python

Python Online Test


« Previous Tutorial Next Tutorial »