Skip to content

Instantly share code, notes, and snippets.

@AnisahTiaraPratiwi
Created March 20, 2021 16:13
Show Gist options
  • Save AnisahTiaraPratiwi/ce0953ae2805384d01b47acc0366cc5a to your computer and use it in GitHub Desktop.
Save AnisahTiaraPratiwi/ce0953ae2805384d01b47acc0366cc5a to your computer and use it in GitHub Desktop.
The counter function counts down from start to stop when start is bigger than stop, and counts up from start to stop otherwise. Fill in the blanks to make this work correctly.
def counter(start, stop):
x = start
if start > stop:
return_string = "Counting down: "
while x >= stop:
return_string += str(x)
if x > stop:
return_string += ","
x -= 1
else:
return_string = "Counting up: "
while x <= stop:
return_string += str(x)
if x < stop:
return_string += ","
x += 1
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"
@Hiduser2
Copy link

def counter(start, stop):
x = start
if start > stop:
return_string = "Counting down: "
while x >= stop:
return_string += str(x)
if start != stop:
return_string += ","
x -= 1
else:
return_string = "Counting up: "
while x <= stop:
return_string += str(x)
if x != stop:
return_string += ","
x += 1
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"

@pylearner1007
Copy link

def counter(start, stop):
output = ""
if start > stop:
output += "Counting down: "
for i in range(start, stop-1, -1):
output += str(i) + ", "
else:
output += "Counting up: "
for i in range(start, stop+1):
output += str(i) + ", "
return output.rstrip(", ") # remove any trailing comma and space

print(counter(1, 10)) # Output: Counting up: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
print(counter(2, 1)) # Output: Counting down: 2, 1
print(counter(5, 5)) # Output: Counting up: 5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment