I have the following code which the function should return the factorial of the number passed as a parameter.
The function should use assertions to check that the passed value is a positive integer. If not, the function will terminate with an AssertionError exception with the message "I used assertions to throw this exception."
def fact(number):
cont = 1
assert number >= 0
for i in range(1, number + 1):
cont *= i
return cont
assert number < 0, "He usado asertos para mostrar esta excepción"
if __name__ == "__main__":
print(fact(5))
The problem is that for the cases in which the inputs are positive, the program correctly returns the factorial result, but for the cases in which the inputs are negative, it does not return the corresponding message of the "assert". I also tried the following way but still the same error
def fact(number):
cont = 1
assert number >= 0
for i in range(1, number + 1):
cont *= i
return cont
assert number < 0
raise AssertionError("He usado asertos para mostrar esta excepción")
if __name__ == "__main__":
print(fact(5))
As mentioned in the comments, the one
assert
placed afterreturn
never gets executed:The code used
assert
should be as follows:The equivalent using
AssertionError
it would look like this:An assert is not a control structure, but a statement that has no relation to those that precede it or those that follow it. They have this general form:
It simply checks that the boolean expression is true. If it is false, the exception is generated
AssertionError
with the message indicated in quotes.Assertions are safeguards against cases that should never occur . That is, the programmer knows that, at that point in the code and if there are no bugs, the Boolean expression will always be true and therefore the exception is never generated. Let's say that the assertion is set "just in case" (in case the program really had a bug and the condition turns out to be false, so that in that case the program immediately breaks due to the exception instead of continuing with an erroneous value) .
So your function should be like this:
In any case, it's bad practice to use assertions for things like this example. Here we are verifying that a parameter received by a function is in the expected range, but if it is not, it is not something attributable to a bug that you have committed. Rather the fault lies with whoever called the function that passed an illegal value. The logical thing in this case is, instead of using assertions, to use a conditional to verify the data, and if it is not correct, generate an exception
ValueError
. This is how Python library functions behave when they receive an invalid value.It would therefore be: