Python from Scratch - Functions and Modules

Welcome back to the Python from Scratch series. In the previous lesson, we learned how to use variables and control structures to store and manipulate data. Be sure to review it if you need a refresher!


Video Tutorial


Transcript

In today's tutorial, we're going to be looking at functions - what they are, how they work, and how to make your own. We're also going to be reviewing some of the built-in functions, and how to use them effectively. Finally, we're going to have a look at creating and importing modules.


Functions - Writing your Own

Functions are an important step to cover, when introducing additional complexity into your programming. If a variable is a named container for data, then a function is a named container for a block of code that can be executed on demand. This is useful if you have a program that executes a certain operation lots of times. Instead of copying and pasting the code to do that operation each section where it's needed, you can simply write one single function to do it for you.

A function is a named container for a block of code.

There are two types of functions: the ones that you write yourself and include in your code, and the ones that are included in Python natively, which carry out common procedures, such as converting an integer to a string, or finding the length of a string.

We're going to look at writing a simple function now, and demonstrate how it can be useful in the real world code. Then, we'll have a look at some of the most important built-in functions.

A simple Example

Let's imagine that we want to make a script for a shopping cart that takes the cost of all the items in your cart, and then adds them together to return a total cost. To write a function that would take two costs, add them up, and then print out the output, we might do something like:

