Reputation:
Im having a issue when programming. Im trying to use sleep() in the print(). The input is:
print(f'New year in 5{sleep(1)}.4{sleep(1)}.3{sleep(1)}.2{sleep(1)}.1{sleep(1)}. NEW YEAR!')
And the output is:
New year in 5None.4None.3None.2None.1None. NEW YEAR!
And the delay happens before print in the screen. Im using the last version of python. I'll be waiting for answers.
Upvotes: 2
Views: 2144
Reputation: 11
Try using time.sleep(1)
(with module dot prefixed) instead of just sleep(1)
.
If you are just calling sleep(1)
your script will search for a locally defined function instead of the function defined in module time.
Upvotes: 1
Reputation: 119
Your code did not work as you expected because all objects passed to the print function are resolved and printed in one go.
Hence when you passed multiple sleep() they were all compiled and there was an initial wait and finally your message was printed..
And the None in your result was the return of time.sleep() function
Solution: Implement a countdown function Make sure that you print to the same line everytime, only change will be the time. This is achieved by using '\r' and end="" in python3 print function
But there is one small issue where te number of digits in you time reduces by one which can be handled by replacing the existing printed line with all white spaces
#!/usr/bin/python3
import time
def countdown(start):
while start > 0:
msg = "New year starts in: {} seconds".format(start)
print(msg, '\r', end="")
time.sleep(1)
# below two lines is to replace the printed line with white spaces
# this is required for the case when the number of digits in timer reduces by 1 i.e. from
# 10 secs to 9 secs, if we dont do this there will be extra prints at the end of the printed line
# as the number of chars in the newly printed line is less than the previous
remove_msg = ' ' * len(msg)
print( remove_msg, '\r', end="")
# decrement timer by 1 second
start -= 1
print("Happy New Year!!")
return
if __name__ == '__main__':
countdown(10)
Upvotes: 0
Reputation: 599
Print can be called with a end
attribute. The default value is a linebreak but you can choose to just put a space.
print('New year in 5', end=' ')
so the next thing you print will be on the same line.
This allow you to moove the sleep function outside of print.
print('New year in 5', end=' ')
sleep(1)
print('4', end=' ')
sleep(1)
print('3', end=' ')
# ...
Upvotes: 0