Can someone tell me why and how assertions are used in Python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Can someone tell me why and how assertions are used in Python?

24th Jun 2017, 5:07 PM
Av Nish
Av Nish - avatar
4 Answers
+ 12
Assertions allow you to check the behavior of your program with incorrect incoming data. For example: you have a function which works with human age. If you input negative value of age Python doesn't give you an error and you'll work with wrong data. But you can raise an error by means of assert. def getage(age): assert (age>0), "Incorrect age" some other code... So if age is negative, it will be AssertionError: Incorrect age.
24th Jun 2017, 5:43 PM
Александр Громозонов
Александр Громозонов - avatar
+ 3
The best in this case is raising an Exception. The assert is used to check if the code is right during tests. You can create some tests sending values into your functions that you know the results and check them with assertions so you'll be sure that your code is right after future maintenance.
6th Aug 2017, 10:40 PM
Myke Albuquerque Pinto de Oliveira
Myke Albuquerque Pinto de Oliveira - avatar
+ 2
See in my codes, i got an example of it. But, is to check if you got reasonable values for your variable, such as, in the example code, you need to give a temperature in Kelvis to convert to Fahrenheit, since Kelvin scale cannot take negative numbers, you could put a ASSERT for when the temperature is negative you show this error.
2nd Jan 2018, 5:43 AM
Tetsuo Miyakawa
Tetsuo Miyakawa - avatar
0
why my output different to online output my output addition some errors of line. etc
4th Oct 2018, 4:10 AM
Solo
Solo - avatar