Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

Different Output in Print and Return in Python Function

I want to return the words from a list whose first letter starts with s and I have performed the following 2 solutions. One is near to the solution and the other one is correct but not in the exact form which is desired. And also I am getting a different result if I use "print" vs "return" in python function. Why is that so? Please guide me.

1st Method:

def s(opt):
    for a in opt:
        if a[0] == 's':
            return(a)
s(['soup','dog','salad','cat','great'])

Output I am getting by running this code is 'soup' - that too in inverted commas - Why?

2nd Method:

def s(opt):
    for a in opt:
        if a[0] == 's':
            print(a)
s(['soup','dog','salad','cat','great'])

Output I am getting by this method is soup, salad in vertical form with no inverted commas and all. Why?

My question is how can I get the desired output by keeping the return in function method? Another question why output is being different when used print vs return in above methods?

Desired Output: ['soup', 'salad']

question from:https://stackoverflow.com/questions/65866782/different-output-in-print-and-return-in-python-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use yield instead of return. When your condition if a[0] == 's' is getting true then the s() function return.

If you want to return multiple values when your requirements meet then you have to use another list to store your answer or you can use list comprehension

def s(opt):
    for a in opt:
        if a[0] == 's':
            yield a


print(list(s(['soup', 'dog', 'salad', 'cat', 'great'])))

# Output
# ['soup', 'salad']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...