我在网上的几页上读到,使用“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/