Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

function
python
user-defined

How to write a function in Python

Educative Answers Team

User defined functions

In Python developers have the option of defining their own functions called user-defined functions. These functions can be written such that they would perform the required task once they’re called.

A function is a block of reusable code that is written in order to perform a specific task. Functions take the required information to perform a task as the input parameter(s), perform the required operations on these parameters, and then they return the final answer.

Syntax

Now let’s discuss the method to write a user-defined function below:

Example

Let’s take a look at an example now.

def Examplefunc(str): #function that outputs the str parameter
  print "The value is", str 
  #no return statement needed in this function

def Multiply(x,y): #function that computes the product of x and y 
  return x*y #returning the product of x and y

#Calling the functions
Examplefunc(9) #9 passed as the parameter)
answer = Multiply(4,2) #4 and 2 passed as the parameters
print "The product of x and y is:",answer

The function Examplefunc above takes a variable str as parameter and then prints this value. Since it only prints the value there is no need for a return command.

The function Multiply takes two parameters x and y as parameters. It then computes the product and uses the return statement to return back the answer.

Calling a function

In line 9 and line 10 we are executing the functions by simply calling them and passing the parameters to them. Since Multiply function returns a value we store it in the variable answer before printing it.

Advantages of user-defined functions

The advantages of using user-defined functions include:

  • Reusable code blocks so they only need to be written once, then they can be used multiple times.

  • Useful in writing common tasks to complex business logic.

  • Modification as per requirement so there is no need to write separate code for different scenarios in the program.

  • Project can be divided into functions, leading to compact and well-defined code.

RELATED TAGS

function
python
user-defined
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring