简体   繁体   中英

While with 2 conditions or 1 condition and if check?

I was making a small program for uni and came to a doubt while designing the algorithm. The program is in Python but I'd be interested on a general non-language-specific solution because I usually practice Java and C++ (though I know every language works slightly different internally)

The question is whether to use either of these loops

while condition 1 and condition 2
    (...)

Or use instead

while condition 1
    (...)
    if condition 2
        quit loop

Thanks for your help, all replies are appreciated!

[ EDIT ]

As all of you have stated, the code is not logically equivalent as I presented it. However, it is on my case scenario. It is good that you pointed it out though because in other cases it will be something to take into account. In this case, however, the value of condition 2 is modified within the while loop on the (...) code block, hence why the only thing that matters is whether in the end of the loop it is true or false.

Anyway, thanks for the explanation and those who advised me to use just the clearest one, it's clarified for me now :)

These 2 statements are not equivalent. In the situation when condition 2 becomes = False and condition 1 = True, your first loop will pass over right after the while's check, and the second one will exec the body of loop and only after that quit. So, i guess choice depends on the aim of that code block.

The two are not equivalent . The equivalent form could be

while cond1
    if not cond2
        quit loop
    <code block>

Your proposed while-if version fails when cond1 is true and cond2 is false: In that case, it executes the code block once before exiting.

Which to use? Use the version that is easier to read and maintain. This is generally the two-condition version, nicely formatted, such as

while cond1 and
      cond2
   <code block>

Leaving the operator ( and ) at the end of the line helps the reader know the statement isn't finished. Your mileage may vary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM