Search code examples
pythonfunctionreturnyield

Python why i got no output here


I recently started learning python and I cannot figure why I got no output from the code below:

def countdown():
    i = 5
    while i > 0:
        return i
        i -= 1
    print (i)

Solution

  • As @alfasin stated in the comments, you bail out of the function by using return before your function does anything.

    What you probably intended to do was this:

    def countdown():
        i = 5
        while i > 0:
            print(i)
            i -= 1
    
        return i
    

    Then call the function:

    countdown()
    

    Output:

    5
    4
    3
    2
    1