Python — Debugging, Strategies, PyCharm, Packages

Debugging — checklist

  1. Describe the problem. Keep asking questions. What is the for-loop doing? When is the function meant to print “You got it”? What assumptions are you making about the value of i?
  2. Reproduce the bug. Find the code path that causes it to happen continuously. Useful if the bug only happens sometimes.
  3. Play computer. Go through step by step as a computer would and evaluate each line.
  4. Watch for red underlines.
  5. Use print() function.
  6. Use a debugger / Python Tutor.
  7. Take a break.
  8. Ask a friend.
  9. Run the code often.
  10. Ask StackOverflow.

Strategies for breaking down a problem

Break it into small problems

# Check if the answer is correct
## Get follower count of each account
## Compare the follower count

Use Skitch

Visual annotation to sketch logic before coding.

Function-focused organisation

### blocks of functions
def my_function_1():
    # do this
    ...
 
def my_function_2():
    # do that
    ...
 
def my_function_3():
    # do them
    ...
 
### the actual action, using the functions
is_on = True
while is_on:
    my_function_1()
    if something == something:
        my_function_2()

PyCharm

Benefits:

  • spell check
  • PEP 8 standardisation
  • history
  • split-screen coding
  • structure view of your code (variables, functions) — like a Cmd-F
  • refactor → rename, rename all your functions at once
  • to-do list via # TODO

Packages

A package is many modules and code bundled together. Find them on pypi.com.

Installing from PyPI

# Pycharm preferences
# Project Interpreter
# Press + sign
# Search for the package
# Install
# import Package
 
# You can either see the source code by right-clicking the import code block and pressing Go to → Implementation
# OR
# Just read the documentation on Pypi.com

Useful packages I’ve used

  • PrettyTable — build tables.
  • Turtle — making art.
  • Colorgram — extract colour from an image.

See next