Overiding error message when using a python program

Brian van den Broek bvande at po-box.mcgill.ca
Fri Apr 22 11:39:03 EDT 2005


aleksander.helgaker at gmail.com said unto the world upon 2005-04-22 10:45:
> 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('clear')
> 	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?
> 

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(request):
     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




More information about the Python-list mailing list