Decreasing sequence
The function in Listing 1 builds a string from the values visited by a for loop.
for loop with a step of -2 (Question 1).
What does mysterious_loop return for n = 0, n = 1, n = 5, and n = 6? Each visited number is followed by one space.
- n = 0:
""/ n = 1:"1 "/ n = 5:"5 3 1 "/ n = 6:"6 4 2 ". - n = 0:
"0 "/ n = 1:"1 "/ n = 5:"5 3 1 -1 "/ n = 6:"6 4 2 0 ". - n = 0:
""/ n = 1:"1 "/ n = 5:"5 3 1 -1 "/ n = 6:"6 4 2 0 ". - n = 0:
""/ n = 1:"1 "/ n = 5:"5 4 3 2 1"/ n = 6:"6 4 2 0 ".
TipHint
range(start, stop, step)supplies integers fromstarttoward, but excluding,stop.stepdefaults to1, andrange(stop)starts at0.list(range(2, 7, 2))is[2, 4, 6];list(range(5, 1, -2))is[5, 3].- A range is empty when the step cannot reach the stop; a zero step raises
ValueError.
listcollects the supplied values in a new list.str(value)returns the value as text, without changing it.str(8)is"8"andstr(2.5)is"2.5"; an existing string remains the same text.