15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3.0<br />

arrrghhh<br />

--------------------------------------------------<br />

% loopmake.py<br />

Loop type? (For/While) w<br />

Data type? (Number/Sequence) s<br />

Enter sequence: [932, 'grail', 3.0, 'arrrghhh']<br />

Iterative variable name? eachIndex<br />

Enter sequence name? myList<br />

-------------------------------------------------<br />

Your custom-generated code:<br />

--------------------------------------------------<br />

eachIndex = 0<br />

myList = [932, 'grail', 3.0, 'arrrghhh']<br />

while eachIndex < len(myList):<br />

print myList[eachIndex]<br />

eachIndex = eachIndex + 1<br />

--------------------------------------------------<br />

Test execution of the code:<br />

--------------------------------------------------<br />

932<br />

grail<br />

3.0<br />

arrrghhh<br />

--------------------------------------------------<br />

Line-by-Line Explanation<br />

Lines 125<br />

In this first part of the script, we are setting up two global variables. The first is a static string consisting<br />

of a line of dashes (hence the name) and the second is a dictionary of the skeleton code we will need to<br />

use for the loops we are going to generate. The keys are "f" for a for loop, "s" for a while loop iterating<br />

through a sequence, and "n" for a counting while loop.<br />

Lines 2730<br />

Here we prompt the user for the type of loop he or she wants and what data types to use.<br />

Lines 3236<br />

Numbers have been chosen; they provide the starting, stopping, and incremental values. In this section<br />

of code, we are introduced to the input() BIF for the first time. As we shall see in Section 14.3.5, input<br />

() is similar to raw_input() in that it prompts the user for string input, but unlike raw_input(), input()<br />

also evaluates the input as a <strong>Python</strong> expression, rendering a <strong>Python</strong> object even if the user typed it in as<br />

a string.<br />

Lines 3839

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!