loops breaks and returns

R

rbt

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?
 
P

Peter Hansen

rbt said:
Is it more appropriate to do this:

while 1:
if x:
return x

Or this:

while 1:
if x:
break
return x

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
 
S

Sam Pointon

rbt said:
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?

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top