To define the function, we need to use the 'def' keyword, and then the name of the function. Next, we type two parentheses (we'll come back to those later), and then a colon. After that, all of the code that we want to be encased within the function should be indented, just as with if, while and for loops.

To make the code in the function run, we type the name of the function, followed by the two parentheses again. If you run this code, you'll see it print out '35', which is the correct output.

Arguments

That's great, but at the moment, our functions are a bit rigid – everything about the function is hard-coded into them. For example, let' say we want to use the sumCart function somewhere else, in a different part of the program, but instead of adding cost1 and cost2 together, we want to add two other costs together that were held in different variables. We'd have to write a whole new function, even though that new function would be exactly the same as the current one, with the names of the variables swapped around - that hardly seems like an efficient solution.

To solve this issue, we use 'arguments', and that's what the parentheses are for. An argument is a way of passing data into a function when we don't know which variable or variables that data is going to be in. If that's confusing, let's take the example that I just referenced. We'll add two more costs: cost3 and cost4.

Now, we're going to add two arguments for the two items that we want to add up. Arguments are defined inside the parentheses, and each argument is given a name, with a comma separating each. An argument acts as a temporary reference to the data that you passed in while the function is running.

When we call the sumCart function, the two variables that we've passed in (cost1 and cost2) are put into the arguments item1 and item2. This always happens in the same order you define the arguments – in other words, the first variable you pass in is assigned to the first argument, the second to the second argument, and so on for as many arguments as your function takes.

What actually happens when the function is run is that those two arguments are converted into local variables and are assigned the values of the variables that you pass into the function when you call it – in this case the value of cost1 is put into the local variable item1, and the value of cost2 is put into the local variable item2. This means you can easily use them inside the function.

Another way you could look at it is, when you pass a variable as an argument, everywhere that that argument's name appears in the function, it is replaced with the variable you passed in. So, in this example, everywhere that item1 is written inside the function, it's replaced with cost1, and the same with item2 and cost2.

To prove that you can pass any numbers you want, if you run this code, you should now receive the sum of cost3 and cost4:

Argument Defaults

Note that a function can accept any number of arguments, but remember: when you call the function, you have to pass it the same number of arguments as you defined, otherwise you will receive an error. There is one way around this: you can define a default value for any argument, which is used in the cases when you don't supply a value.

Considering our current code, let's imagine that we want the second item to cost 5 if we don't give the function a different value. It's not a likely scenario, but it'll demonstrate the concept.

If we run this code, you'll see that, in the first call, the output is 20, which is indeed (cost1 + 5). This doesn't, however, affect the behavior when both arguments are supplied.

Returning values

There's one final feature of functions that we're going to review today: returning values. We've learned how to make a function that doesn't mind what inputs it takes, but what if we wanted to store the answer to 'totalCost' in a variable rather than print it out? Perhaps what we want to do is work out the cost of the first two items, and store it in one variable, then do the same with the second two items and store that answer in a second variable. With the current layout of our function, we couldn't do that in a readable and easy to understand way.

Just like the way we can pass arguments into a function so that we don't have to hard-code where the data is coming from, we can do the same with the output. I'll show you with an example - in our previous function, I'm going to replace the word 'print' with the word 'return':

Obviously, the function is no longer going to print out the answer for us – what it's going to do instead is pass back the value of the variable totalCost to wherever we called the function from. That way, we can use the answer in whatever context we need to. Now, in our previous program, that wouldn't be particularly useful, because we didn't specify anywhere to store it, so I've also changed the way we call the function.

We need to provide Python with a variable in which to store the answer, and then we're simply going to set that variable equal to our statement calling the function. When the function returns a value, that value will now be stored in the variable we specified.


Functions - Built-in

We've learned how to make our own functions, and how to use them, but there are some operations that are carried out often enough that Python has included them for use in any program. The way you call them is exactly the same as calling your own, but you don't have to define them first. We're going to have a brief look at the most important ones now, but be sure be have a look at the Python documentation because there are loads of useful functions that are available for use, which we don't have time to cover right now.

Refer to the Python documentation for a list of all built-in functions.

str()

First, let’s look at one of the most useful functions in Python: the string conversion function. There are many times in scripting when you have a variable that contains a number, or some other type of data, but you need to convert that value to a string in order to do something with it – normally to print it out onto the screen.

Let’s say we have a number in a variable, and that we want to print it out, with the message ‘The number is ‘ and then the number. If we write:

...then we’re going to encounter an error, because what you’re asking Python to do is to add a number and a string together – which doesn’t really make a whole lot of sense. What we need to do is to convert the number 10 into the string 10. If we do that, Python will understand that what we’re trying to do is not find a sum, but instead concatenate the two strings into one.

This is where the str function comes in. It accepts a value, and returns a string to represent it. In the case you pass it a number, it will simply return the number but in string format.

Now that we’ve encased the number in a string conversion function, the code runs perfectly. The str function doesn’t have to take a number though – it can also take other values, such as a Boolean:

The str() function finds the closest string match it can find for the value of ‘true’ and returns it, meaning that we can output it nicely.

len()

Another common task for strings is to be able to find the length of them, and, again, Python has a built in function for this. Let’s take the string ‘Hello World’ and try to find its length. To do this, we’re going to need the built-in len() function, which stands for length. All we need to do is pass it the string we want to use, and it will return the number of characters in it:

The len() function is capable of more than this, though. What it actually does is count the number of items in the object you give it – if you give it a string then that’s the number of characters, but you can also give it a list or a tuple, for example, and it will return the amount of items in that particular object.

int()

Moving on, often you are given a number like 10.6 or 3.896, which is not an integer, but you need an integer from them. The built-in function to convert to an integer is called int(), and it works fairly predictably. The function will return the integer conversion of that number. Note that this function does NOT round the input to the nearest integer – it very simply throws away anything after the decimal point and returns the number to you. So the input of 10.6 will return 10, NOT 11. Similarly, 3.25 would return 3.

The int function can also convert a string to an int data type. For example, given this, the output would still be 10:

However, be careful, because, when it is converting from a string to an integer, int() will NOT deal with decimal places. If you provide it:

Then it will throw an error, because the input wasn’t an integer, so it didn’t know how to handle it.

range()

Finally, we’re going to quickly look at the range() function; it comes up surprisingly often when you start doing more complex tasks in Python, and, while it might not seem massively useful at the moment, it’s worth having a look at and getting to know how it works. Range is a function that you use to create a list of numbers following a certain pattern. The simplest example is that perhaps you need a list containing all of the numbers 0 to 10. Instead of typing them out manually, you can use the range function to do it in one line.

Range accepts an integer as the parameter, and, in this case, we’ll pass it 11. The function thens starts at zero, and makes a list counting upwards until it hits one less than the number you put in. So here, if we put in 11, it will store the numbers 0 – 10 in the list numbers:

What if we wanted to print the numbers five to ten instead? Well, optionally, we can include another argument for the starting number, so this will print the numbers five to ten:

Lastly, what if we wanted to print only the odd numbers under 10? Well, range accepts a third value, which is the amount to go up each step. So if we start at 1, set the step to two and the upper limit to 11, we should end up with all the odd numbers under ten:

As a final note, any of these numbers can be negative as well, so if we wanted to count DOWN from 10 to 1 instead of up, we could set the step to be negative 1, the starting value to 10 and the limit to 0, like so:

Note that range will only deal with integers, so make sure that you don't give it any values that aren’t integers or you’ll throw an error.


Modules - Creating your Own

Alright, we’ve now covered functions; let’s move on to the second topic of today’s lesson: modules. If functions are groups of code, then modules are groups of functions. There’s more to them, but that’s a good way of thinking about them for now.

As we discussed earlier, you can’t make a complex program without sorting code into functions, and as your program continues to grow further, even they become unwieldy. You have to sort them into another hierarchical level. These are modules. So we can summarize them as a structural and organizational tool for our code.

Modules are quite easy to create. They are simply Python files, like your regular scripts. To create a module, write one or more functions in a text file, then save it with a .py extension. Let’s do that now with an example. Open up a new file your text editor or IDE, and make a function. I’m going to continue with the example of a shopping cart from earlier and make a function to calculate tax on the products.

Create a new file in your IDE or text editor and let's create a function for calculating tax on a product.

If we save this file with a .py extension in the same directory as our other script, we can use it as a module! It's important to give it a descriptive name so you know what it does when you come back later, so call this one finance.py


Importing modules

To use modules, we can use either the import or the from keyword. import is the simplest and most common, so let’s try that first. You then specify the name of the module, which is simply the filename, without the .py extension. For example, with our finance module in the same folder as our script, we could write:

...and we would have access to all the functions in the script. We can then call them just as we did before. You can also use the from keyword, which allows you to select specific functions from the library, if you know which ones you require beforehand. For a module that has hundreds of functions, this is recommended – it saves loading time on functions that aren’t even being used.

You can import several by separating their names with commas.

And you can even use the asterisk wildcard to import everything.

After importing the module, to use the functions contained within it, you use the module name, followed by a dot, and then the function name.

This should result in 105 when the script is run. A simple result, but it means you've got a working function!


Built-in Modules

There are plenty of built in modules, just as there are with built in functions. This is where Python really excels! It takes what’s called the “batteries included” approach.

Because Python has such an extensive range of built-in modules, there’s no way to cover them all in one lesson. Some are quite obscure, and there’s no point teaching a load of information you might never have a use for. Instead, let's cover several of the most useful ones.

  • random
  • math
  • os
  • datetime
  • urllib2

random

A good one to start with is random , because it’s easy to understand and useful in most scripts you’ll write. As you’d expect, this module lets you generate random numbers. For example, when using Python to create a website, they can be used in making your password database more secure or powering a random page feature. If we wanted a random integer, we can use the randint function, like so:

This will output either 1, 2, 3, 4 or 5. Randint accepts exactly two parameters: a lowest and a highest number. As you can see, it includes the highest number but goes from 1 above the lowest number. If you want a random floating point number, you can use the random function:

...which outputs a random number between 0 and 1, to a load of decimal places. If you want a larger number, you can multiply it. For example, a random number between 0 and 100:

The random module also has a function for choosing a random element from a set such as a list, called choice.

math

The math module provides access to mathematical constants and functions.

There are lots more functions in the module, but these are some of the most useful. You can find a full list here.

datetime

If you need to work with dates and times, then the datetime module is your friend. This one is a very useful one to know about for web development. If you're making an website with comments, or a blog, then you'll probably be displaying their age, or the time they were created.

Let's import the module as usual:

For convenience, you can also import the date and the time components separately, so you don't have to type as much later.

Let's have a look at some of the functions it provides:

There are some useful functions for converting dates into useable strings. strftime allows you to format a string based on special characters preceded by a percent symbol. %d represents day, for example.

os

The next module we're looking at is os, which provides functions that allow you to interface with the underlying operating system that Python is running on - be that Windows, Mac or Linux. We'll focus on the path submodule. It allows you to manipulate and find the properties of files and folders on the system, so it's the most useful for web development. You'll often need to manage files, for example user uploads.

These timestamps can be converted to useable strings using the datetime module - you can see how you can combine modules.

The last function in the os module we're going to look at is join. It combines two paths into one. You might be thinking: "Why can't I just concatenate the strings?", but it's not as simple as that. On Windows, the path delimiter is a backslash, on Mac and Linux it's a forward slash. This module alleviates problems like that and makes sure your Pythons scripts work on any system.

urllib2

To finish our tour of Python's standard library, we're going to have a brief look at urllib2. This module lets you interface with the web, so it's obviously quite relevant to us. The most useful function it provides is urlopen, which downloads a page.

You use it as follows:

You can obviously swap the URL string for any site. This will download the HTML content of the page. This won't return a string though, so we need to read the data to get that out:

This will return the first 100 characters of the HTML source of Nettuts+. Once you have this data, you can sort through it and extract the necessary bits that you require.


Final Tips

If your module is in a different directory than your script, it’s a bit trickier to import them. You have to create a file that tells Python the folder is a package. For example, if you have a folder, called subdirectory, in the same folder as your script, and then your module within that subdirectory, you would have to create a file called __init__.py in the same folder as the module. This file can be empty. Then, from your script, you'd import it:

%review it if you need a refresher!


Video Tutorial


Transcript

In today's tutorial, we're going to be looking at functions - what they are, how they work, and how to make your own. We're also going to be reviewing some of the built-in functions, and how to use them effectively. Finally, we're going to have a look at creating and importing modules.


Functions - Writing your Own

Functions are an important step to cover, when introducing additional complexity into your programming. If a variable is a named container for data, then a function is a named container for a block of code that can be executed on demand. This is useful if you have a program that executes a certain operation lots of times. Instead of copying and pasting the code to do that operation each section where it's needed, you can simply write one single function to do it for you.

A function is a named container for a block of code.

There are two types of functions: the ones that you write yourself and include in your code, and the ones that are included in Python natively, which carry out common procedures, such as converting an integer to a string, or finding the length of a string.

We're going to look at writing a simple function now, and demonstrate how it can be useful in the real world code. Then, we'll have a look at some of the most important built-in functions.

A simple Example

Let's imagine that we want to make a script for a shopping cart that takes the cost of all the items in your cart, and then adds them together to return a total cost. To write a function that would take two costs, add them up, and then print out the output, we might do something like:

To define the function, we need to use the 'def' keyword, and then the name of the function. Next, we type two parentheses (we'll come back to those later), and then a colon. After that, all of the code that we w

Tags:

Comments

Related Articles