python - 是否可以在这段代码中使用 "while something"而不是 "while True"?

标签 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”循环更好?

最佳答案

您可以使用 isinstance根据@Enzo

的建议,检查 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

关于python - 是否可以在这段代码中使用 "while something"而不是 "while True"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56687774/

相关文章:

python - 使用 Pandas 数据框中的值注释热图

python - MySQLdb executemany 使用列表作为输入?

java - 如何在Jython中减少声音?

c++ - 由围绕矩形顺时针方向移动的数字组成的图案(长度和宽度每次都减小)

javascript - 停止 ng-repeat 然后恢复它

javascript - 在打印窗口处于事件状态时打开 PDF 链接

python - sqlite python,嵌套循环停止主循环

带有通配符和隐藏文件的 Bash for 循环

ruby-on-rails - awesome_print 未显示关联对象

java - 打印 Java 数组的最简单方法是什么?