[英]Why time.sleep() delay doesn't work as intended inside the nested while loop?
有人可以解釋為什么以下代碼(用於打印乘法表) 未按預期工作嗎?
import time
n = int(input("Enter number of multiples: "))
k = int(input("Enter number of tables: "))
c = 1
m = 1 #multiple
while m <= n:
while c <= k:
print("%4d" % (c*m), end='')
c+=1
time.sleep(1) #slower behaviour
m+=1
c=1
print("")
奇怪的是,它不是以一秒鍾的間隔打印單個水平元素,而是以“ k”秒的間隔一次打印整個行。
實際上,用C編寫的代碼表現出相同的行為。
#include<stdio.h>
#include<unistd.h>
void main(){
int n,k,c=1,m=1;
printf("Enter number of Multiples: ");
scanf("%d",&n);
printf("Enter number of tables: ");
scanf("%d",&k);
while(m<=n){
while(c<=k){
printf("%4d",(c*m));
c+=1;
//sleep(1); //slower here
}
m+=1;
c=1;
sleep(1); //faster here
printf("\n");
}
}
也就是說,不是打印元素並等待一秒鍾,而是以“ k”秒的間隔一次打印了整行。
您告訴print跳過換行符,但是終端輸出是行緩沖的。 您需要刷新數據。
print("%4d" % (c*m), end='', flush=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.