Sunday, May 6, 2018

Python debug in Jupyter notebook

This week, we will talk about how to debug in the jupyter notebook. From this week, I will also try to use Python3 as much as possible in my code. You can find the notebook at Qingkai's Github
Let's start by showing you some examples:

Activate debugger after we run the code

The first example is after we have an error occurred, for example, we have a function that squares the input number, but:
def square_number(x):
    
    sq = x**2
    sq += x
    
    return sq
square_number('10')
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-2-e429f5113bd2> in <module>()
----> 1 square_number('10')


<ipython-input-1-822cf3bc7b4e> in square_number(x)
      1 def square_number(x):
      2 
----> 3     sq = x**2
      4     sq += x
      5 


TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
After we have this error, we could activate the debugger by using the magic command - %debug, which will open an interactive debugger for you. You can type in commands in the debugger to get useful information. 
%debug
ipdb> h

Documented commands (type help <topic>):
========================================
EOF    cl         disable  interact  next    psource  rv         unt   
a      clear      display  j         p       q        s          until 
alias  commands   down     jump      pdef    quit     source     up    
args   condition  enable   l         pdoc    r        step       w     
b      cont       exit     list      pfile   restart  tbreak     whatis
break  continue   h        ll        pinfo   return   u          where 
bt     d          help     longlist  pinfo2  retval   unalias  
c      debug      ignore   n         pp      run      undisplay

Miscellaneous help topics:
==========================
exec  pdb

ipdb> p x
'10'
ipdb> type(x)
<class 'str'>
ipdb> p locals()
{'x': '10'}
ipdb> q
Here, the magic command '%debug' activate the interactive debugger pdb in the notebook, and you can type to see the value of the variables after the error occurs, like the ones I typed in above. There are some most frequent commands you can type in the pdb, like:
  • n(ext) line and run this one
  • c(ontinue) running until next breakpoint
  • p(rint) print varibles
  • l(ist) where you are
  • 'Enter' Repeat the previous command
  • s(tep) Step into a subroutine
  • r(eturn) Return out of a subroutine
  • h(elp) h
  • q(uit) the debugger
You can find more information about the pdb from here

Activate debugger before run the code

We could also turn on the debugger before we even run the code:
%pdb on
Automatic pdb calling has been turned ON
square_number('10')
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-5-e429f5113bd2> in <module>()
----> 1 square_number('10')


<ipython-input-1-822cf3bc7b4e> in square_number(x)
      1 def square_number(x):
      2 
----> 3     sq = x**2
      4     sq += x
      5 


TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

ipdb> p sq
*** NameError: name 'sq' is not defined
ipdb> p x
'10'
ipdb> c
# let's turn off the debugger
%pdb off
Automatic pdb calling has been turned OFF

Add a breakpoint

Sometimes we want to add breakpoints to the code
import pdb
def square_number(x):
    
    sq = x**2
    
    # we add a breakpoint here
    pdb.set_trace()
    
    sq += x
    
    return sq
square_number(3)
> <ipython-input-8-4d6192d84091>(8)square_number()
-> sq += x
(Pdb) l
  3         sq = x**2
  4     
  5         # we add a breakpoint here
  6         pdb.set_trace()
  7     
  8  ->     sq += x
  9     
 10         return sq
[EOF]
(Pdb) p x
3
(Pdb) p sq
9
(Pdb) c
12

