0

How many loops will the following for loop have?

for i in range(1, 5, 2):
     print(i, end=" ")

I know that the output is "1 3", but I'm not exactly certain how it goes through, if it loops for each. My gut wants to say 2 loops.

  1. 1, skip 2

  2. 3, skip 4 and reach end of range.

Is this correct thinking?

5
  • 2
    Divide the number of elements in the sequential range by 2. Commented Mar 4, 2024 at 21:13
  • And round up if there's a fraction. Commented Mar 4, 2024 at 21:14
  • Don't think of it in terms of skipping numbers. The last argument to range() is the amount that's added to each element to get the next one. So start with 1, next is 1+2, next is 1+2+2, and so on until you reach 5 or more. Commented Mar 4, 2024 at 21:16
  • Divide number of elements by 2... so that'd be 4 elements / 2 = 2? The 4 elements being 1, 2, 3, 4. "and so on until you reach 5 or more" but 5 is the stopping number, so 4 is the last number that counts... no? Commented Mar 4, 2024 at 21:34
  • Right. ceil((5-1)/2) == 2 Commented Mar 4, 2024 at 21:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.