Last active — forked from anonymous/read.py

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Simple input loop demonstrating higher-order functions

View read.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
"""
Simple input loop thing, with ducks.
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.
"""
 
# Work on both Python 2 and 3
try:
read_str = raw_input
except NameError:
read_str = input
 
def read(parse, message='', error=None):
while True:
try:
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
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
Something went wrong with that request. Please try again.