I want to be able to have two while True
loops running at the same time.
Would this be possible?
I am extremely new to Python, so I do not know how to get round this problem.
This is the code I made:
import time
def infiniteLoop():
while True:
print('Loop 1')
time.sleep(1)
infiniteLoop()
while True:
print('Loop 2')
time.sleep(1)
Right now, it just prints a 'Loop 1'
Thanks in advance
To run both loops at once, you either need to use two threads or interleave the loops together.
Method 1:
import time
def infiniteloop():
while True:
print('Loop 1')
time.sleep(1)
print('Loop 2')
time.sleep(1)
infiniteloop()
Method 2:
import threading
import time
def infiniteloop1():
while True:
print('Loop 1')
time.sleep(1)
def infiniteloop2():
while True:
print('Loop 2')
time.sleep(1)
thread1 = threading.Thread(target=infiniteloop1)
thread1.start()
thread2 = threading.Thread(target=infiniteloop2)
thread2.start()
While Brian's answer has you covered, Python's generator functions (and the magic of yield
) allow for a solution with two actual loops and without threads:
def a():
while True: # infinite loop nr. 1 (kind of)
print('Loop 1')
yield
def b():
for _ in a(): # infinite loop nr. 2
print('Loop 2')
> b()
Loop 1
Loop 2
Loop 1
Loop 2
....
Here, the two loops in a()
and b()
are truly interleaved in the sense that in each iteration, execution is passed back and forth between the two.
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