Python 如果数据输入不止一次,则响应不同
我是python新手。我试图创建一个脚本,当同一数据被多次输入时,它会给我一个不同的响应。代码如下所示:Python 如果数据输入不止一次,则响应不同,python,Python,我是python新手。我试图创建一个脚本,当同一数据被多次输入时,它会给我一个不同的响应。代码如下所示: def loop() : Repeat = 0 response = raw_input("enter something : ") if response == "hi" Repeat += 1 print "hello" loop() if Repeat > 2 : pr
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()
上面的代码不起作用。最好是我想要一个检查这两个条件的语句,但我不太确定如何做到这一点。我会使用
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
#...
除了,你也可以用
试试
/来做这件事,但我想我应该保持简单的开始…试试这样的方法:
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()
中添加一个中断条件,否则它将是一个无限循环您上面的语句正在递归地调用自身。循环的新实例无权访问Repeat的调用值,而是拥有自己的Repeat本地副本。此外,您还有ifRepeat>2
。正如所写的,这意味着它不会得到你的其他打印语句,直到他们输入“hello”三次,使计数器达到3。您可能希望使该重复>=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)
你应该使用一个while循环来完成类似的事情。这个循环的工作方式和原作的目的完全一样,但是请注意它是递归的。这本身并不坏,但python还没有尾部调用优化(肯定在我个人的愿望清单上)。因此,它最终将达到递归深度限制,并比非递归选项占用更多内存。@TimothyAWiseman递归限制可以使用sys.setrecursionlimit
更改,我完全同意速度。(递归总是很慢)。非常正确。这是一个很好的答案,(向上投票),值得指出的是它是递归的,没有尾部调用优化。