我的代码正在为第一个输入工作,但现在我想重新提示用户输入并重复该过程,直到用户输入'stop'。我已经尝试将我的代码放在另一个while循环中,创建一个不同的函数定义并将代码放在现有的if语句中。 这是我目前的代码:
def findInfo(myList, target):
list.sort(myList)
#print myList, target
guesses = 0
low = 0
high = len(myList)-1
mid = (high + low) / 2
while high >= low:
if target == myList[mid][0]:
print "Here are your results:"
print 'state:', myList[mid][0]
print 'total number:', myList[mid][1]
print '% passed:', myList[mid][2]
print '% female students:', myList[mid][3]
return True
elif target > myList[mid][0]:
low = mid + 1
guesses += 1
print "guess", guesses
elif target < myList[mid][0]:
high = mid - 1
guesses += 1
print "guess", guesses
mid = (high + low)/ 2
print False, "no match found"
return False
我真的很困惑在哪里放置代码重新询问用户输入,直到输入的某个单词。
答案 0 :(得分:1)
你可以使用cmd lib,类似的东西:
import cmd
class myApp(cmd.Cmd):
def do_findInfo(self,target, myList = defaultList):
list.sort(myList)
#print myList, target
guesses = 0
low = 0
high = len(myList)-1
mid = (high + low) / 2
while high >= low:
if target == myList[mid][0]:
print "Here are your results:"
print 'state:', myList[mid][0]
print 'total number:', myList[mid][1]
print '% passed:', myList[mid][2]
print '% female students:', myList[mid][3]
return True
elif target > myList[mid][0]:
low = mid + 1
guesses += 1
print "guess", guesses
elif target < myList[mid][0]:
high = mid - 1
guesses += 1
print "guess", guesses
mid = (high + low)/ 2
print False, "no match found"
return False
def do_EOF(self, line):
return True
if __name__ == '__main__':
myApp().cmdloop()
这将显示您需要输入的命令行:“findInfo target”
答案 1 :(得分:1)
为什么不简单地做某事。像这样:
def term(s):
return s in ['stop', 'exit', 'quit']
if __name__=='__main__':
inp = ''
while not term(inp):
inp = raw_input('prompt: ')
if not term(inp):
try:
i = int(inp)
print(findInfo(myList, i))
except ValueError as e:
print('Invalid input: {}'.format(e.message))