January 25, 2021 # Python – Functions

A function is a block of code that is executed as a unit. While there are many inbuilt functions in Python, you can also create your own function. This is known as user-defined functions. Once created, you can reuse a function at other parts of your program. Before you can use a function however, you must define it.

We cover the following:

#### 1. Defining a Function

To define a function, you must follow the rules listed below:

• Function definition begin with the keyword def, followed  by the function name, then open and close parentheses.
• Input parameters to the function are placed inside the braces
• After the braces, then you must add colon (:) before you start writing the function body
• The function body must be indented
• The last statement in a function is optionally a return statement.

For example, the function below calculates the sum of two numbers

```# Function to calculate the sum of two number

def calculatesum(a, b):
sum = a + b
return sum
```

After creating a function, you can use it by calling it.

#### 2. Calling a Function

To use a function, you must call it. If it requires parameters, then you must also provide the parameters. For example we can call the calculatesum function using the code below.

```# Function to calculate the sum of two number

def calculatesum(a, b):
sum = a + b
print("The sum of is " + str(sum))
return sum

# Calling the function calculatesum
calculatesum(4, 6)
```

So it is only when a function it called that the program executes the body of the function. One thing to note is that the function call must appear after the function definition (not before!)

#### 3. Pass by Value and by Reference

In Python, all arguments to a function are passed by reference. This means that the the same variable used in defining a function is reference when calling. So if you change the reference of a parameter within a function, this change is reflected in the calling function.

For example,

```def changelist(list1):
list1.append([10, 20, 30])
print("Changes made Inside the function: " + str(list1))
return

mylist = [1, 2, 3]
changelist(mylist)
print("Changes reflect in the calling function: " + str(mylist))
```

In the code above, when the function is called, the argument mylist is passed by reference. So inside the function, the same mylist is used. So the changes are made to the same mylist object.

The output of the code above would be:

```Changes made Inside the function: [1, 2, 3, [10, 20, 30]]
Changes reflect in the calling function: [1, 2, 3, [10, 20, 30]]```

#### 4. Arguments to Functions

You can pass arguments to a function by one of the following types of arguments:

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

Let’s now look at each one of these

#### 5. Required arguments

This are arguments you must pass to a function, otherwise you get an error. When calling a function foo(a, b, c) for example, then you must provide the three arguments. Also they must match the correct position of each of parameters in the function definition.

Let’s take an example, consider the printdata function below:

```# A function that just prints out the parameter
def printdata(data):
print(data)
return
```

If you are going to call this function, then you better provide the argument, data. Otherwise you get an error. This is required argument

#### 6. Keyword Arguments

In this case, when you call a function, you use name of the parameter to identify the argument being passed.

This means that you can either skip some argument or even place he argument out of other when calling. But the keywords have to match the name of the parameters used in the function definition. Take for example, the function below that takes name and age, then prints them out.

```def nameandage(name, age):
print("Your name is " + name)
print("Your age is " + str(age))

# Calling the function using keyword parameters
nameandage(name = "Jadon", age = 12)

#this is the same as
nameandage( age = 12, name = "Jadon")
```

#### 7. Default Arguments

In this case you may fail to provide a value for the argument during the function call. Then the argument just assumes a default value.

Take for example, the function below. In this case, a default argument is provided at the function definition. So if you omit this argument, the default is used.

```# default argument specified for age
def nameandage(name, age = 13):
print("Your name is " + name)
print("Your age is " + str(age))

# Calling the function without providing argument for age
nameandage(name = "Jadon")
```

#### 8. Variable-length arguments

This is a situation where you need to provide more arguments than are used during the function definition. To create a variable-length argument, you use the * symbol before the name of the argument. Let’s take an example of a name and a list of scores. While the name is provided, but we would not know how many items are in the scores

```def printdata(name, *scores):
print("Student name: " + name)
print("Scores are given below")
for score in scores:
print(score)

scores = [89, 84, 78, 90]

#the variable-length argument is provided
printdata("Solace", scores)

# the variable-length argument is omitted
printdata("Solace")
```

You can see that the variable-length argument can either be provided or omitted. When provided, it is used. But if it is omitted, then it is ignored. Try to run the above code to see the output.

#### 9. Global and Local Variables

Variables that are defined inside the body of a function are local variables. Therefore, they are available only inside the function block that defines it.

However, variables variables defined outside a function are global variables. This means they are available everywhere in the program. #### kindsonthegenius

View all posts by kindsonthegenius →
0 0 vote
Article Rating
Subscribe
Notify of 1 Comment
Inline Feedbacks
View all comments […] 14. Functions and Subroutines in Python […]