0

I have modified some code from Coroutines as follows:

def grep(p1, p2):
    print("Searching for", p1 ,"and", p2)
    while True:
        line = (yield)
        if (p1 or p2) in line:
            print(line)

search = grep('love', 'woman')
next(search)
search.send("I love you")
search.send("Don't you love me?")
search.send("I love coroutines instead!")   
search.send("Beatiful woman")

Output:

Searching for love and woman
I love you
Don't you love me?
I love coroutines instead!

Second argument "woman" is not recognized in the last search. Why is that?

Omar Einea
  • 2,478
  • 7
  • 23
  • 35
MikiBelavista
  • 2,470
  • 10
  • 48
  • 70

2 Answers2

3

Your condition should be like this:

if p1 in line or p2 in line:

because (p1 or p2) would return p1 as long as there's something in it.
so your current condition always evaluates to if p1 in line:

Omar Einea
  • 2,478
  • 7
  • 23
  • 35
0

Because your code condition is either of two arguments(p1 or p2) matches it return only p1 thats why it donot return the last send function result. Now try this code .

Also I am attach the screenshot of output of the code.

 def grep(p1, p2):
        print("Searching for", p1 ,"and", p2)
        while True:
            line = (yield)
            if (p1) in line:
                print(line)
            if (p2) in line:
                print(line)

    search = grep('love', 'woman')
    next(search)
    search.send("I love you")
    search.send("Don't you love me?")
    search.send("I love coroutines instead!")   
    search.send("beautiful woman")

enter image description here

Usman
  • 1,983
  • 15
  • 28