Functions


A function is reusable code that can be called anywhere in your program.

Video: Functions Get PDF Get Exercises Quiz

Function definition

We use this syntax to define as function:

def function(parameters):
    instructions
    return value

The def keyword tells Python we have a piece of reusable code (A function). A program can have many functions.

Practical Example

We can call the function using function(parameters).

#!/usr/bin/python
 
def f(x):
    return(x*x)
 
print(f(3))

Output:

9

The function has one parameter, x. The return value is the value the function returns. Not all functions have to return something.

Parameters

 We can pass multiple variables:

#!/usr/bin/python
 
def f(x,y):
    print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
    print('x * y = ' + str(x*y))
 
f(3,2)

Output:

You called f(x,y) with the value x = 3 and y = 2
x * y = 6


23 thoughts on “Functions

  1. Sadia - February 10, 2016

    Hi Frank,
    please let me know why it is important to keep same name of list while passing to function. here is a simple function that receives list on call and then add. if i change the name of list “a” in method call then it gives me error. why it is not allowed to change. in java while passing arguments we can change name.

    def method(a):
    print(a+a)

    method(a=[1,2,4])

    1. Frank - February 10, 2016

      In your example you give the name in the function call. Try calling it with method([1,2,3])