Input Types

E

EAS

How do you make a loop where the program keeps asking for
an integer or float until it gets one? (No letters or other input.)
 
J

Jeff Epler

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

Usage:Enter an integer: asdf
Invalid input
Enter an integer: 3
3Enter 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:
.... i = int(s)
.... if i < 0 or i > 100:
.... raise ValueError # out of range
.... return i
....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
 
L

Leif K-Brooks

EAS said:
How do you make a loop where the program keeps asking for
an integer or float until it gets one? (No letters or other input.)

import sys # We need sys.stdin for input
while True: # Infinite loop. We break out of it after getting a float.
try: # For catching the exception of getting an invalid float.
num = float(sys.stdin.readline().rstrip("\r\n")) # Try
# parsing it as a float.
break # If we reach this line, it's valid. Exit the loop
except ValueError: # It's an invalid float.
pass # Just let the loop run again.
 
M

moma

Jeff said:
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.
 
J

Jeff Epler

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

You sure can.

numbers, sequences, dicts, functions, exceptions, classes, modules: all
these things are objects, and you can pass any object you like as a
parameter. Of course, not all object types *make sense* everywhere!

One "exception" to this rule is thinking that print is a function, and
trying to write
def send_to(value, action):
return action(value)

def f(x): return x*x
File "<stdin>", line 1
send_to(3, print)
^
SyntaxError: invalid syntax

because print is a statement, not a function, this isn't really an
exception to the rule at all.

Jeff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,197
Messages
2,571,040
Members
47,635
Latest member
SkyePurves

Latest Threads

Top