Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i am making a script that asks mathematical questions and i was wondering, how would i make a timer? I want to make a timer such that the user has 20 seconds to answer and when the time is up then to say: "Sorry, incorrect." I have tried recording the time when the question is given then subtracting it from the time they answer the question then if its great or equal to 20 to display incorrect, however it doesn't work. Any help will be greatly appreciated.
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))
You can use something like this to check and see if they took longer than 20 seconds to answer:
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'
Edit: I think this applies for what you are trying to accomplish. Hopefully you take this and learn from it.
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
Related
I'm making a quiz in Python where a user can add himself the questions and answers and specify the correct one.
I already did this
# Do you want to add another question version
from Question import Question
question_prompt = []
answer_list = []
def add_Question():
question = input('Add your question: ')
print(question)
test = int(input('If your question is correct. Enter 1 else enter 2: '))
if test == 1:
print('Type the answers propositions: ')
a = input('(a): ')
b = input('(b): ')
c = input('(c): ')
d = input('(d): ')
# print(a + '\n' + b + '\n' + c + '\n' + d )
answer = input('Which one is the correct answer? (a) (b) (c) or (d). Just type the letter ie. a: ').lower()
question_insert = f"{question} \n {a} \n {b} \n {c} \n {d}\n\n"
question_prompt.append(question_insert)
answer_list.append(answer)
listing = tuple(zip(question_prompt, answer_list))
questions = [Question(question_prompt[i],answer_list[i]) for i in range(0, len(listing))]
else :
question = input('add your question: ')
print(question)
test = int(input('if your question is correct. Enter 1 else enter 2: '))
return question, a,b,c,d,answer
def insert_question_prompt() :
again = int(input("Do you want to add another question. 1 = 'yes' and 2 = 'no' "))
while again == 1:
add_Question()
again = int(input("Do you want to add another question. 1 = 'yes' and 2 = 'no' "))
print(question_prompt)
def run_test(questions):
score = 0
for question in questions:
answer = input(question.prompt)
if answer == question.answer:
score += 1
print("Hey You got " + str(score) + "out of " + str(len(questions)) + "questions correct")
# questions = [Question(question_prompt[i],answer_list[i]) for i in range(0, len(listing))]
add_Question()
insert_question_prompt()
print(question_prompt)
print(answer_list)
In the function def insert_question_prompt() : I ask the user if he wants to insert another question and repeat the add_Question function.
The run_test function is to test the quiz. Play and access it
But I am unable to access question_prompt and answer_list in the run_test function even though they are not empty.
Basically, I'm blocked at level where the user can test the quiz ie Play and have the score.
Thanks for your help
I'm solving this problem.
My code works when I test it but it is failing the provided check with the error:
:( Little Professor accepts valid level // timed out while waiting for program to exit
It passes the three previous checks for invalid levels. Any insight to why this might be happening would help.
Here is my code:
def main():
level = get_level()
q=1
s=0
while q<=10:
try:
x = generate_integer(level)
y = generate_integer(level)
ans = x + y
eq = int(input(f'{x} + {y} = '))
if ans == eq:
s += 1
pass
elif ans != eq:
c = 1
while c <= 2:
print('EEE')
eq = int(input(f'{x} + {y} = '))
if ans == eq:
s += 1
break
else:
c += 1
if c == 3:
print('EEE')
print(f'{x} + {y} = {ans}')
q += 1
except EOFError:
pass
print(f'Score: {s}')
def get_level():
valid_inputs = (1,2,3)
while True:
try:
level = int(input('Level: '))
if level in valid_inputs:
return level
else:
pass
except ValueError:
pass
def generate_integer(level):
max = 10**level-1
min = 10**(level-1)
if level == 1:
min == 0
num = random.randint(min,max)
return num
main()
I ran your program (as-is) and found at least 1 problem. I'm not sure if it's why check50 flags that error, but you will need to fix it before it will pass. I entered Level: 1, then got a duplicate equation (4 + 5 = ). This violates a requirement buried under How to Test: "Your program should output 10 distinct problems" (emphasis mine). It's easy to miss - I didn't see it until someone mentioned it on the CS50P ED Forum.
Also, the last 2 lines of your program are supposed to be:
if __name__ == "__main__":
main()
Instead, only you have:
main()
Finally, this is an observation on your code structure. You have a lot of if statements for the 3 attempts to answer the question. It's overly complicated and kind of hard to follow. Hint: It can be simplified with another loop to prompt and check answers.
import random
from browser import timer
operators = ['*', '/', '+', '-']
number = input('How many problems would you like?')
number = int(number)
counter = 1
while counter <= number:
first = random.randint(0,10)
second = random.randint(0,10)
randoperator = random.choice(operators)
problem = '{} {} {} {}'.format(first, randoperator, second, "= ")
answer = input(problem)
correct = problem
counter+=1
I have tried putting this in but it doesn't run anything
if problem == answer:
print("Correct!")
You need to actually do the calculation to find out what the answer is. Here's a quick and dirty way to do that:
import random
operators = ['*', '/', '+', '-']
number = input('How many problems would you like?')
number = int(number)
counter = 1
while counter <= number:
first = random.randint(0,10)
second = random.randint(0,10)
randoperator = random.choice(operators)
problem = '{} {} {}'.format(first, randoperator, second)
answer = input(problem + ' = ')
if eval(problem) == float(answer):
print("Correct!")
counter+=1
Using eval is not a great idea for reasons outlined in the answers to this question. In your case, you already know the two integers and the operator, so finding the expected answer without eval is pretty easy. Say you define a function that can do this for you:
def arithmetic(op, a, b):
if op == "+":
return a + b
elif op == "-":
return a - b
elif op == "*":
return a * b
elif op == "/":
return a / b
Then call this function to get the expected answer and compare that with the answer that the user gave,
while counter <= number:
first = random.randint(0,10)
second = random.randint(0,10)
randoperator = random.choice(operators)
problem = '{} {} {}'.format(first, randoperator, second)
answer = input(problem + ' = ')
if arithmetic(randoperator, first, second) == float(answer):
print("Correct!")
counter+=1
I am making a program that takes in user input in the form of test answers at first. It then asks for an answer key. Finally, it should compare each item in the list and determine a grade.
Here is an example run of my program in which hopefully it would work:
How many questions are there? >> 5
What is your answer for question #1 >> a
What is your answer for question #2 >> a
What is your answer for question #3 >> a
What is your answer for question #4 >> a
What is your answer for question #5 >> a
What is the correct answer for question #1 >> a
What is the correct answer for question #2 >> a
What is the correct answer for question #3 >> a
What is the correct answer for question #4 >> a
What is the correct answer for question #5 >> d
Total number correct : 4
Total number possible: 5
Grade = 4.0/5.0, 0.8%
Here is what actually happens:
How many questions are there? >> 5
What is your answer for question #1 >> a
What is your answer for question #2 >> a
What is your answer for question #3 >> a
What is your answer for question #4 >> a
What is your answer for question #5 >> a
Responses:
1. a
2. a
3. a
4. a
5. a
What is the correct answer for question #1 >> c
What is the correct answer for question #2 >> a
What is the correct answer for question #3 >> a
What is the correct answer for question #4 >> a
What is the correct answer for question #5 >> a
Responses:
1. c
2. a
3. a
4. a
5. a
a = c ?
a = a ?
a = a ?
a = a ?
a = a ?
a = c ?
a = a ?
a = a ?
a = a ?
a = a ?
a = c ?
a = a ?
a = a ?
a = a ?
a = a ?
a = c ?
a = a ?
a = a ?
a = a ?
a = a ?
a = c ?
a = a ?
a = a ?
a = a ?
a = a ?
20
Number of correct answers = 20 out of 5
Your score is: -3.0
I am unsure as to why this is happening, is it perhaps the way I iterate through both lists in grading? Here is my code:
class Grader:
def grade(self):
# get number of questions
numOfQuestions = input("How many questions are there? >> ")
# start gathering answers
i = 1
responses = []
while i <= int(numOfQuestions):
entry = input("\nWhat is your answer for question #" + str(i) + " >> ")
responses += entry
i += 1
# display user responses
print("\nResponses:\n")
j = 1
for r in responses:
print(str(j) + ". " + r)
j+=1
# grade the responses
# input answer key
x = 1
answers = []
while x <= int(numOfQuestions):
aentry = input("\nWhat is the correct answer for question #" + str(x) + " >> ")
answers += aentry
x += 1
# display answer key
print("\nResponses:\n")
y = 1
for z in answers:
print(str(y) + ". " + z)
y+=1
# time to actually grade the exam
numCorrect = 0
for p in responses:
for q in answers:
print(p+" = " +q+" ?")
if p == q:
numCorrect += 1
# issue a grade
print(str(numCorrect))
print("Number of correct answers = " + str(numCorrect) + " out of " + str(numOfQuestions))
grade = int(numOfQuestions) - int(numCorrect)
grade = grade / int(numOfQuestions)
print("Your score is: " + str(grade))
if __name__ == "__main__":
a = Grader()
a.grade()
It's here:
numCorrect = 0
for p in responses:
for q in answers:
print(p+" = " +q+" ?")
if p == q:
numCorrect += 1
That's comparing every response to every answer. You want to compare each response only to its corresponding answer. The easiest way is with the zip function, like:
numCorrect = 0
for p, q in zip(responses, answers):
print(p+" = " +q+" ?")
if p == q:
numCorrect += 1
for comparison you can use zip method with which we can loop two list same time here is a small change for answers comparison for question loop
for p,q in zip(responses,answers):
print(p+" = " +q+" ?")
if p == q:
numCorrect += 1
class Grader:
def grade(self):
# get number of questions
numOfQuestions = input("How many questions are there? >> ")
# start gathering answers
i = 1
responses = []
for i in range(0,int(numOfQuestions)):
entry = input("\nWhat is your answer for question #" + str(i+1) + " >> ")
responses.append(entry)
# display user responses
print("\nResponses:\n")
for i in range(0,len(responses)):
print(str(i) + ". " + responses[i])
# grade the responses
# input answer key
answers = []
for i in range (0,len(responses)):
aentry = input("\nWhat is the correct answer for question #" + str(i+1) + " >> ")
answers.append(aentry)
# display answer key
print("\nResponses:\n")
for i in range(0, len(answers)):
print(str(i) + ". " + answers[i])
# time to actually grade the exam
numCorrect = 0
for i in range(0, len(answers)):
print(str(i)," = ",answers[i]," ?")
if responses[i] == answers[i]:
numCorrect += 1
# issue a grade
print(str(numCorrect))
print("Number of correct answers = " + str(numCorrect) + " out of " + str(numOfQuestions))
grade = int(numOfQuestions) - int(numCorrect)
if grade==int(0.0):
print("Scored 100%")
else:
grade = int(numCorrect)/int(numOfQuestions)
print("Your score is: ",grade)
if __name__ == "__main__":
a = Grader()
a.grade()
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
My code is working for the first input, but now I want to re-prompt the user for their input and repeat the process until the user enters 'stop'. I have tried placing my code within another while loop, creating a different function definition and putting code within the existing if statements.
here is my code so far:
def findInfo(myList, target):
list.sort(myList)
#print myList, target
guesses = 0
low = 0
high = len(myList)-1
mid = (high + low) / 2
while high >= low:
if target == myList[mid][0]:
print "Here are your results:"
print 'state:', myList[mid][0]
print 'total number:', myList[mid][1]
print '% passed:', myList[mid][2]
print '% female students:', myList[mid][3]
return True
elif target > myList[mid][0]:
low = mid + 1
guesses += 1
print "guess", guesses
elif target < myList[mid][0]:
high = mid - 1
guesses += 1
print "guess", guesses
mid = (high + low)/ 2
print False, "no match found"
return False
I'm just really confused about where to put the code to re-ask the user for input until a certain word in entered.
You could use the cmd lib, something similar:
import cmd
class myApp(cmd.Cmd):
def do_findInfo(self,target, myList = defaultList):
list.sort(myList)
#print myList, target
guesses = 0
low = 0
high = len(myList)-1
mid = (high + low) / 2
while high >= low:
if target == myList[mid][0]:
print "Here are your results:"
print 'state:', myList[mid][0]
print 'total number:', myList[mid][1]
print '% passed:', myList[mid][2]
print '% female students:', myList[mid][3]
return True
elif target > myList[mid][0]:
low = mid + 1
guesses += 1
print "guess", guesses
elif target < myList[mid][0]:
high = mid - 1
guesses += 1
print "guess", guesses
mid = (high + low)/ 2
print False, "no match found"
return False
def do_EOF(self, line):
return True
if __name__ == '__main__':
myApp().cmdloop()
this will show you the commandline where you need to enter: "findInfo target"
Why not simply do sth. like this:
def term(s):
return s in ['stop', 'exit', 'quit']
if __name__=='__main__':
inp = ''
while not term(inp):
inp = raw_input('prompt: ')
if not term(inp):
try:
i = int(inp)
print(findInfo(myList, i))
except ValueError as e:
print('Invalid input: {}'.format(e.message))