Showing posts with label assert. Show all posts
Showing posts with label assert. Show all posts

Saturday, November 19, 2016

Nice Way to Raise Exception - Assert

'assert' keyword in function is a nice way by which we can raise an exception. With using assert there is no humdrum of try-except, and we can still have a smooth code. Look at the example below -


import random
num=random.randint(1,50)
for i in range(1,50):
    assert num!=i,'Yes it is the '+str(i)+'th element'
    print i


Here , I have a condition in assert; if the condition is satisfied throughout the loop then I will have the exception. In this code suppose we have a num=12 then we will have the exception only when the value of i and num are same. Otherwise the loop will continue. So we'll get the value of i 1 to 11 and then exception and the program halts there.

You see assert is a small go through to avoid or create exception, but in bigger problems we need try and except to not only catch the exception but also if found redirect it.[ Next Topic]

Comical Assert:
assert - 'Hey! I don'tzz  wannaa do zzhissss, so I gonna stooop here if I encounterrr the problem ' 
you - "ok, boss!!"

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...