-
Notifications
You must be signed in to change notification settings - Fork 1
/
yes_no.py
51 lines (46 loc) · 1.54 KB
/
yes_no.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
# Tai Sakuma <[email protected]>
from __future__ import print_function
import sys
try:
input = raw_input
except NameError:
pass
##__________________________________________________________________||
# based on http://code.activestate.com/recipes/577058/
#
def query_yes_no(question, default=True):
"""Ask a yes/no question and return True/False. If keyboard interrupts
three times, return default
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be True or False
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default:
prompt = " [Y/n] "
default = True
else:
prompt = " [y/N] "
default = False
ninterrupt = 0
while 1:
try:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return default
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "\
"(or 'y' or 'n').\n")
except KeyboardInterrupt:
ninterrupt += 1
if ninterrupt >= 3:
return default
sys.stdout.write('\n')
##__________________________________________________________________||
if __name__ == '__main__':
print(query_yes_no('test question 1', True))
print(query_yes_no('test question 2', False))