0
How can I write a python loop to count every other index?
I want to write a python code that outputs the following 1 2 3 4 I tried this: For I in range(2): Print(I, I+1) But this outputs 0 1 1 2 So it does not work for me. How can I fix the loop? The goal of this loop is to go 1000 times to generate those kind of numbers.
5 Antworten
+ 1
just in case you wanted to get a little fancier.
y = [{a, a+1} for a in range(1, 50, 2)]
print(y)
the code is a list comprehension that creates a set 1, 2 etc. and the range starts at 1 to 50 or any number you want and skips every other number.
you can change the set {} to a list [], tuple (), or just print.
y = [print(a, a+1) for a in range(1, 50, 2)]
+ 1
Yes loop counter should be incremented by 2 for each iteration 🤭
0
Andrew your solution will break every third index. If you run the code the answer will be [(1, 2), (3,4), (5,6) ,(8,7)] as you see the third index must be 7,8 not 8,7.
0
Karzan i didnt run into that problem when i ran the code. have you tried to run the code? if so, do you mind sharing it?
- 2
Actually I solved it:
for i in range(2):
if i % 2 ==0:
Print(i, i+1)
else:
print(i+1, i+2)