loops breaks and returns

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • rbt

    #1

    loops breaks and returns

    Is it more appropriate to do this:

    while 1:
    if x:
    return x

    Or this:

    while 1:
    if x:
    break
    return x

    Or, does it matter?
  • Peter Hansen

    #2
    Re: loops breaks and returns

    rbt wrote:[color=blue]
    > Is it more appropriate to do this:
    >
    > while 1:
    > if x:
    > return x
    >
    > Or this:
    >
    > while 1:
    > if x:
    > break
    > return x[/color]

    The former would be considered bad style by some people. Others would
    consider it perfectly acceptable in a small function (say, no more than
    10-20 lines of code?) where it would be clear what's going on. Others
    would consider it fine in any case.

    If I really had a "while 1" loop with only the one exit condition, and
    an immediate return, I would definitely go with the former approach. If
    I had any other place where I was going to return, I'd consider the
    second approach more carefully.

    -Peter

    Comment

    • Sam Pointon

      #3
      Re: loops breaks and returns

      rbt wrote:[color=blue]
      > Is it more appropriate to do this:
      >
      > while 1:
      > if x:
      > return x
      >
      > Or this:
      >
      > while 1:
      > if x:
      > break
      > return x
      >
      > Or, does it matter?[/color]

      I would pick the first form if that's the only place where x would be
      returned from the function. However, if there would be redundant
      'return x'-es in the function because of this, then the second form
      becomes preferable. It's not set in stone, though - if you have a
      compelling reason to break the rule-of-thumb, do so.

      Comment

      Working...