so i am trying to figure this out for school. Im trying to print x out every minute and every ten min it will print on a new line. so far i cant get the "printing x" every min down. can someone please help.
this is my code
import time;
inTime = float(input("type in how many second"))
oldTime = time.time()-inTime
print (time.time())
def tenMin(oldTime):
newTime = time.time()
if ((newTime - oldTime)>= 25):
return True
else:
False
while (True):
if (tenMin==True):
print ("x")
newTime = time.time()
oldtime = time.time()
else:
oldTime = time.time()
continue
Your first problem is in the line
if (tenMin==True):
You compare a function reference to a boolean, clearly the answer would be False. You have to pass a parameter
if (tenMIn(oldTime)):
...
First you have some issues with you code:
else:
False - This is not true syntax in python.
If you want timer, why are you asking the user for input?
You have a logic problem:
inTime = float(input("type in how many second"))
oldTime = time.time()-inTime
time.time is float yes, but can a user really know what to print in UnixTime?
I'll suggest a simple solution it's not the very best but it works.
It will print "x" every 1 Min and after 10 Min it will print "\n" (new line)
import time
def main():
#both timers are at the same start point
startTimerTen = time.time()
startTimerMin = startTimerTen
while True:
getCurrentTime = time.time()
if getCurrentTime - startTimerTen >= 600:
# restart both parameters
startTimerTen = getCurrentTime
startTimerMin = getCurrentTime
print "This in 10 min!\n"
if getCurrentTime - startTimerMin >= 60:
# restart only min parameter
startTimerMin = getCurrentTime
print "x"
#end of main
if __name__ == "__main__":
main()
Related
I have this code to stop a function at a specific time. I would loop through the function and then break the function, if it takes too long, is there a better way to do it?
import time
def function_one()
rec = (time.time())
print("im starting")
ans = str(time.time() - rec)
ans = (round(float(ans), 15))
print("this is where im doing something code")
while ans < 10:
return function_one()
break
You can make it simpler like this:
import time
def function_one():
start_time = time.time()
while True:
print('Function doing something ...')
if time.time() - start_time > 10:
break
function_one()
Here, I'm using a while loop just to keep the function running, but that depends on the details of your function.
In general, what you need is:
set the start time
do whatever the function is supposed to be doing;
check if it's been running for too long and, in case it has, you can simply return.
So, something like:
import time
def function_one():
start_time = time.time()
# do your job
if time.time() - start_time > 10:
return something
function_one()
If you want to stop a function after a set amount of time has passed I would use a while loop and do something like this.
import time
def function_one():
start = (time.time()) #start time
limit = 1 #time limit
print("im starting")
while (time.time() - start) < limit:
#input code to do here
pass
print(f"finished after {time.time() - start} seconds")
function_one()
My python game isn't working, the sequences beginning with:
if int(total_time) > 10:
isn't triggering, but when I press D, C or W I am getting the 'you opened something' text though. The code there is right as far as I know, it's just not working. I used the or prevtime to allow you to do it the first time.
import random, time, pygame, sys
from pygame.locals import *
total_time = time.clock()
pygame.init()
XQR_prevtime = 0
ppayh_prevtime = 0
pu_ekaw_prevtime = 0
diff = 1
windowSurface = pygame.display.set_mode((400,400),0,32)
time.sleep(3)
XQR_awakened = False
ppayh_awakened = False
pu_ekaw_awakened = False
if int(total_time) > 10:
if int(XQR_prevtime) > (12 - diff) or int(XQR_prevtime) == 0 or XQR_awakened == True:
if XQR_awakened == True:
print("You left something open...")
time.sleep(2)
print("And a mystery came in")
time.sleep(2)
sys.exit()
if random.randint(0,diff) == 1:
print(3)
XQR_prevtime = time.clock()
door_opening.play()
XQR_awakened = True
if int(ppayh_prevtime) > (12 - diff) or int(ppayh_prevtime) == 0 or ppayh_awakened == True:
if ppayh_awakened == True:
print("You left something open...")
time.sleep(2)
print("And a friend came in")
time.sleep(2)
sys.exit()
if randint(0,diff) == 1:
print(3)
ppayh_prevtime = time.clock()
closet_opening.play()
ppayh_awakened = True
if int(pu_ekaw_prevtime) > (12 - diff) or int(pu_ekaw_prevtime) == 0 or pu_ekaw_prevtime == True:
if ekaw_up_awakened == True:
print("You left something open...")
time.sleep(2)
print("And an answer came in")
time.sleep(2)
sys.exit()
if randint(0,diff) == 1:
print(3)
pu_ekaw_prevtime = time.clock()
window_opening.play()
pu_ekaw_awakened = True
total_time never changes, so you can never reach your condition.
The line
total_time = time.clock()
assigns a numeric value (a float) to total_time. There is no reference back to the time.clock() function, the function returns just a normal float object, not a timer object.
And normal float values don't change, they are immutable. The total_time value is not going to change as you game runs.
If you want to measure elapsed time, just keep calling time.clock():
if time.clock() > 10:
You don't need to convert a float value to int here, comparisons with integers just work.
I want to create a game where the idea is to spam as much as possible in the time limit: 10 seconds
import time
import random
print("Spamming race")
print("*************")
time.sleep(10)
print("You must spam the number '1'.")
time.sleep(3)
print("Ready")
time.sleep(1)
print("Set")
no = (0.25,0.5,0.7,1,1.25,1.5,1.7,2,2.25,2.5,2.75,3)
number = random.choice(no)
time.sleep(number)
print("Go!")
max_time = 1
t = 31
start_time = time.time()
g = input()
if time.time - start_time > max_time > t: #where the problem is but I don't know why
distance = g.count('1')
print("And he crosses the line with a distance of ",distance)
It says the problem is on line 23 but I can't see what is the problem can someone help me?
As #Rawing pointed out, you forget to call time.time:
if time.time()-start_time>max_time>t:
distance=g.count('1')
print("And he crosses the line with a distance of ",distance)
Rawing is correct. To elaborate, use time.time() instead of time.time
I think what you want for that line is:
if (time.time()-start_time)>t:
I have this following code and am stuck in the while loop
I know there is a problem with the while datetime.datetime.now() < (datetime.datetime.now() + datetime.timedelta(minutes=wait_time)): line.
Can anyone help please ?
nodes_with_scanner = []
wait_time = 60
while datetime.datetime.now() < (datetime.datetime.now() + datetime.timedelta(minutes=wait_time)):
nodes_with_scanner = get_nodes_with_scanner_in_dps(self.node_names, scanner_id, username=self.users[0].username)
log.logger.debug("Number of pre-defined {0} scanners detected in DPS: {1}/{2}".format(scanner_type, len(nodes_with_scanner), len(self.node_names)))
if state == "create":
if len(self.node_names) == len(nodes_with_scanner):
log.logger.debug("All {0} pre-defined scanners with id '{1}' have been successfully created in DPS for nodes '{2}'".format(scanner_type, scanner_id, ", ".join(self.node_names)))
return
elif state == "delete":
if len(nodes_with_scanner) < 1:
log.logger.debug("All {0} pre-defined scanners with id '{1}' have been successfully deleted in DPS for nodes '{2}'".format(scanner_type, scanner_id, ", ".join(self.node_names)))
return
log.logger.debug("Still waiting on some {0} pre-defined scanners to '{1}' in DPS; sleeping for 1 minute before next check".format(scanner_type, state))
time.sleep(60)
You are asking if the current time is smaller than the current time plus a delta. Of course that's going to be true each and every time, the future is always further away into the future.
Record a starting time once:
start = datetime.datetime.now()
while datetime.datetime.now() < start + datetime.timedelta(minutes=wait_time)):
If wait_time doesn't vary in the loop, store the end time (current time plus delta):
end = datetime.datetime.now() + datetime.timedelta(minutes=wait_time))
while datetime.datetime.now() < end:
It may be easier to just use time.time() here:
end = time.time() + 60 * wait_time
while time.time() < end:
You use datetime.datetime.now() in your while loop, what means each iteration you check if the time now is lower then the time now + delta.
That logically wrong, because it will be True forever as the time now will be always lower than the time now plus delta.
You should change it to this:
time_to_start = datetime.datetime.now()
while datetime.datetime.now() < (time_to_start + datetime.timedelta(minutes=wait_time)):
print "do something"
I want to write a function called boom(h,m,s) that after input from main starts printing in HH:MM:SS format the countdown clock, and then prints "boom".
I'm not allowed to use existing modules except the time.sleep(), so I have to base on While\For loops.
import time
def boom(h,m,s):
while h>0:
while m>0:
while s>0:
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s-=1
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s=59
m-=1
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s=59
m=59
h-=1
while h==0:
while m==0:
while s>0:
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s-=1
print ("BooM!!")
I figured how to calculate the seconds part, but when I input zeros on H and M parameters, it's messing with the clock.
The problem is here:
while h==0:
while m==0:
while s>0:
If m == 0, and s == 0 the while loop doesn't break, so there is an infinite loop.
Just add an else clause to the (last and) inner-most while, like so:
while s>0:
...
else: # executed once the above condition is False.
print ('BooM!!')
return # no need to break out of all the whiles!!
just convert it all to seconds and convert it back when you print ...
def hmsToSecs(h,m,s):
return h*3600 + m*60 + s
def secsToHms(secs):
hours = secs//3600
secs -= hours*3600
mins = secs//60
secs -= mins*60
return hours,mins,secs
def countdown(h,m,s):
seconds = hmsToSecs(h,m,s)
while seconds > 0:
print "%02d:%02d:%02d"%secsToHms(seconds)
seconds -= 1
sleep(1)
print "Done!"