[Tutor] A few newbie questions ...

Wesley J. Chun wesc@alpha.ece.ucsb.edu
Fri, 18 Feb 2000 14:07:43 -0800 (PST)


    > Date: Fri, 18 Feb 2000 10:36:15 -0800 (PST)
    > From: Deirdre Saoirse <deirdre@deirdre.net>
    > 
    > On Fri, 18 Feb 2000, Joseph Stubenrauch wrote:
    > 
    > > 2.  Is it possible to have input be either a string or
    > > number, depending on what the user inputs?  In other
    > > words, I would like to create a menu with options
    > > #1-4, and option X and Q to quit.  Is that possible?
    > 
    > You can try and convert a string to a number and assume it's a string if
    > that fails:
    > 
    > a = "foo"
    > try:
    >  b = int(a)
    > except:
    >  b = a
    > 
    > print b


fortunately, you have a recent version of Python.

prior to 1.5, int(string) fails.  if your application
required backwards-compatibility to older systems (if
any, it would be 1.4), you would have to use the tried-
and-true string.atoi() function:

C:\>python
Python 1.3 (Apr 13 1996) [MSC 32 bit (Intel)]
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> int('4')
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: int() argument can't be converted to int
>>> import string
>>> string.atoi('4')
4
>>>


otherwise, either way [int() or string.atoi()] would work.


one suggestion i have as a side project for you is to write
a "menu" function or class that helped you with text-based
menu-generation.  it would take a list of all items, perhaps
choose a default selection (if the user just hits return,
provides error messages on invalid entries, automatically
generates the menu item numbers, etc.

once you accomplish this, you can generically use this
piece of code anywhere you have a menu-driven interface
and not have to reinvent the wheel every time.

hope this helps!!

-wesley
cyberweb.consulting :: silicon.valley, ca
http://www.roadkill.com/~wesc/cyberweb/