+ 4

Why does the output comes with only the first element in a list when I use a function?

Here is my code: names=['ahmed','mohammed','hany'] def func(list): for name in list: return (name) print(func(names)) output>ahmed shouldn't it iterate through the list and give the whole list? when I use print instead of return, it works but gives me the word 'none' in the end.

22nd Aug 2017, 11:52 PM
Mohammed Abdulhady
Mohammed Abdulhady - avatar
4 Answers
+ 4
@Jamie's solution looks good to me--and appropriate; I'm not here to distract--just writing to encourage you: As you go through SoloLearn's course, just remember the concept you were originally thinking. Python has several interesting ways to get at data. You may soon run into some syntax compatible with your idea :)
23rd Aug 2017, 12:52 AM
Kirk Schafer
Kirk Schafer - avatar
+ 4
@Jamie ... Maybe, i.e., if 'better' confuses things, I'm not being helpful. I rather prefer your focus and respect your choice, so I considered carefully before posting.
23rd Aug 2017, 1:08 AM
Kirk Schafer
Kirk Schafer - avatar
+ 1
Thank you for your comments, I am still a newbie in programming. (actually I am a dentist :D). I became very interested lately in programming. I noticed that everytime I keep the 'print' statement in the function and then print my function like what I did above, it gives me the right output followed by 'None' but if I used the 'return' statement (which is considered the right one), it gives me only the first name in my list. This is very mind boggling. I also tried to change my indentations, but it gives me errors.
23rd Aug 2017, 6:46 AM
Mohammed Abdulhady
Mohammed Abdulhady - avatar
+ 1
Any user defined function exits the function when it reaches the "return" keyword. And when you don't use the "return" keyword it returns none. So You could use this code to get rid of none in the last line: names=['ahmed','mohammed','hany'] def func(list): for name in list: print(name) return "" print(func(names))
11th Sep 2017, 8:02 AM
Mohammed Hany
Mohammed Hany - avatar