Introduction to Assert in Python
The following article provides an outline on Assert in Python. Asserts in python are special debugging statements which helps for flexible execution of the code. Moreover they are a form of raise-if statement, when a expression ends false then the assert statements will be raised. They act as a sophisticated form of sanity check for the code.
Syntax:
When a assert statement is faced then python execution evaluates the statement or the expression which is mentioned. When the statement becomes false then a Assertion Error exception is raised.
assert Expression[, Arguments]
The argument set act as the parameters for the Assertion error. Assertion Error exceptions are capable of trapped and griped like some other exception by means of the try-except statement, but when they are not being handled, they will end the program and create a traceback.
Why Python Assert?
- Help full in code debug.
- Help to find code bugs in a very short span of time.
- Allows checking parameter types and values.
- Allows to check invariants of data structure.
- Checking “can’t happen” situations.
- To ensure a function returns a reasonable outcome.
- Failed assertions can be reported by rewriting them before the failed instance. So a introspection information message is dropped by the rewritten message.
Examples of Assert in Python
Given below are the examples of Assert in Python:
Example #1
Code:
def radix_sort(Input_List, base=10):
if Input_List == [ ]:
return
def Input_factory(numeral , base):
def Input(Input_List , index_value):
return ((Input_List[index_value]//(base**numeral)) % base)
return Input
greatest = max( Input_List )
proponent = 0
while base**proponent <= greatest:
Input_List = sort_count(Input_List, base - 1, Input_factory(proponent, base))
proponent = proponent + 1
return Input_List
def sort_count(Input_List , greatest , Input):
count = [0]*(greatest + 1)
for i in range(len( Input_List )):
count[Input(Input_List, i)] = count[Input(Input_List, i)] + 1
# to determine the last index_value for each of the element
count[0] = count[0] - 1
# zero-based index_valueing decrement
for i in range(1, greatest + 1):
count[i] = count[i] + count[ i - 1 ]
output_value = [None]*len(Input_List)
for i in range(len(Input_List) - 1, -1, -1):
output_value[count[Input(Input_List, i)]] = Input_List[i]
count[Input(Input_List, i)] = count[Input(Input_List, i)] - 1
return output_value
Input_List = input('Enter the list of (nonnegative) numbers: ').split()
for element in Input_List:
element = int(element)
assert element > 0,"!!! Negative number is entered !!!"
Input_List = [ int(x) for x in Input_List ]
sorted_list = radix_sort(Input_List)
print( ' Radix oriented sorted output : ' , end='')
print(sorted_list)
Output:
Explanation:
- Radix sort allows the keyed in input to be sorted without comparing the elements.
- For achieving this a bucket is been generated. For elements with more than one digit involved the technique is applied for all the digits in the element. It is also termed as bucket sort.
- Here the assert process is achieved by below code block:
Code:
for element in Input_List:
element = int(element)
assert element > 0,"!!! Negative number is entered !!!"
- This assert check is used to verify whether any of the keyed in element are a negative value. When a negative value is found then the assertion error will be triggered stating !!!Negative number is entered !!!.
Example #2
Code:
def heap_sort(Order_value, number, i):
Greatest = i # Initialize Greatest as root
left= 2 * i + 1 # left = 2*i + 1
right= 2 * i + 2 # right = 2*i + 2
# to verify the left child of root is greater than the root
if left< number and Order_value[i] < Order_value[left]:
Greatest = left
# to verify the right child of root is greater than the root
if right < number and Order_value[Greatest] < Order_value[right]:
Greatest = right
# swap roots on neccesity
if Greatest != i:
Order_value[i],Order_value[Greatest] = Order_value[Greatest],Order_value[i] # swap
# Heapify the root.
heap_sort(Order_value, number, Greatest)
# main function for Order_value sorting
def heapSort(Order_value):
number = len(Order_value)
# max heap build process.
for i in range(number, -1, -1):
heap_sort(Order_value , number , i)
# extract of all the constituents in the given heap
for i in range(number-1, 0, -1):
Order_value[i], Order_value[0] = Order_value[0], Order_value[i] # swap
heap_sort(Order_value , i , 0)
# main section of the code
Order_value = input('Enter the list of (nonnegative) numbers: ').split()
assert len(Order_value) > 0,"!!! List is empty !!!"
for constituent in Order_value:
constituent = int(constituent)
assert constituent > 0,"!!! Negative number is entered !!!"
heapSort(Order_value)
number = len(Order_value)
print ( "Sorted Order_value value is" )
for i in range( number):
print (Order_value[i])
4.8 (7,888 ratings)
View Course
Output:
Explanation:
- Heap sort is also a type of selection sorting technique. It engages isolating the known input as non sorted and sorted elements. The algorithm looping process is carried out in such manner that for the unsorted region so that for every loop the biggest value would be pressed. Across each and every elements of the input list the above process will be iterated.
- A maximum heap is produced at the agreed input list. The final value is after that exchanged by means of the primary value constantly and as well the value range is relatively diminished by one. The process will be repeated until the value range decreases to one.
- Here the assert process is achieved by below code block:
Code:
assert len(Order_value) > 0,"!!! List is empty !!!"
for element in Input_List:
element = int(element)
assert element > 0,"!!! Negative number is entered !!!"
- Here two assert checks are maintained, One is to check whether the keyed in input list is empty or not and the other assert check is used to verify whether any of the keyed in element are a negative value.
- When a negative value is found then the assertion error will be triggered stating ” !!! Negative number is entered !!! ” . Similarly when a empty list is keyed in by the user then a assertion error stating ” !!! List is empty !!! ” is triggered.
Recommended Articles
This is a guide to Assert in Python. As like exception handling sections in python the assertions also make the language considerably stronger from code stability perspective. Here we discuss the introduction, why python assert? and examples. You may also have a look at the following articles to learn more –