Home > other >  How to count in Python with just two lines
How to count in Python with just two lines

Time:11-17

my problem is the following:

import time
for i in range(100):
    print(f"Total connections: {i} \n Something: {i   1}", end="\r")
    time.sleep(0.5)

But my output is the following:

Total connections: 1
Total connections: 2
Total connections: 3
Something: 4

I expected something like:

Total connections: 3
Something: 4

I want only that the numbers are changing and that there are just two lines.

Can somebody please help me?

CodePudding user response:

Lets start with what you have:

import time
for i in range(100):
    print(f"Total connections: {i} \n Something: {i   1}", end="\r")
    time.sleep(0.5)

The time.sleep() method does not change the output, so lets get rid of it:

for i in range(100):
    print(f"Total connections: {i} \n Something: {i   1}", end="\r")

Lets refactor that to take the top of the range out into a variable:

foobar = 100
for i in range(foobar):
    print(f"Total connections: {i} \n Something: {i   1}", end="\r")

You want only two lines, presumably with the ending "Total connections" and the "Something" count. Neither require the loop, so let's get rid of that:

foobar = 100
print(f"Total connections: {foobar} \n Something: {foobar   1}", end="\r")

And the output looks like:

$ python3 test.py
Total connections: 100 
 Something: 101

CodePudding user response:

i think you should implement it like this

import time, os
for i in range(100):
    print(f"Total connections: {i} \n Something: {i   1}", end="\r")
    os.system('clear')
    time.sleep(0.5)
  • Related