Avoiding "invalid literal for int()" exception

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • aine_canby@yahoo.com

    Avoiding "invalid literal for int()" exception

    >>v = raw_input("Ente r: ")
    Enter: kjjkj
    >>int(v)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: 'kjjkj'

    In my program I need to be able to enter char strings or int strings on
    the command line. Then I use an if-elif structure to establish which is
    which. For example -

    if uniList[0].lower() in ("e","exit") : # uniList stores a unicode
    string origionally taken from stdin
    return
    elif uniList[0].lower() in ("h","help") :
    verb.PrintVerb( )
    elif uniList[0].lower() in ("p","pass") :
    break
    elif int(uniList[0]) in range(0,10):
    verb.SetImporta nce(int(uniList[0]))
    break
    else:
    verb.AddNewVerb ((uniList[0])

    How could I avoid the ValueError exception if uniList[0] == "Åker"? I
    was thinking of having something like -

    formatError = False
    try:
    iVal = int(uniList[0])
    if iVal not in range range(0,10):
    formatError = True
    catch ValueError:
    iVal = -1

    if uniList[0].lower() in ("e","exit") : # uniList stores a unicode
    string origionally taken from stdin
    return
    elif uniList[0].lower() in ("h","help") :
    verb.PrintVerb( )
    elif uniList[0].lower() in ("p","pass") :
    break
    elif iVal != -1 and not formatError:
    verb.SetImporta nce(iVal)
    break
    elif not formatError:
    verb.VerbEntere d((uniList[0])
    else:
    print "Enter numbers between 0 and 10..."

    Is this the correct way to do this in your opinion? Sorry, I'm totally
    new to python and exceptions.

    Thanks,

    Aine.

  • Marc 'BlackJack' Rintsch

    #2
    Re: Avoiding &quot;invali d literal for int()&quot; exception

    In <1165832540.392 387.240550@j72g 2000cwa.googleg roups.com>, aine_canby
    wrote:
    elif uniList[0].lower() in ("p","pass") :
    break
    elif int(uniList[0]) in range(0,10):
    Replace this line with:

    elif uniList[0].isdigit() and 0 <= int(uniList[0]) < 10:
    verb.SetImporta nce(int(uniList[0]))
    break
    else:
    verb.AddNewVerb ((uniList[0])
    You may want to give `uniList[0]` a name before entering the
    ``if``/``elif`` construct to avoid accessing the first element over and
    over.

    Ciao,
    Marc 'BlackJack' Rintsch

    Comment

    • John Machin

      #3
      Re: Avoiding &quot;invali d literal for int()&quot; exception


      aine_canby@yaho o.com wrote:
      >v = raw_input("Ente r: ")
      Enter: kjjkj
      >int(v)
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      ValueError: invalid literal for int() with base 10: 'kjjkj'
      >
      In my program I need to be able to enter char strings or int strings on
      the command line. Then I use an if-elif structure to establish which is
      which. For example -
      >
      if uniList[0].lower() in ("e","exit") : # uniList stores a unicode
      string origionally taken from stdin
      return
      elif uniList[0].lower() in ("h","help") :
      verb.PrintVerb( )
      elif uniList[0].lower() in ("p","pass") :
      break
      elif int(uniList[0]) in range(0,10):
      verb.SetImporta nce(int(uniList[0]))
      break
      else:
      verb.AddNewVerb ((uniList[0])
      >
      How could I avoid the ValueError exception if uniList[0] == "Åker"?I
      was thinking of having something like -
      >
      formatError = False
      try:
      iVal = int(uniList[0])
      if iVal not in range range(0,10):
      formatError = True
      catch ValueError:
      Perhaps you meant
      except ValueError:
      :-)

      iVal = -1
      >
      Consider using uniList[0].isdigit() -- see


      HTH,
      John

      Comment

      • aine_canby@yahoo.com

        #4
        Re: Avoiding &quot;invali d literal for int()&quot; exception


        John Machin skrev:
        aine_canby@yaho o.com wrote:
        >>v = raw_input("Ente r: ")
        Enter: kjjkj
        >>int(v)
        Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        ValueError: invalid literal for int() with base 10: 'kjjkj'

        In my program I need to be able to enter char strings or int strings on
        the command line. Then I use an if-elif structure to establish which is
        which. For example -

        if uniList[0].lower() in ("e","exit") : # uniList stores a unicode
        string origionally taken from stdin
        return
        elif uniList[0].lower() in ("h","help") :
        verb.PrintVerb( )
        elif uniList[0].lower() in ("p","pass") :
        break
        elif int(uniList[0]) in range(0,10):
        verb.SetImporta nce(int(uniList[0]))
        break
        else:
        verb.AddNewVerb ((uniList[0])

        How could I avoid the ValueError exception if uniList[0] == "Åker"? I
        was thinking of having something like -

        formatError = False
        try:
        iVal = int(uniList[0])
        if iVal not in range range(0,10):
        formatError = True
        catch ValueError:
        >
        Perhaps you meant
        except ValueError:
        :-)
        >
        >
        iVal = -1
        >
        Consider using uniList[0].isdigit() -- see


        HTH,
        John
        Yes, thanks for your help.

        Comment

        • Gabriel Genellina

          #5
          Re: Avoiding &quot;invali d literal for int()&quot; exception

          At Monday 11/12/2006 07:22, aine_canby@yaho o.com wrote:
          >elif int(uniList[0]) in range(0,10):
          Either of these will work to avoid an unneeded conversion:

          elif uniList[0] in "0123456789 ":

          elif uniList[0] in string.digits:

          elif uniList[0].isdigit():


          --
          Gabriel Genellina
          Softlab SRL

          _______________ _______________ _______________ _____
          Correo Yahoo!
          Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
          ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar

          Comment

          • Marc 'BlackJack' Rintsch

            #6
            Re: Avoiding &quot;invali d literal for int()&quot; exception

            In <mailman.1415.1 165879866.32031 .python-list@python.org >, Gabriel
            Genellina wrote:
            At Monday 11/12/2006 07:22, aine_canby@yaho o.com wrote:
            >
            >>elif int(uniList[0]) in range(0,10):
            >
            Either of these will work to avoid an unneeded conversion:
            >
            elif uniList[0] in "0123456789 ":
            >
            elif uniList[0] in string.digits:
            >
            elif uniList[0].isdigit():
            The last does not work. Not only that it accepts numbers greater than 9
            because it checks if the whole string consists of digits, it also accepts
            u'²₂' and other unicode digits.

            Ciao,
            Marc 'BlackJack' Rintsch

            Comment

            • Peter Otten

              #7
              Re: Avoiding &quot;invali d literal for int()&quot; exception

              Marc 'BlackJack' Rintsch wrote:
              In <mailman.1415.1 165879866.32031 .python-list@python.org >, Gabriel
              Genellina wrote:
              >
              >At Monday 11/12/2006 07:22, aine_canby@yaho o.com wrote:
              >>
              >>>elif int(uniList[0]) in range(0,10):
              >>
              >Either of these will work to avoid an unneeded conversion:
              >>
              >elif uniList[0] in "0123456789 ":
              >>
              >elif uniList[0] in string.digits:
              >>
              >elif uniList[0].isdigit():
              >
              The last does not work. Not only that it accepts numbers greater than 9
              because it checks if the whole string consists of digits, it also accepts
              u'²?' and other unicode digits.
              By the way, if you require an implicit 0 <= int(s) < 10 check, none of the
              above work with the newer Pythons:
              >>s = "23"
              >>s in "0123456789 "
              True
              >>s in set("0123456789 ")
              False

              Peter

              Comment

              • Gabriel Genellina

                #8
                Re: Avoiding &quot;invali d literal for int()&quot; exception

                Marc 'BlackJack' Rintsch ha escrito:
                In <mailman.1415.1 165879866.32031 .python-list@python.org >, Gabriel
                Genellina wrote:
                >
                elif uniList[0].isdigit():
                >
                The last does not work. Not only that it accepts numbers greater than 9
                because it checks if the whole string consists of digits, it also accepts
                u'²₂' and other unicode digits.
                Oh, I didn't know that last part! Thanks.
                I get a bit confused by the [0], thinking it was checking a single
                character.

                --
                Gabriel Genellina

                Comment

                • Fredrik Lundh

                  #9
                  Re: Avoiding &quot;invali d literal for int()&quot; exception

                  Gabriel Genellina wrote:
                  >>elif uniList[0].isdigit():
                  >>
                  >The last does not work. Not only that it accepts numbers greater than 9
                  >because it checks if the whole string consists of digits, it also accepts
                  >u'²₂' and other unicode digits.
                  >
                  Oh, I didn't know that last part! Thanks.
                  I get a bit confused by the [0], thinking it was checking a single
                  character.
                  if you really want to use isdigit(), writing

                  uniList[0].encode("ascii" , "ignore").isdig it()

                  should solve the unicode issue, I think.

                  </F>

                  Comment

                  Working...