Reputation: 1
I am trying to run two while
loops based on an input condition. In this example, that is taken out and replaced by a 1 == 0
so that 0
can be changed back and forth for testing. Once selected, each while
loop should run for 10 seconds and then the input condition checked (replaced by 1 == 0
) again.
The problem appears to be in the time comparison, since it never evaluates correctly. What am I missing?
#!/usr/bin/env python3
import time
import os
import bellmod
while True:
starttime = time.time()
print("Start time " + str(starttime)) #Time check
elapsedtime = 0 #Reset elasped time to 0 for each loop iteration.
if 1 == 0: #Change this to run either loop. See if remote or local has precidence.
while(elapsedtime < 10):
print("Inside remote while " + time.strftime("%H:%M:%S")) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.
else:
elapsedtime = 0
while(elapsedtime < 10):
print("inside bottom of local while " + str(int(time.time() - starttime))) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.
Upvotes: 0
Views: 480
Reputation: 1121356
Your inner while
loops are endless, because elapsedtime
is never updated:
while(elapsedtime < 10):
print("inside bottom of local while " + str(int(time.time() - starttime))) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.
elapsedtime
is updated after the while
loop ends, but that is never reached.
You need to fix your indentation so elapsedtime
is calculated each loop iteration:
while(elapsedtime < 10):
print("inside bottom of local while " + str(int(time.time() - starttime))) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.
Note that while
is not a function. Using (...)
groups the test expression, but is not needed or normally used. If you pass in values as separate arguments to print()
, that takes care of including a separator and conversion to string for you:
while elapsedtime < 10:
print("inside bottom of local while", int(time.time() - starttime))
elapsedtime = time.time() - starttime
If you don't need to use elapsedtime
in the loop, just inline the calculation:
while time.time() - starttime < 10:
print("inside bottom of local while", int(time.time() - starttime))
Upvotes: 2
Reputation: 77837
You don't change elapsedtime
inside the loop ... it's stuck at 0.
Indent the last line:
if 1 == 0: #Change this to run either loop. See if remote or local has precidence.
while(elapsedtime < 10):
print("Inside remote while " + time.strftime("%H:%M:%S")) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.
else:
elapsedtime = 0
while(elapsedtime < 10):
print("inside bottom of local while " + str(int(time.time() - starttime))) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.
Upvotes: 1