Hacking Secret Ciphers with Python

(Ann) #1
Chapter 6 – The Caesar Cipher 77

The for loop is very good at looping over a string or list of values (we will learn about lists
later). This is different from the while loop, which loops as long as a certain condition is True.
A for statement has six parts:



  1. The for keyword.

  2. A variable name.

  3. The in keyword.

  4. A string value (or a variable
    containing a string value).

  5. A colon.

  6. A block of code.


Figure 6-1. The parts of a for loop statement.

Each time the program execution goes through the loop (that is, on each iteration through the
loop) the variable in the for statement takes on the value of the next character in the string.


For example, type the following into the interactive shell. Note that after you type the first line,
the >>> prompt will turn into ... (although in IDLE, it will just print three spaces) because the
shell is expecting a block of code after the for statement’s colon. In the interactive shell, the
block will end when you enter a blank line:





for letter in 'Howdy':
... print('The letter is ' + letter)





The letter is H
The letter is o
The letter is w
The letter is d
The letter is y








A while Loop Equivalent of a for Loop


The for loop is very similar to the while loop, but when you only need to iterate over
characters in a string, using a for loop is much less code to type. You can make a while loop
that acts the same way as a for loop by adding a little extra code:





i = 0
while i < len('Howdy'):
... letter = 'Howdy'[i]




Free download pdf