Input Types

moma moma at example.net
Sat May 15 14:23:51 EDT 2004


Jeff Epler wrote:
> Here's a function that can do the job.
> 
> def typed_input(prompt="", convert=int, catch=ValueError,
>                 eprompt="Invalid input."):
>     while 1:
>         s = raw_input(prompt)
>         try:
>             return convert(s)
>         except catch:
>             print eprompt
> 

You can send functions (int, float) and exceptions as parameters?
Amazing.


> Usage:
>>>>typed_input("Enter an integer: ")
> 
> Enter an integer: asdf
> Invalid input
> Enter an integer: 3
> 3
> 
>>>>typed_input("Enter a number: ", float)
> 
> Enter a number: 
> Invalid input
> Enter a number: 3.14
> 3.1400000000000001
> 
> How does it work?
> 
> 1. The "while 1" loop is repeated until the "return" statement is
> successfully executed.
> 
> 2. int(s) and float(s) convert a string argument s to the specified
> type, or raise the ValueError exception
> 
> 3.  When there is a ValueError exception, the "error prompt" is printed,
> and the while loop returns to the top to try again.
> 
> You can also write your own "convert" function to restrict values to a
> range, etc:
> 
> 
>>>>def int_0_100(s):
> 
> ...     i = int(s)
> ...     if i < 0 or i > 100:
> ...         raise ValueError  # out of range
> ...     return i
> ...
> 
>>>>typed_input("Enter a number from 0 to 100: ", int_0_100)
> 
> Enter a number from 0 to 100: asdf
> Invalid input.
> Enter a number from 0 to 100: 101
> Invalid input.
> Enter a number from 0 to 100: 37
> 37
> 
> You can also specify the catch= or eprompt= arguments to change the
> exception that is caught or the error prompt string.
> 
> Jeff
> 



More information about the Python-list mailing list