read the digits of a positive or negative number PYTHON

Question:

I have this code that prints the digits of a positive number but when I add a negative number it comes out error is not a number,

dato_entrada=input("INTRODUZCA UN NÚMERO: ")

if dato_entrada.isdigit():
    dato_entrada=int(dato_entrada)
    if dato_entrada < 0:
        dato_entrada= (dato_entrada * -1)
        cont = 0
        cont += 1
    else:
        aux_number = dato_entrada
        cont=0
        while aux_number != 0:
            aux_number= dato_entrada // 10
            dato_entrada=dato_entrada // 10
            cont += 1

        print(f"El número  tiene {cont} dígitos" )


else:
    print("El dato introducido no es un numero") 

I need to read any number, I need help?

Asked By: Staryellow

||

Answers:

isdigit() definition:

(method) isdigit: (self: Self@str) -> bool
Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

- is not a digit, that’s why it is failing. You can check if it is a real number with this for example:

try:
    dato_entrada = int(dato_entrada)
    ... # your code
except ValueError:
    print("El dato introducido no es un numero")

or this:

try:
    dato_entrada = int(dato_entrada)
except ValueError:
    dato_entrada = None
if dato_entrada:
    ... # your code
else:
    print("El dato introducido no es un numero")
Answered By: ErnestBidouille

isdigit() will return false if there is a ‘.’ or ‘-‘ in the string. If you know that you will always have integers you could check the first char of the string for ‘-‘ at the start of the string.

check_string = data_entrada
if check_string[0] == '-':
    check_string = check_string[1:]
if check_string.isdigit():
    # add your code, but replace data_entrada with check_string
Answered By: CSEngiNerd
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.