BattleCalls
BattleCalls

Reputation: 63

For loop in for loop not executing right

I just wrote some code for a loading symbol that displays

Loading
Loading.
Loading..
Loading...

and then repeats this five times. My only problem is after it executes that loop once, it won't repeat. Here's my code:

import time
for x in range(5):
    for y in range(4):
        print("Loading"+"."*y,end='\r')
        time.sleep(1)

Upvotes: 2

Views: 305

Answers (3)

Sandip Shinde
Sandip Shinde

Reputation: 3

import time
for x in range(5):
    if x != 0:
        print("")
    for y in range(4):
        print("Loading" + "." * y, end='\r')
        time.sleep(1)
    

This will print Loading 5 times.

Upvotes: 0

CodeWithYash
CodeWithYash

Reputation: 251

The problem is that your code is printing the line next line on existing line. To avoid this replace you code with this:-

import time
for x in range(5):
    for y in range(4):
        print("Loading"+"."*y,end='\r')
        time.sleep(1)
    print("\n")

Using a line break will print the code on the next line, not on the existing line. Thank you.

Upvotes: 0

Selcuk
Selcuk

Reputation: 59444

If you overwrite Loading... with Loading it will not erase the extra three dots. Try

print("Loading" + "." * y + "   ", end='\r')

Upvotes: 7

Related Questions