In this Python lesson, you will learn how to use assert. This will be proof that you are truly a Python pro.
Do you know what is the difference between a Python professional and a beginner?
The Python code of an experienced Python developer takes care of the correctness of the data.
Let’s see how to use assert for a simple data validation check.
I’ve used assert to take care of the data to be validated. In my case, I’m confident that the delivery date will not be earlier than the order date. I used assert to take care of the date validation check.
import datetime as dt order_date = dt.date(2022, 1, 1) delivery_date = dt.date(2022, 1, 1) assert order_date <= delivery_date, 'Delivery date can\'t be earlier than order date'
Even when both dates are the same (technically it is possible to order and deliver on the same date), nothing will happen. After you run the code in such a way that literally nothing will happen. It means that the code can move on because assert will not find the problem here.
And what will happen when assert finds a date validation error?
import datetime as dt
order_date = dt.date(2022, 6, 1)
delivery_date = dt.date(2022, 1, 1)
assert order_date <= delivery_date, 'Delivery date can\'t be earlier than order date'
Assert properly checked that the delivery date is earlier than the order date, which we agreed is not proper. That's how assert saved us from a wrong date being provided. Thanks to assert, we checked that our code was working wrongly.
This is how the use of assert found a bug in my Python code.