下面是一段困扰我一段时间的 Python 代码。
var=0
while (var <1 or var>100):
var=raw_input('Enter the block number ')
if (var >=1 and var<=100):
print '\nBlock Number : ',var
else:
print 'ERROR!!! Enter again.'
问题是 while 循环不断迭代而不中断。任何人都可以帮助我如何打破循环。
有什么方法可以在 Python 中实现 do..while 吗?
最佳答案
问题是 raw_input
返回一个字符串。你正在比较一个字符串和一个整数,你可以在 python 2.x 中这样做(在 python 3 中,这种比较会引发 TypeError
),但结果显然总是 False
。要完成这项工作,您可能需要像 var=int(raw_input('Enter the block number'))
来自documentation :
objects of different types always compare unequal, and are ordered consistently but arbitrarily.
关于python - 虽然循环没有中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11543454/