[英]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.我正在为uni做一个小程序,在设计算法时遇到了一个疑问。 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)该程序使用 Python 编写,但我对通用的非特定于语言的解决方案感兴趣,因为我通常练习 Java 和 C++(尽管我知道每种语言在内部的工作方式略有不同)
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.然而,在这种情况下,条件 2 的值在 (...) 代码块的 while 循环中被修改,因此唯一重要的是在循环结束时它是真还是假。
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.这 2 条语句是不等价的。 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.在条件 2 变为 = False 且条件 1 = True 的情况下,您的第一个循环将在 while 检查后立即通过,第二个循环将执行循环体,并且仅在此之后退出。 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.当 cond1 为真且 cond2 为假时,您建议的 while-if 版本失败:在这种情况下,它会在退出前执行一次代码块。
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.将运算符 ( and
) 留在行尾有助于读者了解语句尚未完成。 Your mileage may vary.你的旅费可能会改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.