0% found this document useful (0 votes)
19 views1 page

Using Assert in Python for Debugging

The 'assert' keyword in Python is a debugging tool used to verify expected conditions in code. It evaluates an expression and continues execution if True, but raises an Assertion Error with an optional message if False. Examples include checking variable values, function results, and dictionary key existence.

Uploaded by

Mahesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views1 page

Using Assert in Python for Debugging

The 'assert' keyword in Python is a debugging tool used to verify expected conditions in code. It evaluates an expression and continues execution if True, but raises an Assertion Error with an optional message if False. Examples include checking variable values, function results, and dictionary key existence.

Uploaded by

Mahesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

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”

You might also like