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

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

Im thinking we would need 2 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 = " ")

>Solution :

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 

Leave a Reply