Hardware Reference
In-Depth Information
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 sim-
ple, 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 filling the kettle with
water, turning 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. When you tell someone to make a cup of tea
you assume they have already been shown how to fill the kettle and that you don't have to
tell them how to use a tap!
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.
Functions may take arguments (sometimes called parameters ), which are a way of supplying
data to them. Think of them as the raw materials into, or the controls that adjust, the func-
tion machine. Imagine a machine that makes different 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.
he print command that you used in the preceding code is a function in Python 3 that dis-
plays its parameter on the screen. The arguments to a function are often contained in brack-
ets after the function name.
choice is another function that you have been using, perhaps without realising it. Its argu-
ment is a list of items, and the processing it does is to select one at random. Its output is an
item from the list, which it returns.
If you find yourself writing the same code in multiple parts of a program, or using copy and
paste, you should think about putting the repeated code into your own function.
TIP
There are so many functions that if all of them were available at once, it would be over-
whelming to the programmer. Instead, Python contains only a few essential functions by
default, and others have to be imported from packages of functions before they can be used.
 
Search WWH ::




Custom Search