Skip to content
Create a gist now

Instantly share code, notes, and snippets.

@lfairy / forked from anonymous/
Last active

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Simple input loop demonstrating higher-order functions
Simple input loop thing, with ducks.
By Lambda Fairy (
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.
# Work on both Python 2 and 3
read_str = raw_input
except NameError:
read_str = input
def read(parse, message='', error=None):
while True:
return parse(read_str(message).strip())
except ValueError 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
raise ValueError('enter yes or no')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.