如何在 while 循环中只打印最后一行
How to print only last line in a 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
如何让循环只打印最后一行?
您可以保存要打印的字符串并在 循环后打印它:
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
使用 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_
时,打印并中断。
你可以试试这个:
count = 0
while count < 4:
print('hi')
count += 1
else:
# Replace below string with what you wish.
print('end')
+=
表示count + 1
。 else
在 while
完成后达到(不会打印,如果你 break
循环而不是让它正常完成)。
count = 0
while count ** 2 < snum_:
print "Using search with increment 1, the root lies between", count,"and", count + 1
count = count + 1
如何让循环只打印最后一行?
您可以保存要打印的字符串并在 循环后打印它:
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
使用 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_
时,打印并中断。
你可以试试这个:
count = 0
while count < 4:
print('hi')
count += 1
else:
# Replace below string with what you wish.
print('end')
+=
表示count + 1
。 else
在 while
完成后达到(不会打印,如果你 break
循环而不是让它正常完成)。