Reputation: 1
I am starting to learn programming so take it easy on me. Can you explain like I am five? Here is the code from LTPHW:
for i in [ "/", "-", "|", "\\", "|" ]:
print "%s \r" % i ,
I am getting errors that I could not understand. Is it supposed to print out
/, -, |, \\, |
What is going on here?
Upvotes: 0
Views: 48
Reputation: 49330
Unfortunately, the problem is that that code doesn't have any visible output.
>>> for i in [ "/", "-", "|", "\\", "|" ]:
... print "%s \r" % i ,
...
>>>
The root cause is that LPTHW is terrible.
For each character in the list, this prints that character, then a space, then goes back to the beginning of the line, then prints a space. That last space after going back to the beginning of the line overwrites the written character.
Now, it looks like it's trying to do something like a spinning bar animation. You could start messing around with sys.stdout.write
, but it's easiest to just move to Python 3 (LPTHW still insists on Python 2 for some reason). You should also add a call to time.sleep
so you can actually see the animation. Also, you don't need to create a list of single-character strings; just use a multi-character string:
import time
for i in '/-|\\|':
print(i, end='\r', flush=True)
time.sleep(0.3)
Upvotes: 1