Doesn’t Python3 recognize 0 as int?

Asked

Viewed 231 times

3

The question says I need to receive user entries until a blank line is typed. After the user finishes the entry, I need to check in this entry if there are valid numbers and print them at the end of the program.

Follow an example of input given in the question:

1000
abacaxi
uva
15.19
-1
+1.45
123.456-
12.34+

And the expected exit:

Lista de Números Válidos Lidos = ['1000', '15.19', '-1', '+1.45']

That is, words and numbers ending with "-" and "+" are not considered valid, but numbers beginning with "-" and "+" should be considered. So far, no problem.

I used the following logic: for each item the user entered, I check if the last character is integer. If it is, enter a new list named numerosValidos. If not, as is the case with strings and the numbers that end with signal, the program does nothing. It follows the code:

def encontraValidos(lista):
    numerosValidos = []
    if len(lista) == 0:
        print("Lista de Números Válidos Lidos = {}".format(lista))
    else:
        for item in lista:
            try:
                if int(item[-1]):
                    numerosValidos.append(item)
                else:
                    pass
            except ValueError:
                pass

    return numerosValidos

And I get the exit:

Lista de Números Válidos Lidos = ['15.19', '-1', '+1.45']

However, as was said in the example of the question, the entry "1000" should be on that list. Threshing the code, I realized that the "1000" does not enter the if int(item[-1]), but I can’t understand why.

Some help?

1 answer

5


Because zero is considered false.

Just do if x will perform what we call Truth value testing and in this test it was defined that the numerical value zero will be considered false¹ . Thus, if int('0') will be the same as if 0, not executing the block within the conditional.

It follows the same idea that the C language uses (and perhaps many others), which did not even have the boolean type and used 0 and 1 for the service, being 0 the equivalent of false and 1 the true.

Allied to this, its verification is flawed. It is not enough to just check if the last character is a number because in this case the string petunias42 or 12uva45 would be considered valid numerical values.

The best way to treat this is to try to generate an instance of float from the entry. If it is not a valid number the exception will be launched ValueError:

palavras = ['1000', 'abacaxi', 'uva', '15.19', '-1', '+1.45', '123.456-', '12.34+']
numeros = []

for palavra in palavras:
    try:
        float(palavra)
    except ValueError:
        continue

    numeros.append(palavra)

print(numeros)

(1): A PEP 285 which provides for the addition of the boolean type in Python not only indicates that 0 is considered false but suggests that the boolean is implemented as a subtype of int.

This PEP proposes the Introduction of a new built-in type, bool, with two constants, False and True. The bool type would be a Straightforward subtype (in C) of the int type, and the values False and True would behave like 0 and 1 in Most respects (for example, False==0 and True==1 would be true) except Repr() and str().

This can be confirmed within the language by doing:

>>> print(isinstance(True, int))
True

>>> print(isinstance(False, int))
True

>>> print(issubclass(bool, int))
True

Browser other questions tagged

You are not signed in. Login or sign up in order to post.