Search code examples
pythonpython-3.xwhile-loop

How do I get - the last element only - of a While Loop in python?


The problem is I get all the elements in the while loop instead of the final result. Anyone knows how do I get python to insert the last element only in the terminal?

I've tried to insert the result of the following loop: subtracting 6 from 74, 42 times. The result should be -178 which I get using this code:

i = 74
while i > -180:
    print(i)
    i = i - 6

I want the result printed in one element (last element) instead of all the numbers leading to -178.


Solution

  • i = 74
    step = 6
    while True:
        i = i - step
        if i <= -180:
            i = i + step
            break
    
    print(i) # prints(-178)
    

    you can check in if its less than -180 as well.