Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

How to declare a function in Python

Kainat Asif

A function is a collection of statements that are executed only when the function is called.

Declaration

Functions in Python are declared using the def keyword, as shown in the code snippet below:

def _funcName_ (_parameter(s)_, ...): 
   //function body
  • _funcName_: The name of the function.
  • _parameters(s)_: The input parameters that are passed to the function.
  • function body: The statements written within a function.

Return value

To return a value from a function, use the return keyword, as shown below:

return x
  • x: The return value of the function.

Note: When a function returns, the statements in the function after the return statement are not executed.

Calling a function

A function is called by writing its name, followed by its parameters enclosed in brackets.

_funcName_ ( _parameters(s) )

Examples

Example 1

Consider a simple example of a function that returns the sum of two numbers:

def sum(a, b):
  tempSum = a + b
  return tempSum

a = 2
b = 10

res = sum(a, b)
print "a + b =", res

Explanation

  • Lines 1-3: The sum function is declared and takes two input parameters, a and b. The sum function calculates the mathematical sum of a and b in line 2 and stores the sum in a local variable, tempSum. The tempSum variable is returned using the return keyword.
  • Line 18: The sum function is called in line 8 and is passed with a and b as input parameters. The return value of the sum function is then stored in the res variable.

Example 2

Consider an example of a function with no input parameters and no return value:

def noParam():
  print "This is a function with no parameters and no retrun value"

a = 2
b = 10

noParam()

RELATED TAGS

python

CONTRIBUTOR

Kainat Asif
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring