Skip to main content
 首页 » 编程设计

python之一旦我回复了回复,该功能就不会继续。有没有办法可以返回一个值然后继续

2025年05月04日13sky-heaven

我正在创建一个您可以与之交谈的机器人。我正在使用 if 函数来检查是否使用了某些单词并因此得到回复。我在函数内部执行此操作并使用 return 打印回复。如果说两件事我希望它能够同时说出它们,问题是一旦我返回回复该功能就不会继续。有没有办法可以返回一个值然后继续?这是我的全部代码之后的主要焦点。

    # Reply 
    if thank == True: 
        return "It's my pleasure\n" 
    if greet == True: 
        return "How are you?\n" 

主要代码:

# Chat Bot 
import random 
 
print("Hi!\n") 
greetings = ["hi","hey","hello","yo","wassup"] 
thanks = ["cheers","thanks","thx"] 
 
def reply(x): 
    greet = False 
    # Greetings 
    for item in greetings: 
        if item in x: 
            greet = True 
 
    # Thanks 
    thank = False 
    for item in thanks: 
        if item in x: 
            thank = True 
 
 
    # Reply 
    if thank == True: 
        return "It's my pleasure\n" 
    if greet == True: 
        return "How are you?\n" 
 
    else: 
        randomAnswers = ["I like cheese.", "That's Cool.", "You are a robot.", "I am not a robot.", "I like music.", "I want to visit australia.","Do you like me?","You're cool."] 
        num = random.randint(0, len(randomAnswers) - 1) 
 
        return randomAnswers[num] 
 
 
 
while 1: 
 
    userMessage = input("Message: ").lower() 
    print() 
    print(reply(userMessage)) 

请您参考如下方法:

Is there a way I can return a value and then carry on?

是的!大多数语言不能做到这一点,但 Python 可以。只是 yield 而不是 returning。这放弃了一个值,但让你的函数继续运行。这是一个例子:

def return_some_values(zero, one, two): 
    if zero: 
        yield 0 
    if one: 
        yield 1 
    if two: 
        yield 2 

因此,此函数在完成之前可以返回 0 到 3 个值。

但是你如何使用它呢?

当您调用一个yield 的函数(“生成器函数”)时,您得到的是一个生成器。生成器和列表一样,是可迭代的——也就是说,你可以遍历它,或者将它复制到列表或集合中,等等。(与列表不同,它不是序列——你不能索引它,你可以只循环一次,然后它就用完了,等等。与列表不同的是,它惰性——值不存在,直到你要求它们。)所以:

values = return_some_values(False, True, True) 
for i in value: 
    print(i) 

…将打印出1,然后打印出2。

请参阅 Iterators 上的教程部分以及以下关于生成器的部分,以获得更长的介绍。和 Generator Tricks for System Programmers也很有帮助。