Code Examples

Counter

programming

The following code in Python, takes two numbers in parameters: start and stop.
It counts down from start to stop when start is bigger than stop.
And counts up from start to stop otherwise.

def counter(start, stop):
    x = start
    msg = ""
    
    if start == stop:
        msg = str(start)    
    elif start > stop:
        msg = "Counting down: "
        while x >= stop:
            msg += str(x)
            if x > stop:
                msg += ","
            x-=1
    else:
        msg = "Counting up: "
        while x <= stop:
            msg += str(x)
            if x < stop:
                msg += ","
            x+=1
    return msg

#Test cases
print(counter(1, 10)) # Must be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2, 1)) # Must be "Counting down: 2,1"
print(counter(5, 5)) # Must be "5"