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"
Some of the errors you made:
break
the loop on the first iterationif x == stop
can never be true because of the enclosing loop's termination condition while x > stop
stop
itself is never added to the outputThe 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'