Search code examples
pythoncountdown

Countdown Function Only Returning One Value


What is wrong with the second function?

def count(n):
  return [i for i in range (n,-1,-1)]

gives me the accurate result of [5, 4, 3, 2, 1] but

def count(n):
  for i in range (n,-1,-1):
      return i

always returns n.


Solution

  • As people have said in the comments, return stops the function and returns the value. Use a generator if you want to do something like this, but not exit the function. Also, it is recommended that you use 4 spaces for indentation by PEP 8, the official Python style guide.

    def count(n):
        for i in range(n, -1, -1):
            yield i
    
    print(list(count(5)))