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']
printis defined asprints the values to a stream; this means that once the control return to the caller, it receivesNone(which is equivalent toreturn None). If you don't want to get aNoneobject then you all need is put some values to thereturnstatement (e.g.,return [1, 2]). Notice that once Python encounter areturnstatement in your function, it immediately send the control back to the caller.