/* jquery */ /* jquery accordion style*/ /* jquery init */

3 April 2013

Learn Python - For Loops

Sometimes we need a loop that executes a fixed number times. It's something you'll find in many other programming languages. A Python 'for' loop is what we'll need. Let's look at a typical statement.

Suppose we wanted to print out each character of a string. The code would look like this:

message = "Hello"
for ch in message:
  print ch

First, we define a variable called 'message' with a string value. Then we start the 'for' loop. The 'in' keyword instructs the loop to operate for a fixed number of times. In this case it's the number of characters in our message, namely five.

Each time the loop repeats it selects the next character from the string and assigns it to the variable 'ch'. So, the first time 'char' will be 'H', then next time it will be 'e', and so on.

Notice the colon ':' at the end of the line. Once again this marks the start of our indented loop code. There's only one line in this loop, a print statement. Run the code to see the loop print out all the characters in the message in sequence.

Now we've seen a simple 'for' loop, let's create a guessing game app that uses one.

A post from my Learn Python on the Raspberry Pi tutorial.

No comments: