+ 4
Can someone tell me why and how assertions are used in Python?
4 ответов
+ 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.
+ 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.
+ 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.
0
why my output different to online output my output addition some errors of line. etc