user16239103
user16239103

Reputation:

Print value from while True: in Python

I'm trying to print a value from this while True.

while True:
   variable = bool(False)
   time.sleep(6)
   variable = bool(True)
   time.sleep(6)

print(variable)

The print is out from the loop I Need to get the variable to use it in a for.

Upvotes: 1

Views: 1373

Answers (3)

blankRiot96
blankRiot96

Reputation: 9

Do a bit of research before asking the question

First of all

variable = bool(False)

Is not necessary, variable = False is the same. variable = eval('False') would be more meaningful, as theres an actual conversion going on

Second, you need to break the loop if you want to exit it, but i assume your just trying to print False and True every 6 seconds

so you would do this


 while True:
   variable = False
   print(variable)
   time.sleep(6)
   variable = True
   print(variable)
   time.sleep(6)

Upvotes: 0

luismriq
luismriq

Reputation: 31

The print(variable) statement will never be reached, to solve this you can do something like this:

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)

Where the loopFunction will be running on a different thread, so the rest of the code will be reached.

If you only want to check the time since the program starts, you can simply do something like:

import time

start = time.time()

# Rest of your code
for i in range(10):
    print((time.time()-start)%12>6)
    time.sleep(3)

Which will give you the same result.

Upvotes: 0

Samwise
Samwise

Reputation: 71424

You need to print inside the loop.

variable = False
while True:
    print(variable)
    time.sleep(6)
    variable = not variable

prints:

False
True
False
True
False

etc

Upvotes: 0

Related Questions