Stopwatch program - python-3.x

I need to make a stop watch program, I need Start, Stop, Lap, Reset and Quit functions. The program needs print elapsed times whenever the Stop or Lap key is pressed. When the user chooses to quit the program should write a log file containing all the timing data (event and time) acquired during the session in human readable format.
import os
import time
log = ' '
def cls():
os.system('cls')
def logFile(text):
logtime = time.asctime( time.localtime(time.time()) )
f = open('log.txt','w')
f.write('Local current time :', logtime, '\n')
f.write(text, '\n\n')
f.close()
def stopWatch():
import time
p = 50
a = 0
hours = 0
while a < 1:
cls()
for minutes in range(0, 60):
cls()
for seconds in range(0, 60):
time.sleep(1)
cls()
p +=1
print ('Your time is: ', hours, ":" , minutes, ":" , seconds)
print (' H M S')
if p == 50:
break
hours += 1
stopWatch()
I have it ticking the time, however they way I have it wont allow me to stop or lap or take any input. I worked to a few hours to find a way to do it but no luck. Any Ideas on how im going to get the functions working?

Related

Timer shutdown computer(python3.x)

i had code a timer shutdown pc which will shutdown after the times up, but it will keep printing the time remaining which is not good if i want to shutdown my computer after 30 minutes, it will print about 1800 lines, how should i modify it if i want it to print one line of time remaining which will keep changing.
import time
seconds = int(input("seconds:"))
for i in range(seconds):
x = (seconds - i)
print(x)
time.sleep(1)
check = input("do u want to shutdown ur computer?(yes/no):")
if check == "no":
exit()
else:
os.system("shutdown /s /t 1")
Try this. Just replace the string "Shutdown has started" with the shutdown command.
import time
import sys
x=int(input("seconds: "))
print("The timer has started. Time remaining for shut down: ")
def custom_print(string, how = "normal", dur = 0, inline = True):
if how == "typing": # if how is equal to typing then run this block of code
letter = 1
while letter <= len(string):
new_string = string[0:letter]
if inline: sys.stdout.write("\r")
sys.stdout.write("{0}".format(new_string))
if inline == False: sys.stdout.write("\n")
if inline: sys.stdout.flush()
letter += 1
time.sleep(float(dur))
if new_string=="0":
print("\nShut down has started")
else:
pass
for k in range(1,x+1):
k=x-k
custom_print(str(k), "typing", 1)

I have a code to make a motor run then sleep, then run again, but can't get it to work

I need to make a motor run for an amount of time, sleep for an amount of time, then repeat making an infinite loop
from adafruit_motorkit import MotorKit
import time
kit = MotorKit()
while True:
endtime = time.time() + 60 # runs motor for 60 seconds
while time.time() < endtime:
kit.motor1.throttle = 1
pass
print('endtime passed')
time.sleep(10)
print('done sleeping')
I'm expecting the motor to run for a minute, give the endtime passed message, and sleep for 10 seconds, but the motor never sleeps. I'm new to python so I don't know much about this and any help is appreciated.
You need to set the throttle back to 0 before calling time.sleep.
time.sleep will only pause the process for the given time, you need to explicitly tell the motor to stop moving.
Example:
while True:
endtime = time.time() + 60 # runs motor for 60 seconds
while time.time() < endtime:
kit.motor1.throttle = 1
pass
print('endtime passed')
kit.motor1.throttle = 0
time.sleep(10)
print('done sleeping')
Also you don't have to busy-wait the 60 seconds the motor is running, you can just set the throttle on the motor and then call time.sleep:
from adafruit_motorkit import MotorKit
import time
kit = MotorKit()
while True:
print('running motor')
kit.motor1.throttle = 1
time.sleep(60)
print('pausing 10 seconds')
kit.motor1.throttle = 0
time.sleep(10)
print('done sleeping')

Measuring time since last time the if statement ran (Python)

