[英]Can you run two infinite loops, one with an input, at the same time in python?
I've seen some posts about running infinite loops in python but nothing covering this specific topic.我看过一些关于在 python 中运行无限循环的帖子,但没有涉及到这个特定主题。
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.抱歉,如果这很愚蠢,我是 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
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.也就是说,这段代码没有做任何有意义的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.