Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Gauld A.Learning to program (Python)_1.pdf
Скачиваний:
23
Добавлен:
23.08.2013
Размер:
1.34 Mб
Скачать

Modular Programming

What will we cover?

What modules are about

Functions as modules

Using module files

Writing our own functions and modules

What's a Module?

The 4th element of programming is modular programming. In fact its not strictly necessary, and using what we've covered so far you can actually write some pretty impressive programs. However as the programs get bigger it becomes harder and harder to keep track of what's happening and where. We really need a way to abstract away some of the details so that we can think about the problems we are trying to solve rather than the minutae of how the computer works. To some extent that's what Python, BASIC etc already do for us with their built in capabilities - they prevent us from having to deal with the hardware of the computer, how to read the individual keys on the keyboard etc.

The role of modular programming is to allow the programmer to extend the built in capabilities of the language. It packages up bits of program into modules that we can 'plug in' to our programs. The first form of module was the subroutine which was a block of code that you could jump to (rather like the GOTO mentioned in the branching section) but when the block completed, it could jump back to wherever it was called from. That specific style of modularity is known as a procedure or function. In Python and some other languages the word module has taken on a specific meaning which we will look at shortly, but first let's consider functions a bit more closely.

Using Functions

Before considering how to create functions let's look at how we use the many, many functions that come with any programming language (often called the library).

We've already seen some functions in use and listed others in the operators section. Now we'll consider what these have in common and how we can use them in our programs.

The basic structure of a function is as follows:

aValue = someFunction(anArgument, another, etc...)

That is a variable takes on a value obtained by calling a function. The function can accept 0 or many arguments which it treats like internal variables. Functions can call other functions internally. Let's consider some examples in our various languages to see how this works:

BASIC: MID$(str$,n,m)

This prints the next m characters starting at the nth in str$. (Recall that names ending in '$' in BASIC signify a string)

time$ = "MORNING EVENING AFTERNOON" PRINT "Good";MID$(time$,8,8)

This prints out "Good EVENING".

54