Input Types

Leif K-Brooks eurleif at ecritters.biz
Sat May 15 11:19:00 EDT 2004


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.



More information about the Python-list mailing list