Home > OS >  How to make alternating 'for' loop?
How to make alternating 'for' loop?

Time:05-21

How do i make alternating step for a 'for' loop? i.e number sequence (-1,2,-3,4,-5)

I know how to make all negative which is

n=int(input())
for i in range (1,n 1):
    i=i*(-1)
    print(i)

im sure there's a better way to do it, but how do i make a 2nd step on for the n=2,4,6... ? putting another i=i*(-1) makes it all again

CodePudding user response:

n=int(input())
for i in range (1,n 1):
  if i%2!=0:
    i=i*(-1)
  print(i)

CodePudding user response:

You can add a condition that checks for even/odd numbers:

for i in range(1, n 1):
    if i%2 == 0:
        print(i)
    else:
        print(-i)

It is not a good practice to change the loop iterator (i in this case) inside the loop, so if you need to store that value and not just print it, save it inside a second variable.

CodePudding user response:

You could introduce a parity check, i.e. check whether the value of i of the current interation is even or odd. This can be achieved using the modulo operator %.

n = int(input())
for i in range(1, n 1):
  if i % 2 == 0:
    print(i)
  else:
    print(-i)

CodePudding user response:

Use math odd numbers are negative, -1 to power of a odd number is -1 so we multiply odd numbers by (-1)^i same way for even numbers because -1 to power of even is 1 so generally in our case each number from <1, 2, 3, 4, ...> maps to <-1, 2, -3, 4, ...>

>>> for i in range(1, n   1):
...     j = i * (-1)**i
...     print(j)
... 
-1
2
-3
4
-5 

CodePudding user response:

Raising -1 to odd powers for -1 and even powers for 1 is how I'd do it. Depends on if you want "odd numbers negative" or "first third fifth numbers" negative.

You could also just maintain a "flip":

flip = -1  # first number will be negative; make it 1 for first number postive
for i in range(1, n 1):
    print(i * flip)
    flip *= -1

# output:
-1
2
-3
4
-5

You can use itertools.cycle() with list of [-1, 1] and zip it with your range.

  • Related