在这段代码中是否可以使用“ while something”而不是“ while True”?

时间:2019-06-20 14:05:42

标签: python loops printing while-loop try-catch

我已经在线阅读了几页,使用“ while True”并用“ break”手动中断while循环是一个不好的做法。在这种情况下,我不想使用“ while True”,我想知道是否有可能。

while True:
    x = input()
    try:
        x = float(x)
        break
    except ValueError:
        continue

我尝试这样做:

while x is not float:
    x = input()
    try:
        x = float(x)
    except ValueError:
        continue

但是循环永远不会中断。 是否有可能的解决方案,还是将其保留为“ while True”循环更好?

3 个答案:

答案 0 :(得分:1)

根据@Enzo的建议,您可以使用isinstance来检查x是否是float的实例

#Define x as None here
x = None

#Run loop until you find x which is a float
while not isinstance(x, float):
    x = input()
    try:
        #If x can be cast to a float, the loop will break
        x = float(x)
    except ValueError:
        continue

答案 1 :(得分:1)

如果这是整个循环,则使用break并没有太大问题。您应尽量避免使用break的主要原因是因为它可能会使较大的循环或内部分支较多的循环(if等)难以遵循。

我认为Python没有做到这一点的简单方法,因此使用break进行简单循环很有效。其他答案中建议的解决方案(使用x的占位符值)也可以,但我个人认为它的可读性较差。

答案 2 :(得分:1)

PEP 315中,我们有以下声明:

  

在适当的do-while循环时,建议该语言的用户使用带内部if中断的while-True形式。

此语句引用PEP 315的这一部分:

  

随后在2009年4月恢复PEP的努力并未取得成功,因为没有出现可以与以下形式竞争的语法:

while True:
    <setup code>
    if not <condition>:
        break
    <loop body>

您没有引用消息来源声称这是“不良做法”,但是来自PEP 315的这些摘录与它们矛盾。