P
P
programmer231452021-08-22 20:31:12
Python
programmer23145, 2021-08-22 20:31:12

How to constantly update the print?

I want to do something like digital time so that seconds, minutes and hours pass inside the program, and I can see this at the beginning of a line that should constantly update its data, well, I can’t do it.

import time
sec = 0
minutes = 0
hour = 0
print(sec, minutes, hour)
while True:
  sec+=1
  time.sleep(1)
  if sec == 60:
    minutes+=1
    
  if minutes == 60:
    hour+=1


what can be added here so that print is constantly updated, well, it’s supposed to be like on a computer or phone.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Nesterov, 2021-08-22
@AlexNest

import time
from os import system, name
def main():
    sec = 0
    minutes = 0
    hour = 0
    
    while True:
      hour_high = hour//10
      hour_low = hour%10

      min_high = minutes//10
      min_low = minutes%10

      sec_high = sec//10
      sec_low = sec%10

      timestring = f'{hour_high}{hour_low}:{min_high}{min_low}:{sec_high}{sec_low}'
      system('cls')
      print(timestring)  
      sec+=1
      time.sleep(1)
      if sec == 60:
        minutes+=1
        sec = 0
        
      if minutes == 60:
        hour+=1
        minutes = 0
      
if __name__ == '__main__':
    main()

V
Vindicar, 2021-08-23
@Vindicar

Here everyone suggests system("cls"), although it would be more practical to use the \x08 character.
A simple example to understand:

print('foobar', flush=True, end='') #немедленный вывод без перевода строки
print('\x08'*3, flush=True, end='') #отступаем на три символа назад
print('xyz', flush=True, end='') #на экране будет выведено fooxyz

But this technique only works if:
1. The data is displayed strictly in one line, and the cursor remains on it.
2. The length of the overwritten part of the string is known.
3. Only one value per screen needs to be updated this way.
Otherwise, you either use the cls trick, or generally spit on the terminal and make a GUI.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question