Is another loop required to print the reverse with different conditions?

Question:

I have the following program that prints even numbers in a provided range. However, I’d like to make it so that if the second number is smaller than the 1st number, e.g. end < start, then print the even numbers but in reverse order.

I’m thinking we would need two separate loops for each condition based on what I have here, but is there a much more simplistic way to accomplish this?

start = int (input("1st number: "))
end = int (input("2nd number: "))

for num in range(start, end + 1):
    if num % 2 == 0 and start < end:
        print (num, end = " ")
    #elif num % 2 == 0 and end > start:
        #print (num, end = " ")
Asked By: Cataster

||

Answers:

you just need to compute range direction first (and no need to test for even/odd property, just use a step of 2 or -2 depending on the direction)

start = 20
end = 30

# uncomment to swap start & end
#start,end = end,start

# compute direction. 2 or -2
direction = 2 if (end-start)>0 else -2

# add direction to end works in both directions
for num in range(start, end + direction,direction):
    print(num,end=" ")

prints:

20 22 24 26 28 30 

now if you swap start and end it prints:

30 28 26 24 22 20 

you just need to invert the range order to achieve what you want:

start = int (input("1st number: "))                                                                                                                                                                                                                           
end = int (input("2nd number: "))

rng = range(start, end + 1) if start < end else range(start, end -1, -1)
for num in rng:
    if num % 2 == 0:
        print (num, end = " ")

The rng = range(start, end + 1) if start < end else range(start, end -1, -1) does all the magic:

1st number: 10
2nd number: 1
10 8 6 4 2
1st number: 1
2nd number: 10
2 4 6 8 10 
Answered By: Alberto Garcia

Some workaround of others’ answers:

print(*[n for n in (range(start,end+1), range(start,end-1,-1))[start>end] if not n % 2])
Answered By: Arifa Chan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.