Python Forum
Change the varaible in For Loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Change the varaible in For Loop (/thread-34614.html)



Change the varaible in For Loop - quest - Aug-13-2021

Hello,
I have a very simple problem:
I am trying to increase the i in for loop like that:
1 2
4 5
3 4
6 7
5 6
8 9
One step I am increasing the i with +3 and the other step I am decreasing the i with -1
for i in range(1,number_of_qubit-2):
       print(i,i+1)
       i=i+3
       print(i,i+1)
       i=i-1
However I am getting this result:
1 2
4 5
2 3
5 6
3 4
6 7
4 5
7 8
Why am I seeing 2 and 3 instead of 4 and 5 ? How can I fix this problem


RE: Change the varaible in For Loop - perfringo - Aug-13-2021

Did you know that Python comes with built-in help?

Quote:Why am I seeing 2 and 3 instead of 4 and 5 ?


>>> help('for')
The "for" statement
*******************

The "for" statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:
/.../
The for-loop makes assignments to the variables(s) in the target list.
This overwrites all previous assignments to those variables including
those made in the suite of the for-loop:

   for i in range(10):
       print(i)
       i = 5             # this will not affect the for-loop
                         # because i will be overwritten with the next
                         # index in the range
How to overcome? Maybe something like this:

>>> for i, j in enumerate(range(1, 4)):
...     print(i+j, i+j+1)
...     print(i+j+3, i+j+4)
...
1 2
4 5
3 4
6 7
5 6
8 9



RE: Change the varaible in For Loop - deanhystad - Aug-13-2021

range() is a generator. i is a variable that you are using to reference the value returned by the generator. The generator doesn't know anything at all about i, and changing i has no effect on the generator. You don't even need i for the generator to work.
for _ in range(5):  # Look Ma, no index!
    print('Hello')
This prints 'Hello' five times.

A while loop does a comparison, so changing the index value does have ah effect. This should work.
i = 0
while i < number_of_qubit-2:
       print(i,i+1)
       i=i+3
       print(i,i+1)
       i=i-1