473,480 Members | 1,942 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Input Types

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
4 1941
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
7231
by: TechNovice | last post by:
Hi: I'm trying to find a way to test input values. To test an integer I tried this code: ******Code****** int input_number; cin>>input_number; while(!input_number) cout<<"invalid...
2
1965
by: SophistiCat | last post by:
Hi, I am working on a computational program that has to read a number of parameters (~50) from an input file. The program contains a single class hierarchy with about a dozen member-classes or...
2
2121
by: Mike | last post by:
Hi I have been tasked with converting my pulp and paper mills weekly projected and actual contractor hrs excel spreadsheet into a an Access 97 database. So far my design has been to use a...
2
5182
by: bildad | last post by:
The following 'book example' of validating input seems to be incomplete. Since it is a beginner's book it may be intentional for simplicity. But I would like to know how to make this program work...
6
1980
by: Dan | last post by:
Is there a way to access and set a hidden input types in the code-behind page for ASP.Net? This seems like a common thing that would need to be done, I must be missing something obvious. ...
8
5884
by: David Cameron | last post by:
I noticed that using an HTMLInputRadioButton and specifying a value to be an empty string (""), this is overridden by ASP.Net which set the value of the control to be the same as the ID of the...
6
4171
by: b. hotting | last post by:
Hi, I don't see why this won't work, it are 3 links, the last one (a get) does work, but the first 2 won't. i would like to use a post, through hidden input types any idea? thanks for your...
18
24927
by: Diogenes | last post by:
Hi All; I, like others, have been frustrated with designing forms that look and flow the same in both IE and Firefox. They simply did not scale the same. I have discovered, to my chagrin,...
14
2380
by: n3o | last post by:
Hello Comp.Lang.C Members, I have an issue with user input that I have been trying to figure out for the longest. For instance, let's say you have something like this: void foo() { int num;...
11
6763
by: arnuld | last post by:
C takes input character by character. I did not find any Standard Library function that can take a word as input. So I want to write one of my own to be used with "Self Referential Structures" of...
0
6911
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7050
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7091
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6743
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
6966
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5344
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
2999
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
2988
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1303
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.