473,327 Members | 1,952 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

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('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?

Jul 19 '05 #1
5 1465
On 22 Apr 2005 07:45:40 -0700, al*****************@gmail.com > 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?


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,
si***@brunningonline.net,
http://www.brunningonline.net/simon/blog/
Jul 19 '05 #2
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>

Jul 19 '05 #3
al*****************@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

Jul 19 '05 #4
Brian van den Broek <bv****@po-box.mcgill.ca> wrote:
you've not included the part of your code which acts on the
user's input.
I think you'll find the answer to the question of where the code
that acts on the user's input lies here:
(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.)

--
\S -- si***@chiark.greenend.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
Jul 19 '05 #5
Sion Arrowsmith said unto the world upon 2005-04-22 13:00:
Brian van den Broek <bv****@po-box.mcgill.ca> wrote:
you've not included the part of your code which acts on the
user's input.

I think you'll find the answer to the question of where the code
that acts on the user's input lies here:

(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.)


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
Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: AIM | last post by:
Error in msvc in building inheritance.obj to build hello.pyd Hello, I am trying to build the boost 1.31.0 sample extension hello.cpp. I can not compile the file inheritance.cpp because the two...
14
by: kosuke | last post by:
I keep getting the following error/warning message when using the python based program getmail4: /usr/lib/python2.3/optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a...
10
by: ale.of.ginger | last post by:
Greetings! I am trying to make a multiplayer (no AI, 2 person) game of tic tac toe in Python. So far it has been pretty simple. My only concern is with the win checking to see if a person has...
3
by: Vincent V | last post by:
Hey im Overiding OnInit in my Custom Page class What i want to be able to do is pass in Some Values Ie PageID PageCategory, PageSubCategory How can i pass in some Vairables So my Custom Page class...
0
by: Terry Tang | last post by:
Hi There, We are extending Python interpreter to support special functions of our tools. What we did is to compile Python's source code (which is got from the an installation on a Linux...
21
by: one2001boy | last post by:
PostMessage() function returns ERROR_NOT_ENOUGH_QUOTA after running in a loop for 700 times, but the disk space and memory are still big enough. any suggestion to resolve this problem? thanks.
2
by: f rom | last post by:
----- Forwarded Message ---- From: Josiah Carlson <jcarlson@uci.edu> To: f rom <etaoinbe@yahoo.com>; wxpython-users@lists.wxwidgets.org Sent: Monday, December 4, 2006 10:03:28 PM Subject: Re: ...
2
by: seb | last post by:
Hi, this simple server (time protocol) does not respond after a few hours, even when it is restarted. The behaviour looks to me like a firewall blocking but I have desabled the firewall. Using...
8
by: jadamwil | last post by:
Hello, I am using the numpy fromfile function to read binary data from a file on disk. The problem is that the program runs fine on a Mac, but gives an error or warning on windows when trying to...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.