Python incremente a number each second - python

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>

Related

Run a loop while waiting for input

Example
x = 0
while True:
x += 1
input = input("whats the day like")
I want it so x will continue going up while waiting for the input
Instead of using a counter look at time module and calculate time before and after the user input and take the difference to get the time taken for user input.
use time.time() to capture the time at particular instance.
If you are doing this just for timing:
from time import perf_counter
start = perf_counter()
inp = input()
print(inp)
print(f"You inserted input in : {perf_counter() - start}")
If by any reason you want to increment x, do the increment part in a separate thread:
from time import sleep
import threading
x = 0
def increment():
global x
while True:
x += 1
print(f"X is now: {x}")
sleep(1)
threading.Thread(target=increment, daemon=True).start()
inp = input()
print(f"input is: {inp}")
output:
X is now: 1
X is now: 2
X is now: 3
hi
input is: hi
By specifying daemon=True, the increment thread doesn't prevent interpreter from terminating.
If you want to stop the thread whenever you receive input, use event object:
from time import sleep
import threading
event = threading.Event()
x = 0
def increment():
global x
while not event.is_set():
x += 1
print(f"X is now: {x}")
sleep(1)
threading.Thread(target=increment).start()
inp = input()
event.set()
print(f"input is: {inp}")
It's great to see a new user on StackOverflow.
I was able to find a solution using the threading module in Python. One way to think about threading in Python is by imagining two Python scripts running simultaneously, but this is not an entirely thorough explanation. To learn more, I would suggest referring to one of the pages below.
Links:
https://realpython.com/intro-to-python-threading/#what-is-a-thread
https://docs.python.org/3/library/threading.html
Example:
import threading
def thread_function(args):
for x in range(args):
print(x)
x = threading.Thread(target=thread_function, args=(5,))
x.start()
input = input("whats the day like")
Output:
0
1
2
3
whats the day like4
Where it waits for user input at the end.

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()

Is it possible to run a two infinite while loops at the same time in python

I have made a timer while loop using
while True:
time.sleep(1)
timeClock += 1
is it possible to execute this loop while executing another infinite while loop at the same time in the same program because I have made a command to show the elapsed time whenever I want
The whole Code is
def clock():
while True:
time.sleep(1)
t += 1
print(t)
clock()
while True:
userInput = input("Do you want to know the total time this porgram has been running?\n Y for yes, N for no : ")
if userInput == Y:
print(t)
else:
pass
Thanks in advance
You can do a very similar thing with multiprocessing...
from multiprocessing import Process, Value
import time
def clock(t):
while True:
time.sleep(1)
t.value += 1
t = Value('i', 0)
p = Process(target=clock, args=[t])
p.start()
while True:
userInput = input("Do you want to know the total time this porgram has been running?\n Y for yes, N for no : ")
if userInput == 'Y':
print(t.value)
Multiprocessing has more overhead than multithreading, but it can often make better use of your machine's capabilities as it is truly running two or more processes in parallel. Python's multithreading really doesn't, due to the dreaded GIL. To understand that, check this out
If you want multiple loops running at the same time, you should use multi-threading. This can be done using the threading library as shown below:
import threading
import time
def clock():
global t
while True:
time.sleep(1)
t += 1
print(t)
x = threading.Thread(target=clock)
x.start()
t = 0
while True:
userInput = input("Do you want to know the total time this porgram has been running?\n Y for yes, N for no : ")
if userInput == 'Y':
print(t)
else:
pass
If the only purpose is a clock however, you'd be better off following kaya's advice and using the time library itself.

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 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