Search code examples
python-3.xwhile-loopcounter

Counter up or down script not working python


I'm trying to create a script that counts up if start < stop or count down is start < stop. I'm getting part of the output but not all. Any tips?

def counter(start, stop):
x = start
if x > stop:
    return_string = "Counting down: "
    while x > stop:
        return_string += str(x)
        if x == stop:
            return_string += ","
        return return_string
else:
    return_string = "Counting up: "
    while x <= stop:
        return_string += str(x)
        if x == stop:
            return_string += ","
        break
return return_string
         print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
         print(counter(2, 1)) # Should be "Counting down: 2,1"
         print(counter(5, 5)) # Should be "Counting up: 5"

Solution

  • Some of the errors you made:

    1. You already break the loop on the first iteration
    2. You add the comma only when you reach stop which is exactly when no comma is needed anymore
    3. that if x == stop can never be true because of the enclosing loop's termination condition while x > stop
    4. For the same reason, stop itself is never added to the output

    The following changes will fix your function:

    def counter(start, stop):
        x = start
        if x > stop:
            return_string = "Counting down: "
            while x > stop:
                return_string += str(x)+","
                x -= 1
        else:
            return_string = "Counting up: "
            while x < stop:
                return_string += str(x)+","
                x += 1
        return_string += str(stop)
        return return_string
    
    >>> counter(1,2)
    'Counting up: 1,2'
    >>> counter(1,5)
    'Counting up: 1,2,3,4,5'
    >>> counter(5,1)
    'Counting down: 5,4,3,2,1'
    >>> counter(5,2)
    'Counting down: 5,4,3,2'