To create a user defined function in Python, you need to follow these steps:

    • Use the def keyword to start the function definition.
    • Give a name to the function , followed by parentheses . You can also include some arguments or parameters inside the parentheses, separated by commas . These are the input values that the function will use.
    • End the first line with a colon (:).
    • Indent the next lines with four spaces or a tab. These are the statements that make up the function body . They define what the function does and how it does it.
    • Optionally , you can use the return keyword to return a value from the function. This is the output value that the function will give back when it is called. If you don’t use return, the function will return None by default.
    • To call the function, use its name followed by parentheses. You can also pass some values inside the parentheses, separated by commas. These are the arguments that will be assigned to the parameters of the function.

Here is an example of creating and calling a user defined function that adds two numbers:

def add_two_numbers(a, b): # define the function with two parameters

    result = a + b # calculate the sum

    return result # return the sum

x = 10 # assign a value to x

y = 20 # assign a value to y

z = add_two_numbers(x, y) # call the function with x and y as arguments

print(z) # print the return value

This will output 30.

Ask a doubt
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.