How to change numbers in the same execution line in Python?

Hello I'm new to programming and was doing a countdown program in python. I made the code and it worked, but then I looked at the program running and the same using several lines just to change the number....Would it be possible to make it only change the number of the count, without appearing several lines in the execution?

Here's my code, I hope you understand what I meant...

from time import sleep

for c in range (10,0,-1):
    print('Aguarde, seu programa vai começar em ',end='')
    if c > 1:
        print(f'{c}',end='')
        if c==10:
            print(' segundos',end='')
        else:
            print('  segundos',end='')
    if c == 1:
        print(f'{c}',end='')
        print('  segundo ',end='')

    for i in range (0,3):
        if c == 0:
            break
        print(' .',end='')
        sleep(0.33)
    print('')

print('Seu programa esta rodando!')
Author: jsbueno, 2019-05-30

1 answers

The terminal where print displays its content is a special program that can have several capabilities - they are activated depending on control codes that you send inside the print string itself.

So, for example, to print color text, several terminals, but not the standard Windows terminal accept sequences of type <ESC>[...m - they are called ANSI sequences, (to print the ESC code, in a Python string we use its ASCII code in hexadecimal, with the sequence \x1b.

These ANSI sequences include commands to reposition the cursor anywhere on the terminal screen - you choose the row and column where you want to print. Here is the reasonably complete documentation, as well as the history, of these sequences: https://en.wikipedia.org/wiki/ANSI_escape_code

Microsoft has promised for this year a new terminal in Windows 10, which should replace the cmd that should have these sequences by default. Meanwhile, you can use a program called" cmder "which is a Unix terminal experience on Windows - or the third-party library" colorama " to enable ANSI sequences on cmd.

However, there is a simpler string, which works even on terminals that are with the ANSI strings disabled, which is the backspacs character - Python has the special encoding \b for the same that can be used in strings.

In addition to this sequence, it is important to customize the call to print to (1), it does not send the "\n" when finished printing and (2) does not wait for the "\N" to update the contents of the line - these two things are done by passing the parameters end="", flush=True to the print.

So try this example:

import time

print("Contagem regressiva")
for i in range(10, -1, -1):
    print(f"\b\b\b{i} ", end="", flush=True)
    time.sleep(0.5)

In case the 3 "\ b "make the cursor go back 3 positions (if it reaches the column 0 it stops), and the space ""after the" {I}", ensures that it clears the second digit (The 0 of 10), when the count becomes of single digit.

 3
Author: jsbueno, 2019-05-30 18:57:15