4.8k views
1 vote
5.

Question 5
Fill in the blanks to complete the “countdown” function. This function should begin at the “start” variable, which is an integer that is passed to the function, and count down to 0. Complete the code so that a function call like “countdown(2)” will return the numbers “2,1,0”.

def countdown(start):
x = start
if x > 0:
return_string = "Counting down to 0: "
while ___ # Complete the while loop
___ # Add the numbers to the "return_string"
if x > 0:
return_string += ","
___ # Decrement the appropriate variable
else:
return_string = "Cannot count down to 0"
return return_string


print(countdown(10)) # Should be "Counting down to 0: 10,9,8,7,6,5,4,3,2,1,0"
print(countdown(2)) # Should be "Counting down to 0: 2,1,0"
print(countdown(0)) # Should be "Cannot count down to 0"

1 Answer

5 votes

Answer:

def countdown(start):

x = start

if x > 0:

return_string = "Counting down to 0: "

while x >= 0: # Complete the while loop

return_string += str(x) # Add the numbers to the "return_string"

if x > 0:

return_string += ","

x -= 1 # Decrement the appropriate variable

else:

return_string = "Cannot count down to 0"

return return_string

print(countdown(10)) # Should be "Counting down to 0: 10,9,8,7,6,5,4,3,2,1,0"

print(countdown(2)) # Should be "Counting down to 0: 2,1,0"

print(countdown(0)) # Should be "Cannot count down to 0"

In the while loop, the condition should be x >= 0 to ensure that the loop continues until the countdown reaches 0. Inside the loop, the current number being counted down should be added to the return_string. The if statement with the comma is used to separate the numbers in the string, except for the last number, which should not have a comma. Finally, x is decremented by 1 at the end of each loop iteration to ensure that the countdown proceeds correctly. If the start variable is less than or equal to 0, the function returns the string "Cannot count down to 0".

User RunDOSrun
by
8.6k points