Iterating through lists in python - python

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

Related

Python quiz - Where the user can add his questions

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

Why is this code showing number 2 multiple times?

So I'm trying to make a calculator but when i do plus (also with other things but for example) it does work but after the outcome comes it asks for number 2 again, I just want the code to start again.
this is the plus piece of the code:
q = input(str("Wil je de bewerkingsteken legende zien? (j/n): "))
if q == "J" or q == "j" :
print ("\nplus = + ")
print ("min = -")
print ("maal = X")
print ("delen door = :")
print ("quadrateren = Q")
print ("tot de kracht van = P")
print ("Worteltrekken = W")
print ("Procent = %")
num1 = float(input("\n Nummer 1: "))
bew = input("\n Bewerkingsteken: ")
num1_word = (str(num1))
if bew == "+" :
plus_num2 = input(float("\nNummer 2: "))
plus_num2_con = (str(plus_num2))
plus_out = (num1 + plus_num2)
plus_out1 = (str(plus_out))
print ("\n" + num1_con +" + " + num2_con + " = " + plus_out1)
First, you write the input wrong for plus_num2. Try this;
plus_num2 = float(input("\nNummer 2: "))
Second, you define the number's name different from last print function. Try This;
print ("\n" + num1_word +" + " + plus_num2_con + " = " + plus_out1)
Third, if you want to start the code again you can add while True on first line.

How would I make it to where if I get the right answer it will print something

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

How do i check if 2 sentences are similar in my chatbot

I made the simplest kind of chatbot possible. Its one that answers your questions depending on what you wanted it to answer to the same question before. The code is kinda like this:
question = []
answer = []
qcount = 0
stop = 0
b = 0
while stop == 0:
b = 0
q = input("Ask me anything: ")
if q == "stop":
exit()
for i in range(qcount):
if q == question[i]:
b = 1
print(answer[i])
if b == 0:
question.append(q)
qcount = qcount + 1
a = input("How should i answer that? ")
answer.append(a)
Is there a way of turning
if q == question[i]
to
if q is similar to question[i]
?
Aryan Mishra already provided you the answer. I have similar answer for you. You can try this as well. You dont need counters and exit statements. You can define the while statement itself as a gate keeper.
I made some more improvements. While this will NOT give you a perfect chatbot, it comes closer.
question = []
answer = []
q = input("Ask me anything: ")
while q.lower() != 'stop':
i = -1
z = q.lower().split()
z.sort()
for x in question:
y = x.split()
y.sort()
if all(elem in y for elem in z):
i = question.index(x)
if i >= 0:
print(answer[i])
else:
question.append(q.lower())
a = input("How should i answer that? ")
answer.append(a)
q = input("Ask me anything: ")
Output:
Ask me anything: What is your Name
How should i answer that? Joe
Ask me anything: What your name
Joe
Ask me anything: name
Joe
Ask me anything: your name
Joe
Ask me anything: what name
Joe
Ask me anything: what is name
Joe
As you can see, when you ask "what is name" it still assumes you are asking what is your name. You need to work with this to get to a more sophisticated bot. Hope this helps you move in the right direction.
My previous answer is also posted here. Since we are comparing a string to a list, it has to an exact match. checking for q in question does not really give you an advantage. You will need to split the words and compare them. Thats what I did in my new response (see above)
question = []
answer = []
q = input("Ask me anything: ")
while q.lower() != 'stop':
if q.lower() in question:
i = question.index(q.lower())
print (answer[i])
else:
question.append(q.lower())
a = input("How should i answer that? ")
answer.append(a)
q = input("Ask me anything: ")
To Make A Fuzzy Finder Do This By Replacing if q == question[i] to if q in question[i] this does not look for a specific word but looks for a keyword
question = []
answer = []
qcount = 0
stop = 0
b = 0
while stop == 0:
b = 0
q = input("Ask me anything: ")
if q == "stop":
exit()
for i in range(qcount):
if q in question[i]: # HERE IS THE ANSWER
b = 1
print(answer[i])
if b == 0:
question.append(q)
qcount = qcount + 1
a = input("How should i answer that? ")
answer.append(a)

How to create a timer in python [closed]

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

Categories

Resources