Truth or Dare? Python Assert Statements

This lesson is all about enforcing the truth. If you fudge the numbers or let AI run wild, your wonky code gets nuked. You will never, ever tell us that two plus two equals five.

I remember government „motivational speakers„ telling us as children that two plus two equals five because „synergy„. In Orwell’s 1984, English Socialism tortures Winston into believing 2+2=5. Fuzzy thought rots code. Let me show you how to wring it out.

This Soviet poster cheerleading the First Five-Year Plan gloats that „2 + 2 + workers’ enthusiasm = 5„. Their math was not only wrong; the stage was set for mass starvation within two years.

Get early access and the code

Go hard!

We can make the computer pinch us for a reality check using an assert statement in Python.

The next thing to do is something unholy: assert that two plus two equals five. assert 2 + 2 == 5 You will see red. Python is not amused.

Now we can try the Soviet quip 2 + 2 + „workers’ enthusiasm„ = 5. Computer says no, since you’re adding apples and oranges, i.e. the integer 4 and text string „enthusiasm„. Python calls bull: the claim is too nonsensical to even check.

We saw that Python refuses to add numbers and words. We’re going to train and tame AI with text anyway. So let’s wrap our numbers in quotes to tell the computer to treat them as text, or strings in geekspeak. Let’s try „2„ plus „2„ equals „4„.

Steps

  1. Open the project folder in VS Code.
  2. Open this file:
test_sanity.py
  1. Read the example assert statements.
  2. Run the file and watch what happens.
  3. Change one passing assert into a failing one.

Example:

assert 2 + 2 == 5
  1. Run the file again.
  2. Read the error message Python gives you.
  3. Fix the broken assert so the file runs again.
  4. For the homework, replace the ??? with your own answer:
assert "2" + "2" == ???
  1. Run the file one last time and make sure every assert passes.

Bibliography

  • Orwell, G. (1949). 1984. Secker & Warburg.

Ready to go hard?

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *

Ta strona wykorzystuje Akismet w celu ograniczenia spamu. Dowiedz się, jak przetwarzane są dane Twoich komentarzy.