I am trying to write a simple countdown timer and for some reason, when I run the script it hangs up and does nothing.
# countdown one minute
import time
countdown = 60
while countdown > 0:
print(str(countdown), end=' ')
countdown -= 1
time.sleep(1)
The problem has something to do with the sleep function, although I’m not sure why. If I comment out that line, the loop prints out all the numbers. Also if I step through the code with the debugger (VSCode), the countdown works as expected. But when I simply run the script in the terminal, nothing happens. Very confused. I am running Python 3.9.1 on Manjaro Linux, just in case that’s of any consequence.
Well, this is bizarre. @moriel as you mentioned, it does work in IDLE. However, it seems like that’s the only place it will work as written. As @SixStringsCoder points out the problem might be with the print statement.
When the code I posted is executed from a script in the terminal, I get nothing. When run with Python shell in the terminal, again nothing happens.
Using print(str(countdown)) and print(countdown) are the only ways I can get my counter to work in the terminal. I guess the end=' ' keyword arg is the problem… Strange. Also kinda sucks because I didn’t want each number to print on its own line.
Here’s some more strangeness. I lowered the countdown int to 10, so I wouldn’t have to wait too long to see what happens. And exactly 10 seconds later, the shell spits out all 10 numbers at once.
So, it is doing the count-down… It just doesn’t print anything until after the loop exits. It works as expected in IDLE, and when stepping through with VSCode… Just not in the terminal when executed from a script file or in the shell. I tried it in 2 different terminal emulators to see if that was the problem but the result is the same.
last time i tested with python 3.8 and it worked.
Now I just have installed python 3.9 and you are right! I does not work. I do not know if it is a bug. We will see!
However I have inserted your code in a function with count as a parameter and called it and it works. I think here you first have to import time if you want to use sleep()!
Yep, i had that same problem. It would just hang for the amount of time indicated (i.e. 10 seconds for counting to 10) then everything gets pooped out at once. Strange behavior indeed. I did it with Python in the terminal and also made a small python script and ran it that way, too. It only worked after I got rid of the end parameter, which again, seems odd.
@sanity has restored my sanity. the flush=True argument fixed the problem. I will have to pay a visit to the documentation to learn more about it. Thanks!
It was only when you mentioned that everything was printed all at once, I remembered reading about some weird behavior with print that can be dealt with using optional argument.