Python Forum
Breaking While Loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Breaking While Loop (/thread-22048.html)



Breaking While Loop - JustWonderful - Oct-27-2019

Hello,

I have potentially eight sequential ifs I need to test for, so instead of nesting eight if statements I thought to use a while loop.
My goal is for the while loop to end once one of my functions returns a value greater than 0. Is there a better way to achieve this
than my method below?

x = 0

while x == 0:

x = function returning 0, 1, or 2
if x > 0:
break

x = function with different arguments returning 0, 1, or 2
if x > 0:
break

x = function with different arguments returning 0, 1, or 2
if x > 0:
break

x = function with different arguments returning 0, 1, or 2
if x > 0:
break

x = function with different arguments returning 0, 1, or 2
if x > 0:
break

x = function with different arguments returning 0, 1, or 2
if x > 0:
break

x = function with different arguments returning 0, 1, or 2
if x > 0:
break

x = function with different arguments returning 0, 1, or 2
if x > 0:
break

x = 3


RE: Breaking While Loop - jefsummers - Oct-27-2019

Youve abstracted this too much for me to help. Can you clarify the conditions you are testing?


RE: Breaking While Loop - JustWonderful - Oct-27-2019

(Oct-27-2019, 12:50 AM)jefsummers Wrote: Youve abstracted this too much for me to help. Can you clarify the conditions you are testing?

I'm trying to write what's below more concisely. I'm wondering if this can be achieved using a while loop.

if function(first_arg) > 0:
    x = function(first_arg)

elif function(second_arg) > 0:
    x = function(second_arg)

elif function(third_arg) > 0:
    x = function(third_arg)

# .
# .
# .

elif function(eighth_arg) > 0:
    x = function(eighth_arg)



RE: Breaking While Loop - perfringo - Oct-27-2019

If I understand correctly it can be done with for-loop:

lst = [0, -2, -5, 6, 8]

def my_func(num):
    return num

for item in lst:
    x = my_func(item)
    if x > 0:
        break
Of course one can have onliner fun as well:

next((item for item in lst if my_func(item) > 0))



RE: Breaking While Loop - JustWonderful - Oct-28-2019

Thank you!!