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.

A sequence was chosen; enter the sequence here as a string.<br />

Line 41<br />

Get the name of the iterative loop variable that the user wants to use.<br />

Lines 4344<br />

Generate the for loop, filling in all the customized details.<br />

Lines 4650<br />

Generate a while loop which iterates through a sequence.<br />

Lines 5254<br />

Generate a counting while loop.<br />

Lines 5661<br />

Output the generated source code as well as the resulting output from execution of the aforementioned<br />

generated code.<br />

Lines 6364<br />

Execute main() only if this module was invoked directly.<br />

To keep the size of this script to a manageable size, we had to trim all the comments and error checking<br />

from the original script. You can find both the original as well as an alternate version of this script on the<br />

book's Web site.<br />

The extended version includes extra features such as not requiring enclosing quotation marks for string<br />

input, default values for input data, and detection of invalid ranges and identifiers; it also does not<br />

permit built-in names or keywords as variable names.<br />

Conditionally Executing Code<br />

Our second example highlights the usefulness of function attributes introduced back in Chapter 11,<br />

"Functions", inspired by the example in PEP 232. Let us assume that you are a software QA developer<br />

encouraging your engineers to install either regression testers or regression instruction code into the<br />

main source but do not want the testing code mixed with the production code. You can tell your<br />

engineers to create a string representing the testing code. When your test framework executes, it<br />

checks to see if that function has defined a test body, and if so, (evaluates and) executes it. If not, it<br />

will skip and continue as normal.<br />

Example 14.2. Function Attributes (funcAttrs.py)

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

Saved successfully!

Ooh no, something went wrong!