Hardware Reference
In-Depth Information
You can create your own functions, or you can use functions that are included in Python or
written by other people. To use a function, you call it by entering its name followed by () .
Figure 2-7:
Functions are
little machines
that process
inputs to
produce an
output.
Functions may take arguments (sometimes called parameters ), which are a way of supplying
data to them. hink of them as the raw materials into, or the controls that adjust, the func-
tion machine. Imagine a machine that makes diferent pasta shapes; its arguments might be
raw pasta and a setting that determines what shape it produces. Arguments can be a variable
(which may change as a program runs) or something hard-coded (written directly into the
program by the programmer and never changed) in the program itself.
You can think of the print command that you used in the preceding code as a function that
displays its parameter on the screen. he arguments to a function are contained in brackets
after the function name.
Structuring Your Programs
Functions are a way to structure programs. Computers and computer programs can quickly
become very complicated. The best way to deal with this is to break things down into simple,
manageable chunks. It's something we do in everyday life: If you ask someone to make you a
cup of tea, you don't give them a long list of instructions about illing the kettle with water, turn-
ing it on, waiting for it to boil, adding a tea bag to the teapot, and so on. We don't think about all
the details - after someone has been told how to make a cup of tea, they don't need to be told
all the steps each time. It's the equivalent of calling the makeTea() function - you need to
deine the steps only once. If you want to pass information like the number of sugars or milk to
add to the tea, you might use arguments - for example, to specify tea with three sugars and
milk, makeTea(3, True) .
If we broke every task down to the simplest steps every time, things would become unman-
ageable. Programming computers is just the same - tasks are broken down into manage-
able chunks. Knowing exactly how and where to break a program into chunks comes with
experience, but with this approach, it becomes possible to program a computer to make it
do just about anything.
Search WWH ::




Custom Search