199k views
5 votes
The loop function is similar to range(), but handles the parameters somewhat differently: it takes in 3 parameters: the starting point, the stopping point, and the increment step. When the starting point is greater than the stopping point, it forces the steps to be negative. When, instead, the starting point is less than the stopping point, it forces the step to be positive. Also, if the step is 0, it changes to 1 or -1. The result is returned as a one-line, space-separated string of numbers. For example, loop(11,2,3) should return 11 8 5 and loop(1,5,0) should return 1 2 3 4. Fill in the missing parts to make that happen.

User JAL
by
4.4k points

2 Answers

2 votes

Answer:

def loop(start, stop, step):

return_string = ""

if step == 0:

step = 1

if start > stop:

step = abs(step) * -1

else:

step = abs(step)

for j in range(start, stop, step):

return_string += str(j) + " "

return return_string

print(loop(11, 2, 3))

print(loop(1, 5, 0))

Step-by-step explanation:

- Create a function called loop that takes three parameters: a starting point, a stopping point, and a step

- Initialize an array to hold the return values of the loop

- If the step equals 0, assign it to 1

- If the starting point is greater than the stopping point, take the absolute value of the step and multiply with -1

- If the starting point is not greater than the stopping point, take the absolute value of the step and multiply with 1

Until here you specified the starting point, stopping point and the step

- Create a for loop that iterates through starting point to the stopping point with the value of the step

- Add the numbers that are in the range to the return_string

- Return return_string

- Call the function to test the given scenarios

User Texh
by
4.4k points
3 votes

Answer and Explanation:

def loop(start, stop, step):

return_string = ""

if step == 0:

step = 1

if start > stop: # the bug was here, fixed it

step = abs(step) * -1

else:

step = abs(step)

for count in range(start, stop, step):

return_string += str(count) + " "

return return_string.strip()

User Stuart Cook
by
4.3k points