Python Functions

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

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


The output is:

It is easy to code in Python

Function in Python, is basically a block of code, that performs a specific task.

The def Keyword in Python

The def keyword is used when we need to create or define a function in Python. The syntax of 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

To create a function in Python, use def keyword followed by the function name, then arguments separated by comma, all arguments enclosed within a round bracket, then a colon. Now from next line, keeping the indentation, write the code, that defines the task of the function. For example:

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

Steps to Create a Function in Python

  • Function block in Python, begins with the def keyword, followed by name of the function, and then parentheses (round opening and closing brackets)
  • The parameters/arguments should be placed inside these parentheses
  • The code block of function starts with a colon (:)
  • The return statement used to exit from a function
  • The return statement with no value, is same as return None

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:


because the function greet() doesn't takes any argument, therefore I've written only the function. The greet() is basically equal to the block of code, written inside this function. Therefore, the following program:

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



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, if I say, arguments are information passed to a function.

For example, if a function say 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:


Here the value 10 and 40 gets transferred to x and y. And then x+y gets 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 the function refers to the arguments of the function.

Function with No Parameters in Python

Function with no parameters in Python, most of the time is used to print some message to the user. For example, in an application that requires from user to create a password, then the direction message can be displayed using a 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")


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

Function with One (Single) Arguments in Python

The following program demonstrates the function in Python, with 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 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 using the return keyword or statement, the value x*x gets returned. Therefore square(13) gets evaluated as 169.

In above program, the following statement:

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())


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
            if z > x:
                return z
                return x
        if y > z:
            return y
            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 10, 6, and 8 as three numbers:

python function with multiple arguments

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

Python Function - Arbitrary Arguments (*args)

In Python, function with Arbitrary 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 Arbitrary arguments in Python, is:

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

Note - The * before argumentName makes the argumentName, Arbitrary arguments.

When Arbitrary arguments are used to a function, then 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 codescracker(*args):
    print("Addition =", args[0] + args[1] + args[2] + args[3])

codescracker(4, 32, 13, 430)

The output is:

Addition = 479

Just like, variables in Python. That is, in case of variables, there is no need to declare the variable, before its use, rather just initialize whenever and whatever the value you need, to a variable. In similar way, in above program too, while defining a function named codescracker(), I've not declared all the parameters. The only *args or whatever the 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 send to a function in Python. For example:

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

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

The output is:

Nickname = Finn

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

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

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

The output will be same as of previous one.

Arbitrary Keyword Arguments in Python (**kwargs)

Since in case of Arbitrary arguments, there is only one asterisk (*) before the name of parameter. Therefore, in case of Arbitrary keyword arguments, there will be two asterisk (**) before the name of parameter. For example:

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

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

Still the output will be same, that is, Nickname = Finn

Using Default Parameter Value in Python Function

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

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


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 list, tuple etc. as an argument to a function in Python. For example:

def myFunction(x):

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


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, 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]

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 »

Follow/Like Us on Facebook

Subscribe Us on YouTube