I want to make my if statement run, only, if it is more than x seconds since it last ran. I just cant find the wey.
As you've provided no code, let's stay this is your program:
while True:
if doSomething:
print("Did it!")
We can ensure that the if statement will only run if it has been x seconds since it last ran by doing the following:
from time import time
doSomething = 1
x = 1
timeLastDidSomething = time()
while True:
if doSomething and time() - timeLastDidSomething > x:
print("Did it!")
timeLastDidSomething = time()
Hope this helps!
You'll want to use the time() method in the time module.
import time
...
old_time = time.time()
...
while (this is your game loop, presumably):
...
now = time.time()
if old_time + x <= now:
old_time = now
# only runs once every x seconds.
...
# Time in seconds
time_since_last_if = 30
time_if_ended = None
# Your loop
while your_condition:
# You still havent gone in the if, so we can only relate on our first declaration of time_since_last_if
if time_if_ended is not None:
time_since_last_if = time_if_ended - time.time()
if your_condition and time_since_last_if >= 30:
do_something()
# defining time_if_ended to keep track of the next time we'll have the if available
time_if_ended = time.time()

python3 time result not correct

I got the follow code. I have added time() to it to let me calculate the delay between when the user get's the problem and when the user inputs the data.
But the resulting time is not always correct and I am not sure why.
from time import time
from random import randint
a = randint(0,1000)
b = randint(0,1000)
cor_answer = a+b
usr_answer = int(input("what is "+str(a)+"+"+str(b)+"? \n"))
start = time()
if usr_answer == cor_answer:
print("yes you are correct!")
else:
print("no you are wrong!")
end = time()
elapsed = end - start
print("That took you "+str(elapsed)+" seconds. \n")
This is the result executing from cmdline:
~/math_quiz/math_quiz$ python3 math_quiz.py
what is 666+618?
1284
1284
1284
yes you are correct!
That took you 4.291534423828125e-05 seconds.
But time() clearly works because if I run it in IDLE I get this:
>>> start = time()
>>> time()-start
13.856008052825928
So I am not sure why the execution from cmdline gets me a different result.
Thanks
Your code currently start the timer after user input the answer
You need to put this code start = time() before usr_answer = int(input("what is "+str(a)+"+"+str(b)+"? \n"))

breaking a loop in the middle python

i am trying to have a loop that keeps functioning until something is inputted which will break the loop. However if i put in 'stop = input()' in the loop then it has to go through that first before doing anything else. my code is like this: (it uses some minecraft commands. basically im trying to make a block move down a 20X20 square and have it be able to stop in the middle on command)
from mcpi import minecraft
mc=minecraft.Minecraft.create()
from time import sleep
pos=mc.player.getTilePos
x=pos.x
y=pos.y
z=pos.z
mc.setBlocks(x-10,y,z+30,x+10,y+20,z+30,49)
BB=0
while BB<20:
BB=BB+1
sleep(.7)
mc.setBlock(x,y+(20-BB),z+30,35)
mc.setBlock(x,y+(21-BB),z+30,49)
stop=input()
if stop=='stp':
break
how do i keep the loop going until someone inputs 'stp'? because currently it will move one block then stop and wait until i input something. The loop works if i take out the last three lines.
Whenever you run into input() in your code, Python will stop until it receives an input. If you're running the script in your console, then pressing Ctrl+C will stop execution of the program. (I'll assume you are, because how else would you be able to input 'stp'?)
You can run your logic in a different thread and signal this thread whenever you get an input.
from mcpi import minecraft
import threading
mc=minecraft.Minecraft.create()
from time import sleep
pos=mc.player.getTilePos
stop = False
def play():
x=pos.x
y=pos.y
z=pos.z
mc.setBlocks(x-10,y,z+30,x+10,y+20,z+30,49)
BB=0
while BB<20:
BB=BB+1
sleep(.7)
mc.setBlock(x,y+(20-BB),z+30,35)
mc.setBlock(x,y+(21-BB),z+30,49)
if stop:
break
t = threading.Thread(target=play)
t.start()
while True:
s = input()
if s == 'stp':
stop = True # the thread will see that and act appropriately
I know this is kind of old but I programed something similar earlier so here is a quick adaptation to your needs, hope you don't need it though xD
from mcpi.minecraft import Minecraft
from threading import Thread
from time import sleep
mc = Minecraft.create()
class Placer(Thread):
def __init__(self):
self.stop = False
Thread.__init__(self)
def run(self):
x, y, z = mc.player.getPos()
mc.setBlocks(x - 10, y, z + 30, x + 10, y + 20, z + 30, 49)
for i in range(20, -1, -1):
mc.setBlock(x, y + i, z + 30, 35)
mc.setBlock(x, y + i + 1 - 1, z + 30, 49)
sleep(0.7)
if self.stop:
break
placer = Placer()
placer.start()
while True:
text = input(": ")
if text == "stp":
placer.stop = True

Resources