Debugging - Jupyter Notebook

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Debugging

It is very common to make mistakes while programming in any language. Fortunately, python is able to
recognize lots of types of mistakes and tell us what the problem is. The process of identifying and fixing
errors, or bugs, in your code is called debugging. It is very important to learn to debug your code, no matter
how much experience you have programming you will inevitably make a mistake, you must learn to
efficiently identify and fix your mistakes.

Let's go through a few examples

1. Run some code that doesn't work


2. Look at python's output from our mistakes
3. Identify the problem
4. Fix the problem

In [1]:  my_dict = {var1: 2, "var2": 16}

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[1], line 1
----> 1 my_dict = {var1: 2, "var2": 16}

NameError: name 'var1' is not defined

In [2]:  for i in range(6)


print(i)

Cell In[2], line 1


for i in range(6)
^
SyntaxError: expected ':'

In [3]:  array = [1,2,3,4,5]


for j in array:
print(array[j])

2
3
4
5

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[3], line 3
1 array = [1,2,3,4,5]
2 for j in array:
----> 3 print(array[j])

IndexError: list index out of range


In [6]:  if 5=4:
print('true')
else:
print('false')

Cell In[6], line 1


if 5=4:
^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

In [5]:  class MyClass:


def __init__(self,attr1val,attr2val):
self.attr1 = attr1val
attr2 = attr2val
print('attr2 is equal to',attr2)

myobj = MyClass(5,6)

print('attr1 is equal to', myobj.attr1)
myobj.attr2

attr2 is equal to 6
attr1 is equal to 5

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[5], line 10
7 myobj = MyClass(5,6)
9 print('attr1 is equal to', myobj.attr1)
---> 10 myobj.attr2

AttributeError: 'MyClass' object has no attribute 'attr2'

In [4]:  import numpy as np


nparray = np.array([1,2,3,4,5,6])
mean(nparray)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[4], line 3
1 import numpy as np
2 nparray = np.array([1,2,3,4,5,6])
----> 3 mean(nparray)

NameError: name 'mean' is not defined

In [ ]:  ​

You might also like