# Functions

Lesson Progress
0% Complete

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.

Syntax

``````python">def functionname( parameters ):

"Optional function_docstring"

function_suite

return [expression]``````

Note the indentation after the colon :

``````python">def sum(arg1, arg2):

total = arg1 + arg2

print "Sum of ", arg1, ' + ', arg2, ' = ', total

# Calling the function with paramenters/arguments

sum(10,50)``````

When the above code is executed, it produces the following result −

``python">Sum of  10 + 50  = 60``

### Pass by Reference or pass by value?

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.

For example −

``````python"># Function definition is here

def changeme( mylist ):

"This changes a passed list into this function"

mylist.append([1,2,3,4]);

print "Values inside the function: ", mylist

return``````
`# Now you can call changeme functionmylist = [10,20,30];changeme( mylist );print "Values outside the function: ", mylist`

Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −

`Values inside the function:  [10, 20, 30, [1, 2, 3, 4]]Values outside the function:  [10, 20, 30, [1, 2, 3, 4]]`

Here is another example where argument is being passed by reference and the reference is being overwritten inside the called function.

``````python"># Function definition is here

def changeme( mylist ):

"This changes a passed list into this function"

mylist = [1,2,3,4]; # This would assign new reference in mylist
print "Values inside the function: ", mylist
return
``````
`# Now you can call changeme functionmylist = [10,20,30];changeme( mylist );print "Values outside the function: ", mylist`

The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −

`Values inside the function:  [1, 2, 3, 4]Values outside the function:  [10, 20, 30]`

## Function Arguments

You can call a function by using the following types of formal arguments −

• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments

### Required arguments

Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.

In this example, ou definitely need to pass two argument, otherwise it gives a syntax error as follows −

`#Defining the functiondef student(name, age):    print "Name: ", name    print "Age: ", age# Calling the functionstudent('Jane', 25)student(25, 'Jane') #interchanging the argumentsstudent() # raises an error since two arguments are required`

Output: Notice the order matters here and error is raise if we supply no argurments

```Name:  Jane
Age:  25
Name:  25
Age:  Jane
Traceback (most recent call last):
File "functions.py", line 14, in <module>
student() # raises an error since two arguments are required
TypeError: student() takes exactly 2 arguments (0 given)
```

### Keyword arguments

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.

`def student(name, age):     print(“Student name is {} and age is {}”.format(name, age))# Calling the function with keyword arguments  student(name ='Jane', age =25)  student(age =25, name ='Jane') `

Output: Here the order does not matter

`Student name is Jane and age is 25Student name is Jane and age is 25`

### Default arguments

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.

``````python">def student(name, age=50):

print “Name: “, name

print “Age: “, age

#Function call

student(name = “Ruth”,age=25)

student(name= “John”)``````

Output: Notice default age is provided when no age is supplied

`Name:  RuthAge:  25Name:  JohnAge:  50`

## The Anonymous Functions

In Python, anonymous function means that a function is without a name.

Unlike normal functions which are defined by the standard keyword def, anonymous functions are defined with the keyword lambda.

Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.

`# Python code to illustrate cube of a number  using lambda function cube = lambda x: x*x*x print(cube(5)) `

Output

`125`

## The return Statement

The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.

``````python"># Function definition is here

def sum( arg1, arg2 ):

# Add both the parameters and return them."

total = arg1 + arg2

print "Inside the function : ", total

# Now you can call sum function

total = sum( 10, 20 );

print "Outside the function : ", total
``````

When the above code is executed, it produces the following result −

`Inside the function :  30Outside the function :  30`

## Scope of Variables

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python

## Global vs. Local variables

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example −

`total = 0; # This is global variable.`
``````python"># Function definition is here

def sum( arg1, arg2 ):

# Add both the parameters and return them."

total = arg1 + arg2; # Here total is local variable.

print "Inside the function local total : ", total

`# Now you can call sum functionsum( 10, 20 );print "Outside the function global total : ", total`
`Inside the function local total :  30Outside the function global total :  0`