Section 10: Debugging, Raising Exceptions, and Doctest Flashcards
What are the steps for a Doctest?
Steps:
-
import doctest
in program - Call
doctest.testmod()
Ex:
```python
def add(x, y):
‘’’ (num, num) -> num Returns the sum of x and y
sum of x and y
»> add(2,2)
4
»> add(-2, 3)
1
»> add(1.2, 3.5)
4.7
‘’’
summation = x*y return summation
import doctest
doctest.testmod()
~~~
What does doctest.testmod()
do?What does
What does doctest.testmod()
do?
- Executes each line in docstring that begins with ‘
>>>
’ - Compare the results obtains with predicted valueIf they do not mach: print that test has failed and whyIf match: nothing is displayed
Define
Software bug:
<aside>
💡 Software bug: error or fault in program thatproduces incorrest or unexpected results
</aside>
- Debugging refers to the process of removing bugs or errors from a program
Types of Errors:
-
Stylistic Errors:Functionality of your code is not affected.
Hard to read - Syntax Errors:Problems with syntax
- Runtime Errors:Problems with code is executed (if there were no syntax errors)
- Logical Errors:No syntax or runtime errors, but not the required result
What happens once an exception is raised?
When exception is raised: Python prints traceback which contains lots useful info used to debug programs
What are Logical Errors?
- Refers to mistakes in the logic of the code → unexpected output
- Cannot automatically warm us
- Solve: break program down into simpler components
Two Main ways of debugging:
- The
print statement
(lazy man’s debugger) - The debugger
- Rubber DuckingExplaining the problem to someone else might help find a solution
Define
Exceptions:
- An exception is when an event which occurs during the execution of the program and disrupts the normal flow of the program’s instructions
- When asked to do something that does not make sense
IndexError, TypeError, ValueError
Exceptions:
IndexError
```python
s = ‘Monday’
c = s[10]
~~~
Trying to access the character that does not exists
Exception
TypeError
TypeError:
```python
s = ‘Monday’
for c in s:
if c > 0 …
~~~
Comparing a string to an integer
Exceptions
ValueError
ValueError
```python
def is_prime(n)
if n <=1:
~~~
Primality is not defined for numbers smaller than 2
How to raise an exception?
When want to communicate to a user that some error occurred during execution, decide deliberately stop execution of your code by raising exception
Generally:
```python
raise<some_exception>(message)
~~~</some_exception>
- message optional: highly recommended
- Type of exception:
NameError, TypeError, ValueError, IndexError, ZeroDivisionError