Raise exceptions and assertions in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Raise exceptions and assertions in Python

I would like to try to understand what this is for, it seems to me that it is a very abstract concept, I tried to investigate but I really don't understand anything, it seems to be very useful to handle the exceptions in Python but I would like to understand this in depth, I appreciate very much if you have easy to read or see resources to understand this topic, thank you very much.

31st Dec 2019, 6:01 AM
Lady Marcela Sanchez Moreno
Lady Marcela Sanchez Moreno - avatar
3 Answers
+ 9
Here’s a simple example so you can see where assertions might come in handy. I tried to give this some semblance of a real-world problem you might actually encounter in one of your programs. Suppose you were building an online store with Python. You’re working to add a discount coupon functionality to the system, and eventually you write the following apply_discount function: def apply_discount(product, discount): price = int(product['price'] * (1.0 - discount)) assert 0 <= price <= product['price'] return price Notice the assert statement in there? It will guarantee that, no matter what, discounted prices calculated by this function cannot be lower than $0 and they cannot be higher than the original price of the product.This speeds up debugging efforts considerably.and it will make your programs more maintainable in the long-run. And that, my friend is the power of assertions.
31st Dec 2019, 7:01 AM
Maninder $ingh
Maninder $ingh - avatar
+ 7
Why Not Just Use a Regular Exception? Now, you’re probably wondering why I didn’t just use an if-statement and an exception in the previous example… You see, the proper use of assertions is to inform developers about unrecoverable errors in a program. Assertions are not intended to signal expected error conditions, like a File-Not-Found error, where a user can take corrective actions or just try again. Assertions are meant to be internal self-checks for your program. They work by declaring some conditions as impossible in your code. If one of these conditions doesn’t hold, that means there’s a bug in the program. If your program is bug-free, these conditions will never occur. But if they do occur, the program will crash with an assertion error telling you exactly which “impossible” condition was triggered. This makes it much easier to track down and fix bugs in your programs. And I like anything that makes life easier—don’t you? For now, keep in mind that Python’s assert statement is a debugging aid.
31st Dec 2019, 7:04 AM
Maninder $ingh
Maninder $ingh - avatar