multiple raw_inputs

Fredrik Lundh fredrik at pythonware.com
Fri Nov 25 08:42:20 CET 2005


Satya Kiran wrote:

> I m a python newbie,infact,I m a newbie to programming and I was suggested
> it was a good idea to start it with python.
>
> I was trying a program which needs three integers from the user.I got it by
> using raw_input thrice.
> Is there a better way(s) to do it?

if you want to ask three questions, asking three questions seem to
be a rather good way to do it...

> Can a user be prompted thrice with a single raw_input and something
> additional?

you could use the input() function to read an integer tuple:

    >>> a, b, c = input("enter three comma-separate values: ")
    enter three comma-separate values: 1, 2, 3
    >>> a
    1
    >>> b
    2
    >>> c
    3

but this is pretty fragile:

    >>> a, b, c = input("enter three comma-separate values: ")
    enter three comma-separate values: 1, 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    ValueError: unpack tuple of wrong size
    >>> a, b, c = input("enter three comma-separate values: ")
    enter three comma-separate values: hello
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<string>", line 0, in ?
    NameError: name 'hello' is not defined

to work around this, you can place the input statement in a loop and
use try-except to catch any errors:

    while 1:
        try:
            a, b, c = input("enter 3 values: ")
        except KeyboardInterrupt:
            raise
        except:
            print "invalid input; try again"
        else:
            break

but at this point, maybe using three separate calls aren't such a bad
idea anyway...

</F>






More information about the Python-list mailing list