Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 = " ")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading