简体   繁体   English

为什么time.sleep()延迟在嵌套的while循环内无法正常工作?

[英]Why time.sleep() delay doesn't work as intended inside the nested while loop?

Can someone explain why the following code (to print multiplication table) is not working as intended ? 有人可以解释为什么以下代码(用于打印乘法表) 未按预期工作吗?

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("")

What's strange about this is that instead of printing single horizontal elements in intervals of one second, it is printing the entire row at once in an interval of 'k' seconds. 奇怪的是,它不是以一秒钟的间隔打印单个水平元素,而是以“ k”秒的间隔一次打印整个行。

In fact, code written in C showed the same behavior. 实际上,用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");
    }
}

That is, instead of printing an element and waiting for a second, it printed entire row at once in intervals of 'k' second(s). 也就是说,不是打印元素并等待一秒钟,而是以“ k”秒的间隔一次打印了整行。

You told print to skip the newline but terminal output is line buffered. 您告诉print跳过换行符,但是终端输出是行缓冲的。 You need to flush the data. 您需要刷新数据。

print("%4d" % (c*m), end='', flush=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM