Commit 2e43752c authored by Éamonn Murray's avatar Éamonn Murray

Add details on assert

parent 2e3948f8
......@@ -69,12 +69,14 @@ There are currently sections on the following topics:
- [Installing Additional Packages](python2/README.md#installing-additional-packages)
- [Virtual Environments](python2/README.md#virtual-environments)
- [Catching Exceptions](python2/README.md#catching-exceptions)
- [Assert](python2/README.md#assert)
- [Gotchas](python2/README.md#gotchas)
- [Jupyter](jupyter/README.md)
- [Installation](jupyter/README.md#installation)
- [Starting Jupyter](jupyter/README.md#starting-jupyter)
- [Shortcuts and Cell Types](jupyter/README.md#shortcuts-and-cell-types)
- [Full List of Shortcuts](jupyter/README.md#full-list-of-shortcuts)
- [Magics](jupyter/README.md#magics)
- [Numpy](numpy/README.md)
- [Installation](numpy/README.md#installation)
- [Basic Usage](numpy/README.md#basic-usage)
......
......@@ -409,6 +409,39 @@ else:
This is a modification of `ifelse.py` to give the user a helpful message if
they have failed to input an integer.
Assert
------
Another way to try to catch unexpected behaviour and return a useful error
message is using the
[`assert`](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement)
statement. This can also make your life easier when debugging your codes.
For example, if you wrote a function that at some positive real number as an
argument. An example of this is in `assert_inverse.py`:
```python
#!/usr/bin/env python3
import sys
def inverse(num):
"""Return the inverse of a number."""
# Use the "sys" module to find what the smallest float is. You could
# also just use the smallest number you think is realistic for whatever
# you're trying to do.
assert abs(num) > sys.float_info.min, \
"inverse() can only be called with non-zero argument"
return 1.0 / num
test_nums = 1, 1.1, 0.4, 0.1, 0.0
for num in test_nums:
print("The inverse of", num, "is", inverse(num))
```
It's good to get into the habit of including these where you can. Particularly
if you have functions that will break if arguments take certain values, even
if you're sure that will never happen.
Gotchas
-------
......
#!/usr/bin/env python3
import sys
def inverse(num):
"""Return the inverse of a number."""
# Use the "sys" module to find what the smallest float is. You could
# also just use the smallest number you think is realistic for whatever
# you're trying to do.
assert abs(num) > sys.float_info.min, \
"inverse() called with non-zero argument"
return 1.0 / num
test_nums = 1, 1.1, 0.4, 0.1, 0.0
for num in test_nums:
print("The inverse of", num, "is", inverse(num))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment