By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,100 Members | 2,892 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,100 IT Pros & Developers. It's quick & easy.

Input Types

P: n/a
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.)
Jul 18 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
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:
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

Jul 18 '05 #2

P: n/a
EAS wrote:
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.
Jul 18 '05 #3

P: n/a
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

Jul 18 '05 #4

P: n/a
On Sat, May 15, 2004 at 08:23:51PM +0200, moma wrote:
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
send_to(3, f) # square the argument: works 9 send_to(3, print) # Print the argument: error

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

Jul 18 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.