Stepping through execution

What we want to do now is watch execution and see why we never exit this function's loop. Let's use next to move to the first line of the loop body:

(Pdb) next
> /Users/sixty_north/examples/palindrome.py(9)digits()
-> while x != 0:
(Pdb) next
> /Users/sixty_north/examples/palindrome.py(10)digits()
-> div, mod = divmod(x, 10)
(Pdb)

Now lets look at the values of some of our variables and try to decide what we expect to happen. We can examine values by using the print command:

(Pdb) print(digs)
[]
(Pdb) print x
1234

This looks correct. The digs list — which will contain the sequence of digits in the end — is empty, and x is what we passed in. We expect the divmod() function to return 123 and 4, so let's try that:

(Pdb) next
> /Users/sixty_north/examples/palindrome.py(11)digits()
-> digs.append(mod)
(Pdb) print div,mod
123 4

This looks correct: The divmod() function has clipped off the least significant digits from our number, and the next line puts that digit into our results list:

(Pdb) next
> /Users/sixty_north/examples/palindrome.py(12)digits()
-> x = mod

If we look at digs, we'll see that it now contains mod:

(Pdb) print digs
[4]

The next line will now update x so that we can continue clipping digits from it:

(Pdb) next
> /Users/sixty_north/examples/palindrome.py(9)digits()
-> while x != 0:

We see that execution goes back up to the while-loop as we expected. Let's look at x to make sure it has the right value:

(Pdb) print x
4

Wait a second! We expect x to hold the digits that aren't already in the results list. Instead, it contains only the digit in the results list. Clearly we've made a mistake in updating x!

If we look at our code, it quickly becomes apparent that we should have assigned div rather than mod to x. Let's exit PDB:

(Pdb) quit

Note that you may have to run quit a few times because of how PDB and unittest interact.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset