How to time the for loop? - python

I am having a code where I have a for loop
I want that for loop run some specific time and then it stop or exit. I tried to find solutions like this:
import time
**NOT HELPFUL for me**
def stopwatch(seconds):
start = time.time()
time.clock()
elapsed = 0
while elapsed < seconds:
elapsed = time.time() - start
time.sleep(1)
stopwatch(20)
My code is like this:
for a in list:
if condition true:
print('Condition True')
else
print('not true')
So, i just need to run this loop for few seconds and then stop. Any help would be appreciated.

Just subtract start time from current time (in seconds)
import time
start = time.time()
for a in list:
if time.time()-start > maxTimeout:
break
print("condition true" if condition else "not true")

Related

How do I stop a separate function from running after my countdown timer function ends?

I'm a complete beginner in programming and just wanted to code something I thought was interesting in python. I want to code the rest of it myself, but I got stumped on this part and cannot figure it out at all.
This is my code so far...
block, is the name I gave each session where users can input numbers
there are 3 blocks where users are given 5 seconds of time in each block
to enter (as many sequences of "5" numbers) as they can.
each time the user enters a sequence of numbers, it should add those values to an index in the block_list. (doesn't matter if they enter 3 or 8 values)
Here's the problem:
So after entering some numbers in, as soon as the timer runs out, I want the program to submit whatever the user is inputting to the list and skip to the next block iteration.
My code just doesn't do this and it also is stuck in a loop as well
Looking for help thanks!
Here is the output:
OUTPUT
and here is the code:
from threading import Thread
import time
from random import *
block = 0
def main():
global block
while block < 3:
Thread(target=userInputs).start()
Thread(target=countTime(5)).start()
block += 1
block_list = []
timeOut = True
def userInputs():
while timeOut == True:
num_inputs = int(input("Input 5 numbers and then press 'enter': "))
block_list.append(num_inputs)
print(block_list)
start_time = time.time()
num_list = [1,2,3,4]
block_list = []
def countTime(seconds):
global timeOut
global start_time
while True:
elapsed_time = time.time() - start_time
if elapsed_time >= seconds:
print()
print("Time spent:")
print(time.time()-start_time)
timeOut = False
break
timeOut = True
start_time = time.time()
print(start_time)
main()

How to run x command for y seconds when condition is met in Python?

I have an application where I have to run a command for y number of seconds but only when a condition is met.
As soon as time duration is up, then it should move to next line.
Example: Second=10
if i==1:
print("Hello") # for 10 seconds
It should only print hello for 10 seconds and then move on.
How can I achieve this in Python?
I would change the previous answer a bit:
import time
if i==1:
starttime=time.time()
while time.time() < (starttime+10):
time.sleep(1) # <-- do not print hello too often !
print("hello")
because otherwise it will print "hello" about 10,345,123 times by my estimate :)
Just add a time loop inside your conditional:
import time
if i==1:
starttime=time.time()
while time.time() < (starttime+10):
print("hello")

Python incremente a number each second

How can I incremente a number each second? I was thinking to something like this.
import threading
def printit():
second = 1
while threading.Timer(1, printit).start(): #for every second that pass.
print(second)
second += 1
printit()
I suggest a different method using time.sleep(1), the solution would be:
from time import sleep
def printit():
... cpt = 1
... while True:
... print cpt
... sleep(1)
... cpt+=1
time.sleep(secs)
Suspend execution of the current thread for the given
number of seconds.
There are a couple ways of doing this. The first as others have suggested is
import time
def print_second():
second = 0
while True:
second += 1
print(second)
time.sleep(1)
The problem with this method is that it halts execution of the rest of the program (unless it is running in another thread). The other way allows you to perform other processes in the same loop while still incriminating the second counter and printing it out every second.
import time
def print_second_new():
second = 0
last_inc = time.time()
while True:
if time.time() >= last_inc + 1:
second += 1
print(second)
last_inc = time.time()
# <other code to loop through>

Trouble with a Python Countdown Program

I have recently finished a course in Python about a month ago. I am continuing expanding my knowledge on Python by creating programs.
The code below is a program for a Python countdown program. What the program does is that it asks the user to input a count of seconds, minutes, and hours.
Anyways, I noticed 2 Bugs that occur in the program.
First Bug:
If we enter an hour and second count (and no minute count), the program would count the remaining time for that certain hour, but it would not subtract the hour and set the minute back to 59. Instead, it would print the minute as a negative number.
Second Bug:
If we enter an hour, second, and minute count, the program would count the reamaining time. But when the program reaches the very last minute (i.e. 01:00:59), it would skip that minute and go on to the next one (i.e. 00:59:59).
About the 2nd Bug: Suppose I enter 1 Hour, 1 Minute, 5 Seconds. It would count down the 5 Seconds. The computer would then print 1:00:00. Instead of counting down the seconds for that certain minute. It would skip to 0:59:59. Hope that helps
It would be fantastic if I could receive some assistance with fixing these two bugs, and maybe a way to differently format the program.
Thanks for reading and I am looking forward to your answer,
-Anonymous
import time
time_count = 0
second = int(raw_input("Seconds:"))
count_minute = int(raw_input("Minutes:"))
count_hour = int(raw_input("Hours:"))
time_count += second
time_count += count_minute * 60
time_count += count_hour * 3600
def clean():
global second
global count_minute
global count_hour
print_second = str(second).zfill(2)
print_minute = str(count_minute).zfill(2)
print_hour = str(count_hour).zfill(2)
print "%s:%s:%s" % (print_hour, print_minute, print_second)
time.sleep(1)
clean()
time.sleep(1)
for i in range(1, time_count + 1)[::-1]:
if second == 0 and count_minute == 0 and count_hour == 0:
clean()
break
elif second != 0:
second -= 1
elif second == 0:
count_minute -= 1
second = 59
if count_minute == 0 and count_hour > 0:
clean()
count_hour -= 1
count_minute = 59
clean()
time.sleep(1)
print """
Timer Finished.
"""
Some problems in your code are, the unnecessary use of globals, direct typechecking, etc. Also if you use higher level constructions(like timedelta objects) the probability of your code being bug free is higher. This is better:
from datetime import timedelta
from time import sleep
while True:
try:
hours, minutes, seconds = input('Enter hours, minutes, seconds (with a comma in between): ')
except (ValueError, TypeError): # other errors
print("Error 1, please ...")
continue
except NameError:
print("Error 2")
continue
else:
print("All good")
break
total = timedelta(hours=hours, minutes=minutes, seconds=seconds)
for passed_seconds in range(int(total.total_seconds())):
print total - timedelta(seconds=passed_seconds)
sleep(1)

Python 2.7 While Loop time

while True:
now = datetime.datetime.now()
if now.second == 1:
print "One"
my program print One about 7 times. How do I make it print only once?
Your computer is too fast.
It takes the current time, tests whether the current second is one and then again. And since it is so fast it can do this within less than one second, you get more lines of output.
Make it wait after each iteration:
while True:
now = datetime.datetime.now()
if now.second == 1:
print "One"
time.sleep(59) # wait 59 seconds after success
time.sleep(1) # wait 1 second after each fail
This program will sleep most time. If you want it to do anything useful, it will be a different program.
How about storing the value previously used for printing?
previous = None
while True:
now = datetime.datetime.now()
if now.second == 1 and now.second != previous:
print "One"
previous = now.second # store the last value

Categories

Resources