如果数据输入多次,则响应不同

时间:2012-10-24 16:25:20

标签: python

我是python的新手。我正在尝试创建一个脚本,当多次输入相同的数据时,它会给出不同的响应。代码如下:

def loop() :
    Repeat = 0
    response = raw_input("enter something : ")
    if response == "hi"
        Repeat += 1
        print "hello"
        loop()
        if Repeat > 2 :
            print "you have already said hi"
            loop()


def main() :
    loop()
    raw_input()

main()

上述代码不起作用。我想要一个检查这两个条件的声明,但我不太确定如何做到这一点。

3 个答案:

答案 0 :(得分:1)

我会使用dict来存储单词/计数。然后,您可以查询该单词是否在字典中并更新计数...

words = {}
while True:
    word = raw_input("Say something:")
    if word in words:
       words[word] += 1
       print "you already said ",words[word]
       continue
    else:
       words[word] = 0
       #...

您也可以使用try / except执行此操作,但我认为我可以保持简单开始...

答案 1 :(得分:1)

尝试这样的事情:

def loop(rep=None):
    rep=rep if rep else set()  #use a set or list to store the responses
    response=raw_input("enter something : ")
    if response not in rep:                    #if the response is not found in rep
        rep.add(response)                      #store response in rep   
        print "hello"
        loop(rep)                              #pass rep while calling loop()
    else:
        print "You've already said {0}".format(response)    #if response is found 
        loop(rep)
loop()        

<强>输出:

enter something : hi
hello
enter something : hi
You've already said hi
enter something : foo
hello
enter something : bar
hello
enter something : bar
You've already said bar
enter something : 

PS:还为loop()添加一个破坏条件,否则它将是一个无限循环

答案 2 :(得分:0)

上面的陈述是递归调用自己的。新的循环实例无法访问Repeat的调用值,而是拥有自己的Repeat本地副本。此外,您还有Repeat > 2。如上所述,这意味着在输入“hello”三次以使计数器达到3之前,它将不会获得您的其他打印语句。您可能想要制作Repeat >= 2

你想要的是一个跟踪输入是否重复的while循环。在现实生活中,你可能想要一些条件告诉你循环何时结束,但你没有抱怨这里你可以使用while True:永远循环。

最后,您的代码只检查他们是否多次输入“hello”。您可以通过跟踪他们已经说过的内容来使其更加通用,并且无需在此过程中使用计数器。对于我没有测试的快速版本,它可能会循环:

alreadySaid = set() #sets are effecient and only store a specific element once
while True: #probably want an actual break condition here, but to do it forever this works
   response = raw_input("enter something : ") 
   if response in alreadySaid:
      print 'You already said {}'.format(response)
   else:
      print response
      alreadySaid.add(response)