Python 不断提示用户输入,直到输入某个单词



我的代码适用于第一个输入,但现在我想重新提示用户输入并重复该过程,直到用户输入"停止"。我尝试将我的代码放在另一个 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   

我只是真的很困惑,不知道在哪里放置代码以重新要求用户输入,直到输入某个单词。

您可以使用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"

为什么不简单地像这样做sth:

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))

相关内容

  • 没有找到相关文章