Skip to content

Instantly share code, notes, and snippets.

Created February 27, 2013 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/5052801 to your computer and use it in GitHub Desktop.
Save anonymous/5052801 to your computer and use it in GitHub Desktop.
Simple input loop
"""
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