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

This program will work. Try it out. However, it is a little bigger than it should be. We are having to
          repeat the following lines twice—once before the loop starts and once inside the loop:



             A  well-known  principle  in  programming  is  DRY  (Don’t  Repeat  Yourself).  Although  it’s  not  a

          concern in a little program like this, as programs get more complex, you need to avoid the situation
          where the same code is used in more than one place, which makes the programs difficult to maintain.
             We  can  use  the  command break  to  shorten  the  code  and  make  it  a  bit  “drier.” When  Python
          encounters the command break, it breaks out of the loop. Here is the program again, this time using
          break:




















             The condition for staying in the loop is permanently set to True. The loop will continue until it gets
          to break, which will only happen after throwing a double 6.
          Summary
          You  should  now  be  happy  to  play  with  IDLE,  trying  things  out  in  the  Python  Shell. I  strongly

          recommend  that  you  try  altering  some  of  the  examples  from  this  chapter,  changing  the  code  and
          seeing how that affects what the programs do.
             In the next chapter, we will move on past numbers to look at some of the other types of data you can
          work with in Python.
   35   36   37   38   39   40   41   42   43   44   45