0

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?

anarchy
  • 3,709
  • 2
  • 16
  • 48
Staryellow
  • 31
  • 6

2 Answers2

1

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
CSEngiNerd
  • 199
  • 6
0

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")
ErnestBidouille
  • 1,071
  • 4
  • 16