简体   繁体   中英

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.

In fact, code written in C showed the same behavior.

#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).

You told print to skip the newline but terminal output is line buffered. You need to flush the data.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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