![](/img/trans.png)
[英]Is it possible to run a two infinite while loops at the same time in python
[英]Can you run two infinite loops, one with an input, at the same time in python?
我看过一些关于在 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
这可以使用线程来完成。
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()
也就是说,这段代码没有做任何有意义的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.