Many thanks!

On 25-03-17 11:17, Alan Gauld via Tutor wrote:
On 25/03/17 10:01, Peter O'Doherty wrote:

def myFunc(num):
      for i in range(num):
          print(i)

print(myFunc(4))
0
1
2
3
None #why None here?
Because your function does not have an explicit return
value so Python returns its default value - None.
So the print() inside the function body prints the 0-3
values then the function terminates and returns the (default)
None to your top level print.

def myFunc(num):
      for i in range(num):
          return i

print(myFunc(4))
0 #why just 0?
Because return always returns from the function immediately.
So you call the function, it enters the loop, sees the return for the
first element and exits. The print() then prints that returned value.

The preferred method to do what I think you were expecting is to build a
list:

def anotherFunction(num):
     result = []
     for i in range(num):
        result.append(i)
     return result

Which is more concisely written using a list comprehension but
that would hide the general point - that you should accumulate results
in a collection if you want to return more than a single value.

To print the result you would typically use the string.join()
method:

print(' '.join(anotherFunction(4))




//=============================
// Peter O'Doherty

// http://www.peterodoherty.net
// m...@peterodoherty.net
//=============================

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to