Range in For-loop Python

Question:


for i in range(4,7):
    i=i+3
    print("Hello")

Kindly help me with the well explained output for this program.

Asked By: Rahul.S

||

Answers:

This code uses a for loop to iterate over the numbers in the range 4 to 7 (inclusive). For each number i in the loop, it adds 3 to i and then prints the string "Hello".

Here is how the code will execute:

  1. The for loop starts with i=4.
  2. i is incremented by 3, so i=7.
  3. The string "Hello" is printed.
  4. The for loop continues with i=5.
  5. i is incremented by 3, so i=8.
  6. The string "Hello" is printed.
  7. The for loop continues with i=6.
  8. i is incremented by 3, so i=9.
  9. The string "Hello" is printed.
  10. The for loop ends because all numbers in the range 4 to 7 have been processed.

Therefore, this code will print the string "Hello" three times.

Note that the assignment of the variable i inside the loop does not make sense because at each iteration of the loop, the variable i is updated

Answered By: Pingu

It is going to print Hello three times.

In every loop it will set the value of loop counter to loop counter + 3.
And then print Hello. But after every iteration the loop counter will be overwritten by the for loop.

So i=i+3 is redundant.

Answered By: Harsh
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.