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

This is an error because you are trying to define a variable that starts with a digit, which is not
          allowed.
             A  little  while  ago,  we  assigned  a  value  to  the  variable k.  We  can  see  what  value  it  has  by  just

          entering k, like so:



             Python has remembered the value of k, so we can now use it in other expressions. Going back to our
          original expression, we could enter the following:




          For Loops
          Arithmetic is all very well, but it does not make for a very exciting program. Therefore, in this section
          you will learn about looping, which means telling Python to perform a task a number of times rather
          than just once. In the following example, you will need to enter more than one line of Python. When
          you  press RETURN  and  go  to  the  second  line,  you  will  notice  that  Python  is  waiting. It  has  not
          immediately run what you have typed because it knows that you have not finished yet. The : character
          at the end of the line means that there is more to do.
             These extra tasks must each appear on an indented line. Therefore, in the following program, at the
          start of the second line you’ll press TAB once and then type print (x). To get this two-line program
          to actually run, press RETURN twice after the second line is entered.























             This  program  has  printed  out  the  numbers  between  1  and  9  rather  than  1  and  10. The range
          command has an exclusive end point—that it, it doesn’t include the last number in the range, but it
          does include the first.
             You can check this out by just taking the range bit of the program and asking it to show its values as
          a list, like this:




             Some of the punctuation here needs a little explaining. The parentheses are used to contain what are
          called parameters. In  this  case, range  has  two  parameters: from  (1)  and to  (10),  separated  by  a
          comma.
             The for  in  command  has  two  parts. After  the  word for  there  must  be  a  variable  name. This
          variable will be assigned a new value each time around the loop. Therefore, the first time it will be 1,
          the next time 2, and so on. After the word in, Python expects to see something that works out to be a
          list of items. In this case, this is a list of the numbers between 1 and 9.
             The print command also takes an argument that displays it in the Python Shell. Each time around
   30   31   32   33   34   35   36   37   38   39   40