Python Forum

Full Version: Breaking While Loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
Youve abstracted this too much for me to help. Can you clarify the conditions you are testing?
(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)
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))
Thank you!!