Overiding error message when using a python program

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • aleksander.helgaker@gmail.com

    #1

    Overiding error message when using a python program

    I've completely rewritten a calculator I wrote to help me learn Python.
    After someone told me about the def command I reliesed that I could
    make the program much better, but there is a very anoying problem which
    ocours when I run the program.

    Here is the code
    <code>
    # IMPOSRTS #
    import sys
    import os

    # DEF'S #
    def print_intro():
    os.system('clea r')
    print "Welcome to Calc v 0.1a"
    print "----------------------"

    def main():
    print_intro()
    while True:
    prompt_user()

    def prompt_user():
    userinput = input(">")

    def fib(n): # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    while b < n:
    print b,
    a, b = b, a+b
    print

    def quit():
    sys.exit()

    # PROGRAM FLOW
    main()
    </code>

    Now when I run this program and I type in a command which I have no
    code for e.g. "pi" (which is 3,14....) I get the error message
    "NameError: name 'pi' is not defined" and then the program quits.

    I'm creating this program for my own use but naturally sometimes I
    would make spelling mistakes (being a dyslexic and all) and so having a
    long error message and having the program quit is more then a bit
    irritating. It would be much more preferable if the program simply
    wrote "Command not recognised" and then kept going. Is this possible?

  • Simon Brunning

    #2
    Re: Overiding error message when using a python program

    On 22 Apr 2005 07:45:40 -0700, aleksander.helg aker@gmail.com > I'm
    creating this program for my own use but naturally sometimes I[color=blue]
    > would make spelling mistakes (being a dyslexic and all) and so having a
    > long error message and having the program quit is more then a bit
    > irritating. It would be much more preferable if the program simply
    > wrote "Command not recognised" and then kept going. Is this possible?[/color]

    It certainly is. "NameError" is what's called an exception, and you
    can catch those. Try something like (untested):

    try:
    print 10 / pi
    except NameError:
    print "Command not recognised"

    I can't see where you'd want that in your code, 'cos I can't see where
    you are actually processing the user's input.

    For more on exceptions, see <http://docs.python.org/tut/node10.html>.

    --
    Cheers,
    Simon B,
    simon@brunningo nline.net,

    Comment

    • aleksander.helgaker@gmail.com

      #3
      Re: Overiding error message when using a python program

      Thanks, this works great.

      I edited def prompt_user() so that it now reads

      <code>
      def prompt_user():
      try:
      userinput = input(">")
      except NameError:
      print "Command not recognised"
      </code>

      Comment

      • Brian van den Broek

        #4
        Re: Overiding error message when using a python program

        aleksander.helg aker@gmail.com said unto the world upon 2005-04-22 10:45:[color=blue]
        > I've completely rewritten a calculator I wrote to help me learn Python.
        > After someone told me about the def command I reliesed that I could
        > make the program much better, but there is a very anoying problem which
        > ocours when I run the program.
        >
        > Here is the code
        > <code>
        > # IMPOSRTS #
        > import sys
        > import os
        >
        > # DEF'S #
        > def print_intro():
        > os.system('clea r')
        > print "Welcome to Calc v 0.1a"
        > print "----------------------"
        >
        > def main():
        > print_intro()
        > while True:
        > prompt_user()
        >
        > def prompt_user():
        > userinput = input(">")
        >
        > def fib(n): # write Fibonacci series up to n
        > """Print a Fibonacci series up to n."""
        > a, b = 0, 1
        > while b < n:
        > print b,
        > a, b = b, a+b
        > print
        >
        > def quit():
        > sys.exit()
        >
        > # PROGRAM FLOW
        > main()
        > </code>
        >
        > Now when I run this program and I type in a command which I have no
        > code for e.g. "pi" (which is 3,14....) I get the error message
        > "NameError: name 'pi' is not defined" and then the program quits.
        >
        > I'm creating this program for my own use but naturally sometimes I
        > would make spelling mistakes (being a dyslexic and all) and so having a
        > long error message and having the program quit is more then a bit
        > irritating. It would be much more preferable if the program simply
        > wrote "Command not recognised" and then kept going. Is this possible?
        >[/color]

        Sure, its possible. How to do it from where you are is a bit more
        dark; you've not included the part of your code which acts on the
        user's input. (And your prompt_user function should use raw_input and
        return the user input for processing by other functions. raw_input is
        safer; input executes arbitrary code.)

        I see just before sending, that you seemed happy with Simon Brunning's
        suggestion. But, as I hate to waste the typing, here's another way
        sketched:

        def funct1():
        print 'This is funct1'

        def funct2():
        print 'This is funct2'

        funct_dict = {'1': funct1, '2': funct2}
        # strings as keys because of raw_input
        # functions are objects, and thus can be values in a dict

        def prompt_user():
        return raw_input('Well ?')

        def dispatch(reques t):
        function = funct_dict.get( request, None)
        if function:
        function()
        else:
        print 'You entered %s, but there is no such command' %request


        Put that in a script and run

        dispatch(prompt _user())

        and you should see the desired behaviour. I will leave integrating the
        idea into the structure you have as yet to you.

        HTH,

        Brian vdB

        Comment

        • Sion Arrowsmith

          #5
          Re: Overiding error message when using a python program

          Brian van den Broek <bvande@po-box.mcgill.ca> wrote:[color=blue]
          > you've not included the part of your code which acts on the
          >user's input.[/color]

          I think you'll find the answer to the question of where the code
          that acts on the user's input lies here:
          [color=blue]
          > (And your prompt_user function should use raw_input and
          >return the user input for processing by other functions. raw_input is
          >safer; input executes arbitrary code.)[/color]


          --
          \S -- siona@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
          ___ | "Frankly I have no feelings towards penguins one way or the other"
          \X/ | -- Arthur C. Clarke
          her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump

          Comment

          • Brian van den Broek

            #6
            Re: Overiding error message when using a python program

            Sion Arrowsmith said unto the world upon 2005-04-22 13:00:[color=blue]
            > Brian van den Broek <bvande@po-box.mcgill.ca> wrote:
            >[color=green]
            >>you've not included the part of your code which acts on the
            >>user's input.[/color]
            >
            >
            > I think you'll find the answer to the question of where the code
            > that acts on the user's input lies here:
            >
            >[color=green]
            >>(And your prompt_user function should use raw_input and
            >>return the user input for processing by other functions. raw_input is
            >>safer; input executes arbitrary code.)[/color]
            >[/color]

            Quite so :-[ I think I must have typed the two parts which you
            quote with different hands, because obviously my brain didn't manage
            to see them both at once.

            Thanks for pointing that out.

            Best,

            Brian vdB

            Comment

            Working...