Home > Software engineering >  python - start from a number and then subtract x in a for
python - start from a number and then subtract x in a for

Time:08-27

I have a code like this

for x in range(1,20):
    print(x)

it works perfectly, but when I want to start from the end like => 60 to 1 i tried this first

for x in range(20,1):
    print(x)

but it prints nothing! also, I tried this,

for x in range(1,20):
    count = 20
    count -= 1
    print(count)

but -= 1 only printed twenty samples of 19. any help?

CodePudding user response:

First answer: Use range() built-in function whit negative step:

for x in range(20, 1, -1):
    print(x)

Second answer: You have to declare the count variable outside the for loop, otherwise it will be initialized to 20 each loop, and then subtracting 1 will always make 19 for each loop.

count = 20
for x in range(1,20):
    count -= 1
    print(count)

CodePudding user response:

@Massifox already pointed out the -1 step but I can add more context. The optional third parameter in range() is step. If you did range(1, 20, 2) it would print 2, 4, 6, ..., 18 because you specified steps of 2.

For your example, you started 20, and incremented until you hit 1, but that will never happen, so nothing gets printed, so you specify a step of -1 like range(20, 1, -1), so that it will step backwards each iteration printing 20, 19, ..., 2 (second parameter is exclusive).

When you tried this

for x in range(1,20):
    count = 20
    count -= 1
    print(count)

You created a temp variable named count, initialized to 20, subtracted one from it, and then printed it, and the result was the 19's you were getting. Everything inside the for loop will be a temporary variable and cannot affect the iteration of the for loop. LMK if this is too verbose.

  • Related