I have code like this:
loopcount = 3 for i in range(1, loopcount) somestring = '7' newcount = int(somestring) loopcount = newcount
so what I want is to modify the range of the for 'inside' the loop.
I wrote this code expecting the range of the for loop would change to (1,7) during the first loop, but it didn't happen.
Instead, no matter what number I put in, it only runs 2 times. (I want 6 times.. in this case)
I checked the value using print like this:
loopcount = 3 for i in range(1, loopcount) print loopcount somestring = '7' newcount = int(somestring) loopcount = newcount print loopcount #output: 3 7 7 7
What is wrong? the number has been changed.
Where is my thinking wrong?
Yes, it is possible to change the range from inside the loop, see the new answer below.
To count iterations we can use the Python enumerate() function and pass it in as the first argument of the for loop.
The general rule of thumb is that you don't modify a collection/array/list while iterating over it. Use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.
Python iter() is an inbuilt function that is used to convert an iterable to an iterator. It offers another way to iterate the container i.e access its elements. iter() uses next() for obtaining values. The iter() method returns the iterator for the provided object.
The range is created based on the value of loopcount
at the time it is called--anything that happens to loopcount afterwards is irrelevant. What you probably want is a while statement:
loopcount = 3 i = 1 while i < loopcount: somestring = '7' loopcount = int(somestring) i += 1
The while
tests that the condition i < loopcount
is true, and if true, if runs the statements that it contains. In this case, on each pass through the loop, i is increased by 1. Since loopcount is set to 7 on the first time through, the loop will run six times, for i = 1,2,3,4,5 and 6.
Once the condition is false, when i = 7
, the while loop ceases to run.
(I don't know what your actual use case is, but you may not need to assign newcount, so I removed that).
From the range()
docstring:
range([start,] stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements.
So, range(1, 10)
, for example, returns a list like: [1,2,3,4,5,6,7,8,9]
, so, your code is basically doing:
loopcount = 3 for i in [1, 2]: somestring = '7' newcount = int(somestring) loopcount = newcount
When your for
loop is "initialized", the list is created by range()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With