12 comments:

  1. Replies
    1. Five weeks ago my boyfriend broke up with me. It all started when i went to summer camp i was trying to contact him but it was not going through. So when I came back from camp I saw him with a young lady kissing in his bed room, I was frustrated and it gave me a sleepless night. I thought he will come back to apologies but he didn't come for almost three week i was really hurt but i thank Dr.Azuka for all he did i met Dr.Azuka during my search at the internet i decided to contact him on his email dr.azukasolutionhome@gmail.com he brought my boyfriend back to me just within 48 hours i am really happy. What’s app contact : +44 7520 636249‬

      Delete
  2. Thanks for posting such a Useful information .You have done a great job.
    Python Training in Hyderabad

    ReplyDelete
  3. Very informative and impressive post you have written, this is quite interesting and i have went through it completely, an upgraded information is shared, keep sharing such valuable information. Top 10 import auto’s uit Duitsland

    ReplyDelete
  4. Am here to testify what this great spell caster done for me. i never believe in spell casting, until when i was was tempted to try it. i and my wife have been having a lot of problem living together, she will always not make me happy because she have fallen in love with another man outside our relationship, i tried my best to make sure that my wife leave this woman but the more i talk to her the more she makes me fell sad, so my marriage is now leading to divorce because she no longer gives me attention. so with all this pain and agony, i decided to contact this spell caster to see if things can work out between me and my wife again. this spell caster who was a man told me that my wife is really under a great spell that she have been charm by some magic, so he told me that he was going to make all things normal back. he did the spell on my wife and after 5 days my wife changed completely she even apologize with the way she treated me that she was not her self, i really thank this man his name is Dr ose he have bring back my wife back to me i want you all to contact him who are having any problem related to marriage issue and relationship problem he will solve it for you. his email is oseremenspelltemple@gmail.com he is a man and his great. wish you good time.
    He cast spells for different purposes like
    (1) If you want your ex back.
    (2) if you always have bad dream
    (3) You want to be promoted in your office.
    (4) You want women/men to run after you.
    (5) If you want a child.
    (6) You want to be rich.
    (7) You want to tie your husband/wife to be yours forever.
    (8) If you need financial assistance.
    (9) HIV/AIDS CURE
    (10) is the only answer to that your problem of winning the lottery

    Contact him today on oseremenspelltemple@gmail.com or whatsapp him on +2348136482342

    ReplyDelete
  5. My name is Tom cam!!! i am very grateful sharing this great testimonies with you all, The best thing that has ever happened in my life, is how i worn the Powerball lottery. I do believe that someday i will win the Powerball lottery. finally my dreams came through when i contacted Dr. OSE and tell him i needed the lottery winning special numbers cause i have come a long way spending money on ticket just to make sure i win. But i never knew that winning was so easy with the help of Dr. OSE, until the day i meant the spell caster testimony online, which a lot of people has talked about that he is very powerful and has great powers in casting lottery spell, so i decided to give it a try. I emailed Dr. OSE and he did a spell and gave me the winning lottery special numbers 62, and co-incidentally I have be playing this same number for the past 23years without any winning, But believe me when I play the special number 62 this time and the draws were out i was the mega winner because the special 62 matched all five white-ball numbers as well as the Powerball, in the April 4 drawing to win the $70 million jackpot prize...… Dr. OSE, truly you are the best, with Dr. OSE you can will millions of money through lottery. i am a living testimony and so very happy i meant him, and i will forever be grateful to him...… you can Email him for your own winning special lottery numbers now oseremenspelltemple@gmail.com OR WHATSAPP him +2348136482342

    ReplyDelete
  6. DR EMU WHO HELP PEOPLE IN ANY TYPE OF LOTTERY NUMBERS

    It is a very hard situation when playing the lottery and never won, or keep winning low fund not up to 100 bucks, i have been a victim of such a tough life, the biggest fund i have ever won was 100 bucks, and i have been playing lottery for almost 12 years now, things suddenly change the moment i came across a secret online, a testimony of a spell caster called DR EMU, who help people in any type of lottery numbers, i was not easily convinced, but i decided to give try, now i am a proud lottery winner with the help of DR EMU, i won $1,000.0000.00 and i am making this known to every one out there who have been trying all day to win the lottery, believe me this is the only way to win the lottery.

    Contact him via email Emutemple@gmail.com
    What's app +2347012841542
    Https://emutemple.wordpress.com/

    ReplyDelete
  7. This post is so helpfull and informative.keep updating with more information...
    Python Programming
    Python Development

    ReplyDelete
  8. I'm Melvin Martins. from the United States. I started playing lottery games 7 years ago and I have never won big. I went online to seek help on how I can win big in my lottery games and I saw some nice reviews about Dr John who has made different people huge winners in their lottery games with his prayers. I gave it a try and I contacted Dr John who told me how and what to do before I can become a big lotto winner and I accepted. He made special prayers for me at his temple and gave me the required numbers to play the lotto game and when I played it, I won a massive $235.4 million POWERBALL jackpot. I was so happy and I chose to receive my winnings in a one-time, lump-sum payment of $160,038,447.27 at Florida Lottery Headquarters in Tallahassee and the balance was given to the store that I bought & played the game from. I would love other people to seek help from him and he can be contacted through WhatsApp/call/text via this number +1 (803) 820 2671 or you can email him on: Drjohnwinlotterspell@gmail.com .

    ReplyDelete