I have this code which generates random characters (it's a kind of terrain generator). I just can't get it to print forever. Here's the current code I have for it:
import random
print(' '.join([random.choice(['#','o','~','*']) for i in range(10000)]))
I tried to do this, but I got a SyntaxError
.
import random
print(' '.join([random.choice(['#','o','~','*']) while True]))
How can I get this to repeat forever? I also want a 0.05 second delay in between the printing of each character.
The infinite loop We can create an infinite loop using while statement. If the condition of while loop is always True , we get an infinite loop.
The “repeat until” block in the “Control” category will repeat all of the statements inside of it until a condition that you set is met. And the “forever” block will repeat a set of statements forever, never stopping until you click on the red stop sign icon on the screen to end your program.
You can run a for loop infinitely by writing it without any exit condition.
Well, if you want a delay between the characters, you can't use join()
because that will give you a single string instead of a "character generator".
And if you plan on using an "infinite" generator, you can't use join()
either for that same reason.
How about this:
import random
import sys
import time
while True:
print(random.choice("#o~*"), end="", flush=True) # Python 3.3 and up
time.sleep(0.05)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With