Can you run two infinite loops, one with an input, at the same time in python?

Question:

I’ve seen some posts about running infinite loops in python but nothing covering this specific topic.

I was wondering if you could run code that asked the user a question for an input, whilst another infinite loop was running in the background?
Sorry if this is stupid, I’m new to python.

import time

num = 1
while True:
    num = num + 1
    time.sleep(0.1)

while True:
    ques = input("What is your favourite type of burger? ")
    if ques == "quit":
        break;

print(num)
# here i am wondering whether i can keep the first loop going while the second loop asks me questions



Asked By: Kerodonasium

||

Answers:

This can be done using threads.

import time
from threading import Thread

num = 1


def numbers():
    global num
    while True:
        num = num + 1
        print(num)
        time.sleep(0.1)


def question():
    while True:
        ques = input("What is your favourite type of burger? ")
        if ques == "quit":
            break


threads = [
    Thread(target=numbers),
    Thread(target=question)
]

for thread in threads:
    thread.start()

for thread in threads:
    thread.join()

That said this code doesn’t do anything meaningful.

Answered By: Michal Racko
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.