Assignment
1. How can we use the “assert” keyword in Python? Explain with Example.
The assert keyword is a debugging tool that allows you to check for expected
conditions in your code.
It works by evaluating an expression. If the expression is True, the code continues
without interruption.
If the expression is False, an Assertion Error is raised, indicating a potential
issue or unexpected behaviour.
Syntax:
assert expression, message
expression: The condition we want to check.
message (optional): A custom message to provide more context if the assertion
fails.
Examples:
Basic Assertion:
x = 10
assert x > 0, "x should be positive" # Passes
assert x == 5, "x should be 5” # Raises Assertion Error with the message
Checking Function Results:
def square(num):
return num * num
result = square (4)
assert result == 16, "Incorrect result from square function"
Asserting Dictionary Key Existence:
my_dict = {"name": "Alice", "age": 30}
key = "name"
assert key in my_dict, f"Key '{key}' “not found in dictionary”