Practical Python: Try, Except, and Assert | by Soner Yıldırım | Towards Data Science

The dream of every software programmer is to write a program that runs smoothly. However, this is not usually the case at first. The execution of a code stops in case of an error.
Unexpected situations or conditions might cause errors. Python considers these situations as exceptions and raises different kinds of errors depending on the type of exception.
ValueError, TypeError, AttributeError, and SyntaxError are some examples for those exceptions. The good thing is that Python also provides ways to handle the exceptions.
Consider the following code that asks the user to input a number and prints the square of the number.
a = int(input("Please enter a number: "))print(f'{a} squared is {a*a}')
It works fine as long as the input is a number. However, if the user inputs a string, python will raise a ValueError:
We can implement a try-except block in our code to handle this exception better. For instance, we can return a simpler error message to the users or ask them for another input.
try:   a = int(input("Please enter a number: "))   print(f'{a} squared is {a*a}')except:   print("Wrong input type! You must enter a number!")
In the case above, the code informs the user about the error more clearly.
If an exception is raised due to the code in the try block, the execution continues with the statements in the except block. So, it is up to the programmer how to handle the exception.
The plain try-except block will catch any type of error. But, we can be more specific. For instance, we may be interested in only a particular type of error or want to handle different types of error differently.
The type of error can be specified with the except statement. Consider the following code that asks user for a number from a list. Then, it returns a name from a dictionary based on the input.
dict_a = {1:'Max', 2:'Ashley', 3:'John'}number = int(input(f'Pick a number from the list: {list(dict_a.keys())}'))
If the user enters a number that is not in the given list, we will get a KeyError. If the input is not a number, we will get a ValueError. We can handle both cases using two except statements.
try:   dict_a = {1:'Max', 2:'Ashley', 3:'John'}   number = int(input(f'Pick a number from the list:    {list(dict_a.keys())}'))   print(dict_a[number])except KeyError:   print(f'{number} is not in the list')except ValueError:   print('You must enter a number!')
Python also allows raising your own exception. It is kind of customizing the default exceptions. The raise keyword along with the error type is used to create your own exception.
try:   a = int(input("Please enter a number: "))   print(f'{a} squared is {a*a}')except:   raise ValueError("You must enter a number!")
Here is the error message in case of a non-number input.
ValueError: You must enter a number!
Let’s do another example that shows how to use try-except block in a function.
The avg_value function returns the average value of a list of numbers.
a = [1, 2, 3]def avg_value(lst):   avg = sum(lst) / len(lst)   return avgprint(avg_value(a))2
If we pass an empty list to this function, it will give a ZeroDivisionError because the length of an empty list is zero.
We can implement a try-except block in the function to handle this exception.
def avg_value(lst):   try:      avg = sum(lst) / len(lst)      return avg   except:      print('Warning: Empty list')      return 0
In case of empty lists, the function will print a warning and return 0.
a = []print(avg_value(a))Warning: Empty list0
The try and except blocks are used to handle exceptions. The assert is used to ensure the conditions are compatible with the requirements of a function.
If the assert is false, the function does not continue. Thus, the assert can be an example of defensive programming. The programmer is making sure that everything is as expected.
Let’s implement the assert in our avg_value function. We must ensure the list is not empty.
def avg_value(lst):   assert not len(lst) == 0, 'No values'   avg = sum(lst) / len(lst)   return avg
If the length of list is zero, the function immediately terminates. Otherwise, it continues until the end.
If the condition in the assert statement is false, an AssertionError will be raised:
a = []print(avg_value(a))AssertionError: No values
The assert is pretty useful to find bugs in the code. Thus, they can be used to support testing.
We have covered how try, except, and assert can be implemented in the code. They all come in handy in many cases because it is very likely to encounter situations that do not meet the expectations.
Try, except, and assert provides the programmer with more control and supervision over the code. They spot and handle exceptions very well.
Thank you for reading. Please let me know if you have any feedback.