[Tutor] I'm puzzled

bob bgailer at alum.rpi.edu
Mon Jan 23 01:07:06 CET 2006


At 03:46 PM 1/22/2006, Vincent Zee wrote:
>Why will this little program crash when you enter the enter key?

Thank you for including the "traceback" message in your 2nd post.

Index error means you tried to reference an element of a sequence 
that is not there. a is the empty string when you just hit enter to 
the raw_input request. It therefore has no elements, so a[0] raises 
the exception.

To avoid this test first for len(a) > 0.

>while True:
>     a = raw_input('number? ')
>     if a.isdigit():
>         print 'isdigit'
>     elif a[0] == '-' and a[1:].isdigit():
>         print '- + isdigit'
>     elif a == 'q':
>         break
>     else:
>         print 'no digit'



More information about the Tutor mailing list