Python Asserts

All of these assume basic use of the assert keyword:

assert <condition>, "<optional error message>"

✅ Python Assert — 20 Basic Assignments


1) Simple Assert

Write:

assert 5 > 2

Run and ensure no error is thrown.


2) Failing Assert

Write an assert that fails:

assert 2 > 5, "2 is not greater than 5"

Observe the AssertionError.


3) Assert on Even Number

Ask the user for a number and assert that it’s even.


4) Assert on Positive

Input a number from the user and assert that it’s positive.


5) Assert in Function

Write a function check_positive(n) that asserts n >= 0.


6) Assert String Length

Ask the user for a string and assert its length is ≥ 5.


7) Assert List Non-Empty

Create a list from user input and assert it’s not empty.


8) Assert Integer Input

Ask user for input, convert to int, and assert conversion succeeds (use try/except to loop until valid).


9) Assert Alphabet String

Ask user for a word and assert it contains only letters (str.isalpha()).


10) Assert Range 1–10

Ask user for a number and assert it’s between 1 and 10.


11) Assert True/False

Create a variable flag = True and assert that it’s True.


12) Assert on List Length

Given a list, assert its length is exactly 3.


13) Assert Sum

Given:

Assert that sum(nums) == 6.


14) Assert Dictionary Key

Create a dict and assert a specific key exists:


15) Assert Function Return

Write a function square(x) that returns x*x, then assert:


16) Assert No Zero Division

Ask two numbers and assert the second is not 0 before dividing.


17) Assert Float

Ask user input and assert it is a float value (use try/except + assert).


18) Assert Unique List

Ask user for 5 numbers and assert the list has no duplicates.


19) Assert File Exists

Ask user for a filename and assert that it exists on disk.

(Hint: use import os and os.path.exists())


20) Assert Valid Email

Ask user for a string and assert it contains '@' and '.'.


🧠 What You’re Practicing

Concept
Example

Basic assert

assert x > 0

Assert with message

assert cond, "error info"

Using assert in functions

check inputs

Validating user input

simple input guards

Combining assert + try/except

safe validation


📌 Example Starter Code

Positive Number with Assert

Even Number Using Assert


⚠️ Important Notes

✔ An assert will raise an AssertionError if the condition fails. ✔ Use clear messages to indicate why the assertion failed.


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated