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.

Tests for identifier validity. First symbol must be alphabetic and remaining symbols must<br />

be alphanumeric. This tester program only checks identifiers that are at least two<br />

characters in length.<br />

1 #!usr/bin/env python<br />

2<br />

3 import string<br />

4<br />

5 alphas = string.letters + '_'<br />

6 nums = string.digits<br />

7<br />

8 print 'Welcome to the Identifier Checker v1.0'<br />

9 print 'Testees must be at least 2 chars long.'<br />

10 myInput = raw_input('Identifier to test? ')<br />

11<br />

12 if len(myInput) > 1:<br />

13<br />

14 if myInput[0] not in alphas:<br />

15 print '''invalid: first symbol must be<br />

16 alphabetic'''<br />

17 else:<br />

18 for otherChar in myInput[1:]:<br />

19<br />

20 if otherChar not in alphas + nums:<br />

21 print '''invalid: remaining<br />

22 symbols must be alphanumeric'''<br />

23 break<br />

24 else:<br />

25 print "okay as an identifier"<br />

The example also shows use of the string concatenation operator ( + ) introduced later in this section.<br />

Running this script several times produces the following output:<br />

$ python idcheck.py<br />

Welcome to the Identifier Checker v1.0<br />

Testees must be at least 2 chars long.<br />

Identifier to test? counter<br />

okay as an identifier<br />

$<br />

$ python idcheck.py<br />

Welcome to the Identifier Checker v1.0<br />

Testees must be at least 2 chars long.<br />

Identifier to test? 3d_effects<br />

invalid: first symbol must be alphabetic<br />

Let us take apart the application line by line.<br />

Lines 36<br />

Import the string module and use some of the predefined strings to put together valid alphabetic and

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

Saved successfully!

Ooh no, something went wrong!