-2

This is my code

for i in range(0,5):
        intl = i
        print(intl)
        intn = i+1
        print(intn)    
        i+=1
        print("---------")

What I am getting as the output is the following.

0
1
---------
1
2
---------
2
3
---------
3
4
---------
4
5
---------

Instead of that, I need to get;

0
1
---------
2
3
---------
4
5
---------
ForceBru
  • 43,482
  • 10
  • 63
  • 98
N-Sam
  • 17
  • 4
  • You're changing the value of i (which is set by the for loop) inside the for loop. That won't work. If you remove that line everything will work just the same way as before. – ScienceSnake Feb 04 '21 at 16:14

3 Answers3

1

Sorry I made a mistake. What you are looking for is the step parameter of range() like this:

for i in range(0,5,2):
        intl = i
        print(intl)
        intn = i+1
        print(intn)    
        print("---------") 

Now, for every loop it will skip one number (so i=0, then i=2, then i=4). When modifiying the variable i within a for loop, you will change the local version of i that is active in the current loop. Python doesn't actually use i to get the next item from a itterable, and thus manually changing it doesn't do anything for your loop.

JarroVGIT
  • 4,291
  • 1
  • 17
  • 29
  • No, I still get the same output.. :/ – N-Sam Feb 04 '21 at 16:22
  • But this is because the range is (0,6). This range will differ based on another variable. So I cant manually give the range. Instead, I'm substituting that variable for the range. If that's the case, this won't work. for i in range(gri_tables.n): intl = i – N-Sam Feb 04 '21 at 16:33
  • 1
    @PranavHosangadi fair point, I have changed my answer and gave some more explanation, apologies. – JarroVGIT Feb 04 '21 at 16:42
0

You can simply do this:

for i in range(0, 5, 2):
    intl = i
    intn = i+1
    print(intl)
    print(intn)    
    print("---------")

Now the range function has a step of 2. The step is the difference between each number. By default, it's 1.

for i in range(0, 5):
    print(i)

Returns:

0
1
2
3
4
for i in range(0, 5, 2):
    print(i)

Returns:

0
2
4

In your code, you did this:

i+=1

This doesn't work because the variable i is set by the for loop in each iteration. This means that no matter what you do with the i variable, in the next iteration it will be 1 more than last time.

Jaime Etxebarria
  • 560
  • 3
  • 14
-1

This code prints '-------' whenever the next value of i is divisible by 2.

x = 5

for i in range(0, x+1):
    print(i)
    if (i+1) % 2 == 0:
        print('---------')
ph140
  • 478
  • 3
  • 10
  • But this is because the range is (0,6). This range will differ based on another variable. So I cant manually give the range. Instead, I'm substituting that variable for the range. If that's the case, this won't work. for i in range(gri_tables.n): intl = i – N-Sam Feb 04 '21 at 16:31
  • well, if it differ based on a variable 'x' you can do, for i in range(0, x+1) – ph140 Feb 04 '21 at 16:32