Thursday, 23 September 2021

Python: assert statements

‘assert’ statements are used to validate the input before processing.

 

Example

assert principal > 1 – Assertion error thrown when principal is <= 1.

assert time > 1 and time < 100 – Assertion error is throw, when the time is <= 1 and >= 100

 

Find the below working application.

 

assert_stmt_demo.py

import traceback

def interest_calc(principal, time, rateOfIntrest):
    assert principal > 1
    assert time > 1 and time < 100
    assert rateOfIntrest > 1 and rateOfIntrest < 5

    return (principal * time * rateOfIntrest) / 1000

def demo(principal, time, rateOfIntrest):
    try:
        interest_calc(principal, time, rateOfIntrest)
    except AssertionError:
        traceback.print_exc()

demo(0, 10, 5)

print('\n\n')
demo(10, 1000, 5)


Output

Traceback (most recent call last):
  File "/Users/krishna/miscellaneous/assert_stmt_demo.py", line 12, in demo
    interest_calc(principal, time, rateOfIntrest)
  File "/Users/hkrishna/miscellaneous/assert_stmt_demo.py", line 4, in interest_calc
    assert principal > 1
AssertionError



Traceback (most recent call last):
  File "/Users/krishna/miscellaneous/assert_stmt_demo.py", line 12, in demo
    interest_calc(principal, time, rateOfIntrest)
  File "/Users/krishna/miscellaneous/assert_stmt_demo.py", line 5, in interest_calc
    assert time > 1 and time < 100
AssertionError



Previous                                                    Next                                                    Home

No comments:

Post a Comment