[Tutor] Calculator functions part II

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 22 Jun 2001 01:10:21 -0700 (PDT)


On Thu, 21 Jun 2001, Josh Gregorio wrote:

> Cool. I didn't know that. Is it generally better to convert strings to
> integers, rather than use input()? When would input() be appropriate?

It's usually better to convert strings to integers.  For your own casual
scripts, input() is perfectly fine.  In the outside world though, it's a
death-trap... *grin*

When we're entering commands into the Python interpreter, we can imagine
the following happening:

### simplified Python interpreter loop:
while 1:
    result = input(">>> ")
    print result
###

In a limited sense, the above is what we run when we type "python" at the
command prompt.  input() has as much power as we do, and anyone who can
enter something into input() can write their own one-line Python program.  
Using some imagination, you can see why we're hesitant to look at input()
favorably.

There are instances in the real world where people have done the
equivalent of plopping input() in their programs.  This is a Bad Thing, as
in Melissa Virus bad.


By the way, here's a small helper function that will make reading integers
safer for you:

###
def getInteger(prompt=None):
    try:
        if prompt: print prompt,
        return int(raw_input())
    except ValueError:               ## If bad things happen
        return getInteger(prompt)    ## try it again!
###

If you're not familiar with exceptions, you can think of it as telling
Python the following instructions: "Let's try the following ... And if
anything bad happens that deals with bad Values, let's do this ..."


Here's a small test of that function:

###
>>> mynumber = getInteger("Please enter a number:")
Please enter a number:muhahah
 Please enter a number:forty two
 Please enter a number:42

>>> mynumber
42
###

Some of the output formatting is off, but I hope the idea makes sense.  
Good luck!