possible bug in while loop test
MRAB
python at mrabarnett.plus.com
Sat Sep 2 16:40:22 EDT 2017
On 2017-09-02 18:53, Charles Hixson wrote:
> python3 --version
> Python 3.5.3
>
> Running on Debian stretch
>
> In this code s is a string parameter
>
> while (j < k and \
> (s[j].isalnum()) or \
> (s[j] in seps and s[j+1].isalnum()) ):
> j = j + 1
> print ("i = {0}, j = {1}, k = {2}, len[s] = {3}". \
> format(i, j, k, len(s) ) )
>
> Yields the result:
>
> i = 25, j = 27, k = 31, len[s] = 32
> i = 25, j = 28, k = 31, len[s] = 32
> i = 25, j = 29, k = 31, len[s] = 32
> i = 25, j = 30, k = 31, len[s] = 32
> i = 25, j = 31, k = 31, len[s] = 32
> Traceback (most recent call last):
> File "parse1.py", line 40, in <module>
> print (parse1("The gostack distimms the doshes."))
> File "parse1.py", line 21, in parse1
> (s[j] in seps and s[j+1].isalnum()) ):
> IndexError: string index out of range
>
> I hesitate to report this, because I've been wrong so often, but it
> looks to me like the last iteration should not have happened since j is
> not less than k.
>
The last iteration happened because j < k when you tested the while
loop's condition.
You then added 1 to j before printing out j and k. At this print, j >= k.
More information about the Python-list
mailing list