Page 44 - Programming the Raspberry Pi Getting Started with Python
P. 44

Figure 4-2   A complex list





             You can combine what you know about lists with for loops and write a short program that creates a
          list and then prints out each element of the list on a separate line:








             Here’s the output of this program:







          Functions

          When  you  are  writing  small  programs  like  the  ones  we  have  been  writing  so  far,  they  only  really
          perform one function, so there is little need to break them up. It is fairly easy to see what they are
          trying  to  achieve. As  programs  get  larger,  however,  things  get  more  complicated  and  it  becomes
          necessary  to  break  up  your  programs  into  units  called functions.  When  we  get  even  further  into
          programming, we will look at better ways still of structuring our programs using classes and modules.
             Many of the things I have been referring to as commands are actually functions that are built into
          Python. Examples of this are range and print.
             The  biggest  problem  in  software  development  of  any  sort  is  managing  complexity. The  best
          programmers write software that is easy to look at and understand and requires very little in the way
          of  extra  explanation. Functions  are  a  key  tool  in  creating  easy-to-understand  programs  that  can  be
          changed without difficulty or risk of the whole thing falling into a crumpled mess.
             A  function  is  a  little  like  a  program  within  a  program. We can use it to wrap up a sequence of
          commands we want to do. A function that we define can be called from anywhere in our program and
          will contain its own variables and its own list of commands. When the commands have been run, we
          are returned to just after wherever it was in the code we called the function in the first place.
             As an example, let’s create a function that simply takes a string as an argument and adds the word
          please to the end of it. Load the following file—or even better, type it in to a new Editor window—and

          then run it to see what happens:
   39   40   41   42   43   44   45   46   47   48   49