I want to create a python script that print loading with dots appearing 1 by 1 and disappering them 1 by 1. I know how to disappear all of them but I want them them to go back 1 by 1.
Here is the code:-
for x in range(5):
for y in range(4):
dot = "."*y
loading = (f"Loading {dot}")
print(loading " ", end = '\r')
time.sleep(1)
CodePudding user response:
You could define a function that returns a "zigzag" sequence that corresponds to the number of dots you want. The divmod
builtin comes in handy here. (If you remove the if
statement from the zigzag
function, you get the same behavior you had before.)
This function also avoids the need for nested loops, which also makes it easy to print out an infinite loading sequence (since you can just increment a counter).
I'm also using .ljust(12)
(where 12 is the length of "Loading "
plus 4, the maximum number of dots) to left-justify the string that's printed on every line to the correct length instead of just "blindly" adding a number of spaces.
import time
def zigzag(counter, maximum):
iteration, step = divmod(counter, maximum)
if iteration % 2 == 1: # go backwards every other iteration
return maximum - step
return step
for x in range(20):
n_dots = zigzag(x, 4) # up to 4 dots
message = f"Loading {'.' * n_dots}"
print(message.ljust(12), end='\r')
time.sleep(.1)
This prints out
Loading
Loading .
Loading ..
Loading ...
Loading ....
Loading ...
Loading ..
Loading .
Loading
etc.
CodePudding user response:
I implemented the part that outputs dots in your code by making it a function.
import time
def dotmove(n):
dot = "."*n
loading = (f"Loading {dot}")
print(loading " ", end = '\r')
time.sleep(1)
for x in range(5):
for y in range(4):
dotmove(y)
for z in range(2, 0, -1):
dotmove(z)
CodePudding user response:
A more simplified version
import time
def load(dot_lenth=type(int),delay=1):
dot=""
for i in range(dot_lenth):
print(f"Loading{dot}",end="\r")
dot ="."
time.sleep(delay)
for i in reversed(range(dot_lenth)):
print(f"Loading{dot[0:i]} ",end="\r")
time.sleep(delay)
load(20,0.1)