0

I want to print i and k till i is less than or equal to k. in C++ the code can be given as:

for(i=0;i<k;i++){
    cout<<i<<k;
    k--;
}

I am not getting the correct output.

this is my code

k=5
for i in range(k):
    print(i,k)
    k-=1

the output i get is:

0 5 
1 4 
2 3 
3 2 
4 1

but i want to get:

0 5
1 4
2 3

is there someway to use the range() function for this?

  • In python it works different than C. In C when you do `k--` the condition in the loop checks for the new value. In python once you did `range(k)` the range is calculated and changing `k` doesn't affect the loop anymore – Tomerikoo Jul 08 '19 at 11:08

2 Answers2

2

For loops in Python are really for-each and suboptimal for your needs. Use while instead:

i = 0; k = 5
while i < k:
    print(i,k)
    i += 1
    k -= 1
Jonas Byström
  • 25,316
  • 23
  • 100
  • 147
0
k=5
for i in range(k):
    print(i,k)
    if k<=i:
       break
    k-=1