Created
February 27, 2013 23:24
-
-
Save anonymous/5052801 to your computer and use it in GitHub Desktop.
Simple input loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Simple input loop thing! | |
By Lambda Fairy (github.com/lfairy) | |
Examples:: | |
n = read(int, 'Enter a number: ') | |
MIN = 1 | |
MAX = 100 | |
guess = read( | |
int_in_range(MIN, MAX), | |
'Enter a number from {} through {}: '.format(MIN, MAX)) | |
true = read(yes_no, 'Do you like ducks? ') | |
Public domain, because public domain is cool. | |
""" | |
def read(parse, message='', error=None): | |
while True: | |
try: | |
return parse(input(message).strip()) | |
except Exception as ex: | |
print(error or ex) | |
def int_in_range(low, high): | |
def parse(s): | |
number = int(s) | |
if not (low <= s <= high): | |
raise ValueError('number must be from {} through {}'.format(low, high)) | |
return number | |
return parse | |
YESES = set('yt') | |
NOESES = set('nf') | |
def yes_no(s): | |
if len(s) < 1: | |
raise ValueError('enter yes or no') | |
letter = s[0].lower() | |
if letter in YESES: | |
return True | |
elif letter in NOESES: | |
return False | |
else: | |
raise ValueError('enter yes or no') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment