从 while True: in Python 打印值
Print value from while True: in Python
我正在尝试从中打印一个值为 True 的值。
while True:
variable = bool(False)
time.sleep(6)
variable = bool(True)
time.sleep(6)
print(variable)
循环中打印出来我需要获取变量以在 for 中使用它
请帮忙
你需要在循环内打印。
variable = False
while True:
print(variable)
time.sleep(6)
variable = not variable
打印:
False
True
False
True
False
等等
提问前做一些调查
首先
variable = bool(False)
不是必须的,variable = False
也是一样的。
variable = eval('False')
会更有意义,因为正在进行实际转换
其次,如果你想退出它,你需要打破循环,但我假设你只是想每 6 秒打印一次 False 和 True
所以你会这样做
while True:
variable = False
print(variable)
time.sleep(6)
variable = True
print(variable)
time.sleep(6)
永远不会到达print(variable)
语句,要解决这个问题你可以这样做:
import threading, time
variable = None
def loopFunction():
global variable # The loopFunction will be using the global variable defined before, without this the variable will be treated as local.
while True:
variable = False # bool(False) is False
time.sleep(6)
variable = True # bool(True) is True
time.sleep(6)
# The loopFunction will be running until the program ends on a new thread
loop = threading.Thread(target = loopFunction, args = ())
loop.start()
# Rest of your code
for i in range(10):
print(variable)
time.sleep(3)
loopFunction 将 运行 在不同的线程上,因此将到达其余代码。
如果您只想查看自程序启动以来的时间,您可以简单地执行以下操作:
import time
start = time.time()
# Rest of your code
for i in range(10):
print((time.time()-start)%12>6)
time.sleep(3)
这会给你相同的结果。
我正在尝试从中打印一个值为 True 的值。
while True:
variable = bool(False)
time.sleep(6)
variable = bool(True)
time.sleep(6)
print(variable)
循环中打印出来我需要获取变量以在 for 中使用它 请帮忙
你需要在循环内打印。
variable = False
while True:
print(variable)
time.sleep(6)
variable = not variable
打印:
False
True
False
True
False
等等
提问前做一些调查
首先
variable = bool(False)
不是必须的,variable = False
也是一样的。
variable = eval('False')
会更有意义,因为正在进行实际转换
其次,如果你想退出它,你需要打破循环,但我假设你只是想每 6 秒打印一次 False 和 True
所以你会这样做
while True:
variable = False
print(variable)
time.sleep(6)
variable = True
print(variable)
time.sleep(6)
永远不会到达print(variable)
语句,要解决这个问题你可以这样做:
import threading, time
variable = None
def loopFunction():
global variable # The loopFunction will be using the global variable defined before, without this the variable will be treated as local.
while True:
variable = False # bool(False) is False
time.sleep(6)
variable = True # bool(True) is True
time.sleep(6)
# The loopFunction will be running until the program ends on a new thread
loop = threading.Thread(target = loopFunction, args = ())
loop.start()
# Rest of your code
for i in range(10):
print(variable)
time.sleep(3)
loopFunction 将 运行 在不同的线程上,因此将到达其余代码。
如果您只想查看自程序启动以来的时间,您可以简单地执行以下操作:
import time
start = time.time()
# Rest of your code
for i in range(10):
print((time.time()-start)%12>6)
time.sleep(3)
这会给你相同的结果。