如果输入的数据多于on,则响应不同

2024-03-28 21:22:04 发布

您现在位置: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()

上面的代码不起作用。最好是我想一个声明,检查这两个条件,但我不太清楚如何可以做到这一点。你知道吗


Tags: 数据代码脚本loopinputrawifmain
3条回答

我将使用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来做这个,但是我想我应该保持简单的开始。。。你知道吗

上面的语句递归地调用自身。循环的新实例不能访问Repeat的调用值,而是有自己的Repeat本地副本。另外,还有ifRepeat > 2。正如所写的,这意味着它不会得到你的其他打印语句,直到他们输入“hello”三次,使计数器达到3。你可能想把它变成Repeat >= 2。你知道吗

您需要的是一个while循环,用于跟踪输入是否重复。在现实生活中,你可能需要一些条件来告诉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)

尝试以下操作:

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 : 

另外,还要给loop()添加一个中断条件,否则它将是一个无限循环

相关问题 更多 >