Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make this repeat forever?

Tags:

python

loops

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.

like image 230
Vladimir Putin Avatar asked Jun 20 '14 21:06

Vladimir Putin


People also ask

How do you make a loop that runs forever?

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.

How do you make something repeat forever on scratch?

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.

Can a for loop be infinite?

You can run a for loop infinitely by writing it without any exit condition.


1 Answers

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)
like image 86
Tim Pietzcker Avatar answered Oct 10 '22 22:10

Tim Pietzcker