ValueError: invalid literal for int () with base 10: '*'

0

I'm starting to program in Python, and my question is this:

my program does run, however when wanting to exit the loop, it throws me the following error:

def pcn_loop3():
    while True:
        x = int(input("Ingrese un numero ('*' para terminar): "))
        if x == '*':
            break
        elif x > 0:
            print("Numero positivo")
        elif x == 0:
            print("Igual a 0")
        else:
            print("Numero negativo")
  

Enter a number ('' to finish): 3
  Positive number
  Enter a number ('' to finish):
  Traceback (most recent call last):
    File "", line 1, in
      pcn_loop3 ()
    File "C: \ 01_Mis.Documents \ 01 My Programs in Python \ My projects \ kk.py", line 3, in pcn_loop3
      x = int (input ("Enter a number ('' to end):"))
  ValueError: invalid literal for int () with base 10: '*'

And I can not make it come out of the loop and if I remove int to the variable x it throws me the following error:

  

Enter a number ('*' to finish): 3
  Traceback (most recent call last):
    File "", line 1, in
      pcn_loop3 ()
    File "C: \ 01_Mis.Documents \ 01 My Programs in Python \ My projects \ kk.py", line 6, in pcn_loop3
      elif x > 0:
  TypeError: unorderable types: str () > int ()

How do I get it out of the infinite cycle, without it throwing me an error ...?

    
asked by Eduardo Mena 18.02.2017 в 19:46
source

1 answer

0

The problem occurs because you are casting a * to int, so it throws an exception that you are not considering or handling, so that it works you should change your code to this:

def pcn_loop3():
    while True:
        x = input("Ingrese un numero ('*' para terminar): ")
        if x == '*':
            break
        try:
            x = int(x)
            if x > 0:
                print("Numero positivo")
            elif x == 0:
                print("Igual a 0")
            else:
                print("Numero negativo")
        except ValueError:
            # Si no se puede castear entonces informo que lo ingresado no es un numero
            print("No es un numero")
    
answered by 18.02.2017 / 21:19
source