Skip to main content

Section 5.1 Introduction to Functions and Files

Subsection 5.1.1 Introduction to Functions

In Python, a function is a chunk of code that performs some operation that is meaningful for a person to think about as a whole unit, for example calculating a student’s GPA in a learning system or responding to the jump action in a video game. Once a function has been defined and you are satisfied that it does what it is supposed to do, you will start thinking about it in terms of the larger operation that it performs rather than the specific lines of code that make it work.
This breaking down of a task or problem is crucial to the successful implementation of any program of more than 50 or so lines (and plenty of smaller ones too). For example, the program that displays the Instagram landing page is made up of functions that:
And each of those is made up of functions as well. For example, the function that displays your friends’ posts is a for loop that calls a function to:
In this chapter you will learn about named functions, functions that can be referred to by name when you want to execute them.

Subsection 5.1.2 Introduction to Files

After exploring functions, we are also going to explore working with data outside of our program by reading and writing files. So far, the data we have used in this book have all been either coded right into the program, or have been entered by the user. In real life data often resides in files. For example, the images we worked with in the image processing unit ultimately live in files on your hard drive. Web pages, and word processing documents, and music are other examples of data that live in files. In the second half of this chapter we will introduce the Python concepts necessary to use data from files in our programs.
For our purposes, we will assume that our data files are text files, that is, files filled with characters. The Python programs that you write are stored as text files. We can create these files in any of a number of ways. For example, we could use a text editor to type in and save the data. We could also download the data from a website and then save it in a file. Regardless of how the file is created, Python will allow us to manipulate the contents.

Subsection 5.1.3 Learning Goals

Subsection 5.1.4 Objectives

At the end of this chapter, you should be able to:,
You have attempted of activities on this page.