我正在编写一个问数学问题的脚本,我想知道,我将如何制作计时器?我想制作一个计时器,使用户有20秒的时间来回答,当时间到了,然后说:“抱歉,不正确。”我已经尝试记录问题的时间,然后从他们回答问题时减去它,然后如果它大于或等于20显示不正确,但它不起作用。任何帮助将不胜感激。
if op != '*': # != means 'not equal'
r1 = random.randint (-1, 100) # Randomises a number from -1 to 100
r2 = random.randint (-1, 100)
answer = ops.get(op)(r1,r2)
start = time.time()
equ = int(input('Q{}: What is {} {} {}?\n'.format(q, r1, op, r2)))
end = time.time()
if end - start >= 20:
print ("Sorry you took too long to answer.")
elif answer.upper() = 'FRIDAY':
print 'Correct, today is {}'.format(answer)
else:
r1 = random.randint(-1,12)
r2 = random.randint(-1,12)
answer = ops.get(op)(r1,r2)
equ = int(input('Q{}: What is {} x {}?\n'.format(q, r1, r2)))
if equ == answer :
score += 1
print("Correct, Well done, your score is: " + str(score))
else:
print("Incorrect, Sorry. Your score is: " + str(score))
答案 0 :(得分:0)
您可以使用此类内容来查看是否需要超过20秒才能回答:
import time
start = time.time()
answer = raw_input('What day is it?: ')
end = time.time()
if end - start >= 20:
print 'You took too long to answer'
elif answer.upper() == time.strftime('%A').upper():
print 'Correct, today is {}'.format(answer)
else:
print 'That's not correct, sorry'
编辑:我认为这适用于您要完成的任务。希望你接受这个并从中学习。
import time
import random
import operator
ops = {'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
i = 1
while True:
r1 = random.randint(-1,12)
r2 = random.randint(-1,12)
op = random.choice(list(ops.keys()))
answer = ops.get(op)(r1,r2)
start = time.time()
equ = int(input('Q{}: What is {} {} {}?\n'.format(i, r1, op, r2)))
end = time.time()
if end - start >= 10:
print('You took too long to answer')
elif equ == answer:
print('Correct!')
else:
print('Wrong')
i += 1