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

Exercise
          Try  incorporating  the  preceding  test  into  the  dice  program. While  you  are  at  it,  add  two  more  if
          statements:  one  that  prints  “Good  Throw!” if  the  throw  is  higher  than  10  and  one  that  prints
          “Unlucky!” if the throw is less than 4. Try  your  program  out. If you get stuck, you can look at the
          solution in the file 3_3_double_dice_solution.py.
          Else
          In the preceding example, you will see that some of the possible throws can be followed by more than
          one message. Any of the if lines could print an extra message if the condition is true. Sometimes you
          want a slightly different type of logic, so that if the condition is true, you do one thing and otherwise
          you do another. In Python, you use else to accomplish this:
















             In this case, only one of the two messages will ever be printed.
             Another variation on this is elif,  which  is  short  for else if. Thus, we could expand the previous
          example so that there are three mutually exclusive clauses, like this:




















          While
          Another  command  for  looping  is while,  which  works  a  little  differently  than for.  The  command
          while looks a bit like an if command in that it is immediately followed by a condition. In this case,
          the condition is for staying in the loop. In other words, the code inside the loop will be executed until
          the condition is no longer true. This means that you have to be careful to ensure that the condition will
          at some point be false; otherwise, the loop will continue forever and your program will appear to have
          hung.
             To illustrate the use of while, the dice program has been modified so that it just keeps on rolling

          until a double 6 is rolled:
   34   35   36   37   38   39   40   41   42   43   44