0

I'm writing a program that needs to run a for loop then either return a string or runs the next for loop. I made it so that when it returns something a variable changes and the next loop doesn't run. It works fine but I feel there is a better way to do it.

check=0
    if check==0:
        for j in range (0,10):
            if something happens:
                check=1
                return('string')
    if check==0:
        for j in range (0,7):
            if something happens:
                check=1
                return('string')
michael
  • 37
  • 3

1 Answers1

0

Assuming the two if something happens checks are checking different conditions and the two returns are different strings:

for j in range(10):
   if something_happens:
      return 'string'

for j in range(7):   
   if some_other_thing_happens:
      return 'some other string'

As Daniel Mesejo said, return will "return" from the function and skip the code beneath it, so you don't need the check variable. You can't directly combine the loops because the first check may evaluate to False until j>=8, but the second check may pass and return prior to this, changing your logic.

If the checks to something happens are the same and the return values are both the same, you can simplify to just:

for j in range(10):
   if something_happens:
      return 'string'

Though, depending on what something_happens actually does, you may need to loop on range(18) instead. Hard to say without knowing what gets evaluated in the conditional.

See this for further understanding on return