Dark theme

Answers


The value we need is 77 not 122. The find function is great, but it quietly returns a -1 if it doesn't find what it is looking for. This is different from str.index() which does the same job, but breaks the code if it doesn't find what it is looking for. Not breaking the code is good, but ideally we should be testing for -1. Here's the working code that does this: test7.py.


The key take-home messages are:

  1. print is the coder's best friend.
  2. Decomposing a problem helps identify which bit of code is going wrong.

Print is so helpful, it is sometimes worth setting up a "turn on debugging" variable at the top of your code, and then making print statements turn on or off using this, then you can quickly switch on debugging using this:

debugging = True
# blah
# blah
# blah
if debugging: print ("Code run to here, value = ", value)
# blah
# blah
# blah
if debugging: print ("Code run to here, value now = ", value)

Turning it off by altering the variable at the top to debugging = False. Better still, you could set this up using sys.argv so that even after the code has been distributed to users, it is easy for them to turn on debugging and report issues to you. Here's some code that does that: test8.py. Try running it with:
python test8.py
and then
python test8.py True