如何在while循环中仅打印最后一行

时间:2015-01-31 17:38:07

标签: python-2.7 while-loop

count = 0

while count ** 2 < snum_:
    print "Using search with increment 1, the root lies between", count,"and", count + 1
    count = count + 1

如何让循环只打印最后一行?

3 个答案:

答案 0 :(得分:0)

您可以保存要打印的字符串,然后循环之后将其打印出来:

count = 0
result = ''

while count ** 2 < snum_:
    result = "Using search with increment 1, the root lies between %d and %d" % count, count + 1
    count = count + 1

print result

答案 1 :(得分:0)

使用for循环和itertools.count()

import itertools
for count in itertools.count(1):
    if count**2 >= snum_:
        print "Using search with increment 1, the root lies between %d and %d" % count-1, count
        break

但是一般的想法也可以应用于你的while循环:当count**2 不再小于snum_时,打印并中断。

答案 2 :(得分:0)

你可以试试这个:

count = 0

while count < 4:
    print('hi')
    count += 1
else:
    # Replace below string with what you wish.
    print('end')

+=表示count + 1。在else完成后达到while(如果您break循环而不是让它正常完成,则不会打印。