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"))
Related
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 am working on a number guessing game for python3 and the end goal of this is to show the user if they play more than one game that they'll receive an average number of guesses. However, I am unable to record how many times the game actually runs. Any help will do.
from random import randint
import sys
def guessinggame():
STOP = '='
a = '>'
b = '<'
guess_count = 0
lowest_number = 1
gamecount = 0
highest_number = 100
while True:
guess = (lowest_number+highest_number)//2
print("My guess is :", guess)
user_guess = input("Is your number greater than,less than, or equal to: ")
guess_count += 1
if user_guess == STOP:
break
if user_guess == a:
lowest_number = guess + 1
elif user_guess == b:
highest_number = guess - 1
print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
PLAY_AGAIN = input("Would you like to play again? y or n: ")
yes = 'y'
gamecount = 0
no = 'n'
if PLAY_AGAIN == yes:
guessinggame()
gamecount = gamecount + 1
else:
gamecount += 1
print("thank you for playing!")
print("You played", gamecount , "games")
sys.exit(0)
return guess_count, gamecount
print('Hello! What is your name?')
myname = input()
print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES: if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print(" ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")
guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)
## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.
It is because you are either calling guessinggame() everytime user wants to play again or you are exiting the program. Also you are setting gamecount to 0 every time you call guessinggame(). You should move gamecount declaration and initialization out of your function. Also increment gamecount before you call guessinggame().
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()
Hello So I am making a simple timed addition program for the little kids in my school. How do I make it so that after 5 seconds it will do:
print ("Try again")
here is my code
running = True
import time
from random import randint
while running:
print ("Hello world!")
time.sleep(1.5)
print ("Thank you for running this program, if not I would have been trapped here for like EVER!")
time.sleep(2.5)
print ("My name is ιllιlııllııllııllıιllιlı.")
time.sleep(2.5)
print ("Crap! It seems like my system is still bugged I cant diplay my name")
time.sleep(2.5)
print ("You are going to have to help me")
time.sleep(2.5)
print (5000 * '-')
time.sleep(2.5)
print ("Here is how you are going to have to help me, I need you to solve math problems in order to get me out of here, I am going to give you 5 seconds to solve them!")
time.sleep(10)
print ("Ok this is going to start in 3")
time.sleep(1)
print ("2")
time.sleep(1)
print ("1")
time.sleep(0.5)
print ("GO")
add1 = (randint(0,99))
print ("What's", add1, "+", add2, "?")
addansm = int(input("Write your answer here:"))
addans = add1 + add2
addans = int()
if addans and addansm == addans :
print ("Correct!")
time.sleep(2.5)
running2 = True
running = False
else :
print ("Try again!")
running = False
Thank you for your help, Some extra information is that as soon as
print ("What's", add1, "+", add2, "?")
Happens I want the 5 second timer to start
Thanks you very much!
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?