Skip to the content

assert

Python · Unit 20: Testing and debugging

An assert is a check: you tell Python something that must be true and it checks it for you.

If it holds, the program keeps going as if nothing happened. It is how you make sure the code does what you think.

total = 120 + 30
assert total == 150
print("The total is", total)

Prints

The total is 150

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Complete it to check that the bill adds up to 100.

  3. 3. Multiple choice

    What happens when the condition of an assert holds?

  4. 4. Predict the output

    What does this code print?

  5. 5. Find the bug

    This program should print the average of the three grades, and the assert checks that it is 8. Which line has the error?

  6. 6. Complete the code

    Complete the message that should come out when the number is negative.

  7. 7. Predict the output

    What does this code print?

  8. 8. Put the lines in order

    Put the lines in order so the function checks the divisor and the program catches the error.

  9. 9. Multiple choice

    What is the assert in this function for?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →