Python 覆盖结果的while循环
我正在编写简单的倒计时代码,并且很难覆盖时间。 结果以一行的形式出现(如00:00:0200:00:01),我希望它叠起来看起来像一个实际的时钟Python 覆盖结果的while循环,python,python-3.x,loops,while-loop,python-3.7,Python,Python 3.x,Loops,While Loop,Python 3.7,我正在编写简单的倒计时代码,并且很难覆盖时间。 结果以一行的形式出现(如00:00:0200:00:01),我希望它叠起来看起来像一个实际的时钟 print(time_left,end="") 下面是我所做的,我把\r作为 print("time_left + "\r", end="") 这不起作用 import time while True: uin = input(">> ") try: when_to_stop = abs(int(
print(time_left,end="")
下面是我所做的,我把\r
作为
print("time_left + "\r", end="")
这不起作用
import time
while True:
uin = input(">> ")
try:
when_to_stop = abs(int(uin))
except KeyboardInterrupt:
break
except:
print("Not a number!")
while when_to_stop > 0:
m, s = divmod(when_to_stop, 60)
h, m = divmod(m, 60)
#.zfill(2) to make 00:00:00 form
time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str(s).zfill(2)
print(time_left + '\r', + end="")
time.sleep(1)
when_to_stop -= 1
print()
你需要使用
print(time_left,end='\r')
end='\r'
将光标返回到行首。因此,当您再次打印相同的内容时,它会覆盖 我会在循环的同时重新编写(只是为了“美观”)。因此,您不需要使用break
。只需检查该值是否不为零,并仅在解析成功时设置该值
when_to_stop = 0
while(when_to_stop == 0):
uin = input(">> ")
try:
when_to_stop = abs(int(uin))
except:
print("Not a number!")
print(when_to_stop)
如果您使用IDLE,“\r”不起作用,您必须用其他东西打开您的程序,或者您也可以双击您的程序打开它而不进行编辑,您将看到覆盖。您好,谢谢您的评论!结果是00:00:03 00:00:02 00:00:01,这看起来不错,但并不完全是我想要的,我的意思是一行溢出自己