Functions and Modules - Learn Python in One Day and Learn It Well (2015)

Learn Python in One Day and Learn It Well (2015)

Chapter 7: Functions and Modules

In our previous chapters, we’ve briefly mentioned functions and modules. In this chapter, let’s look at them in detail. To reiterate, all programming languages come with built-in codes that we can use to make our lives easier as programmers. These codes consist of pre-written classes, variables and functions for performing certain common tasks and are saved in files known as modules. Let’s first look at functions.

What are Functions?

Functions are simply pre-written codes that perform a certain task. For an analogy, think of the mathematical functions available in MS Excel. To add numbers, we can use the sum() function and type sum(A1:A5) instead of typing A1+A2+A3+A4+A5.

Depending on how the function is written, whether it is part of a class (a class is a concept in object-oriented programming which we will not cover in this book) and how you import it, we can call a function simply by typing the name of the function or by using the dot notation. Some functions require us to pass data in for them to perform their tasks. These data are known as parameters and we pass them to the function by enclosing their values in parenthesis ( ) separated by commas.

For instance, to use the print() function for displaying text on the screen, we call it by typing print(“Hello World”) where print is the name of the function and “Hello World” is the parameter.

On the other hand, to use the replace() function for manipulating text strings, we have to type “Hello World”.replace(“World”, “Universe”) where replace is the name of the function and “World” and “Universe” are the parameters. The string before the dot (i.e. “Hello World”) is the string that will be affected. Hence, “Hello World” will be changed to “Hello Universe”.

Defining Your Own Functions

We can define our own functions in Python and reuse them throughout the program. The syntax for defining a function is as follows:

def functionName(parameters):

code detailing what the function should do

return [expression]

There are two keywords here, def and return.

def tells the program that the indented code from the next line onwards is part of the function. return is the keyword that we use to return an answer from the function. There can be more than one return statements in a function. However, once the function executes a return statement, the function will exit. If your function does not need to return any value, you can omit the return statement. Alternatively, you can write return or return None.

Let us now define our first function. Suppose we want to determine if a given number is a prime number. Here’s how we can define the function using the modulus (%) operator we learned in Chapter 3 and the for loop and if statement we learned in Chapter 6.

def checkIfPrime (numberToCheck):

for x in range(2, numberToCheck):

if (numberToCheck%x == 0):

return False

return True

In the function above, lines 2 and 3 uses a for loop to divide the given parameter numberToCheck by all numbers from 2 to numberToCheck - 1 to determine if the remainder is zero. If the remainder is zero, numberToCheck is not a prime number. Line 4 will return False and the function will exit.

If by last iteration of the for loop, none of the division gives a remainder of zero, the function will reach Line 5, and return True. The function will then exit.

To use this function, we type checkIfPrime(13) and assign it to a variable like this

answer = checkIfPrime(13)

Here we are passing in 13 as the parameter. We can then print the answer by typing print(answer). We’ll get the output: True.

Variable Scope

An important concept to understand when defining a function is the concept of variable scope. Variables defined inside a function are treated differently from variables defined outside. There are two main differences.

Firstly, any variable declared inside a function is only accessible within the function. These are known as local variables. Any variable declared outside a function is known as a global variable and is accessible anywhere in the program.

To understand this, try the code below:

message1 = "Global Variable"

def myFunction():

print(“\nINSIDE THE FUNCTION”)

#Global variables are accessible inside a function

print (message1)

#Declaring a local variable

message2 = “Local Variable”

print (message2)

#Calling the function

myFunction()

print(“\nOUTSIDE THE FUNCTION”)

#Global variables are accessible outside function

print (message1)

#Local variables are NOT accessible outside function.

print (message2)

If you run the program, you will get the output below.

INSIDE THE FUNCTION

Global Variable

Local Variable

OUTSIDE THE FUNCTION

Global Variable

NameError: name 'message2' is not defined

Within the function, both the local and global variables are accessible. Outside the function, the local variable message2 is no longer accessible. We get a NameError when we try to access it outside the function.

The second concept to understand about variable scope is that if a local variable shares the same name as a global variable, any code inside the function is accessing the local variable. Any code outside is accessing the global variable. Try running the code below

message1 = "Global Variable (shares same name as a local variable)"

def myFunction():

message1 = "Local Variable (shares same name as a global variable)"

print(“\nINSIDE THE FUNCTION”)

print (message1)

# Calling the function

myFunction()

# Printing message1 OUTSIDE the function

print (“\nOUTSIDE THE FUNCTION”)

print (message1)

You’ll get the output as follows:

INSIDE THE FUNCTION

Local Variable (shares same name as a global variable)

OUTSIDE THE FUNCTION

Global Variable (shares same name as a local variable)

When we print message1 inside the function, it prints "Local Variable (shares same name as a global variable)" as it is printing the local variable. When we print it outside, it is accessing the global variable and hence prints "Global Variable (shares same name as a local variable)".

Importing Modules

Python comes with a large number of built-in functions. These functions are saved in files known as modules. To use the built-in codes in Python modules, we have to import them into our programs first. We do that by using the import keyword. There are three ways to do it.

The first way is to import the entire module by writing import moduleName.

For instance, to import the random module, we write import random.

To use the randrange() function in the random module, we write

random.randrange(1, 10).

If you find it too troublesome to write random each time you use the function, you can import the module by writing import random as r (where r is any name of your choice). Now to use the randrange() function, you simply write r.randrange(1, 10).

The third way to import modules is to import specific functions from the module by writing

from moduleName import name1[, name2[, ... nameN]].

For instance, to import the randrange() function from the random module, we write from random import randrange. If we want to import more than one functions, we separate them with a comma. To import the randrange() and randint() functions, we write from random import randrange, randint. To use the function now, we do not have to use the dot notation anymore. Just write randrange(1, 10).

Creating our Own Module

Besides importing built-in modules, we can also create our own modules. This is very useful if you have some functions that you want to reuse in other programming projects in future.

Creating a module is simple. Simply save the file with a .py extension and put it in the same folder as the Python file that you are going to import it from.

Suppose you want to use the checkIfPrime() function defined earlier in another Python script. Here’s how you do it. First save the code above as prime.py on your desktop. prime.py should have the following code.

def checkIfPrime (numberToCheck):

for x in range(2, numberToCheck):

if (numberToCheck%x == 0):

return False

return True

Next, create another Python file and name it useCheckIfPrime.py. Save it on your desktop as well. useCheckIfPrime.py should have the following code.

import prime

answer = prime.checkIfPrime(13)

print (answer)

Now run useCheckIfPrime.py. You should get the output True. Simple as that.

However, suppose you want to store prime.py and useCheckIfPrime.py in different folders. You are going to have to add some codes to useCheckIfPrime.py to tell the Python interpreter where to find the module.

Say you created a folder named ‘MyPythonModules’ in your C drive to store prime.py. You need to add the following code to the top of your useCheckIfPrime.py file (before the line import prime).

import sys

if 'C:\\MyPythonModules' not in sys.path:

sys.path.append('C:\\MyPythonModules')

sys.path refers to your Python’s system path. This is the list of directories that Python goes through to search for modules and files. The code above appends the folder ‘C:\MyPythonModules’ to your system path.

Now you can put prime.py in C:\MyPythonModules and checkIfPrime.py in any other folder of your choice.