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
Related
I am trying to print an output but I just can't figure out method.
keepAsking = True
author = ""
booktitle = ""
purchaseprice = float()
sellprice = float()
stockcount = int()
margin = float()
bookList = []
priceList = []
while keepAsking == True :
print("Enter Book Data: -")
author = input("Author: ")
if author == "" :
print("Blank Entry")
else :
booktitle = input("Title: ")
if booktitle == "" :
print("Blank Entry")
else :
purchaseprice = input("Purchase Price: ")
if purchaseprice == "" :
print("Incorrect Value")
else :
sellprice = input("Sell Price: ")
if sellprice == "" :
print("Incorrect Value")
else :
bookList.append(author)
bookList.append(booktitle)
if purchaseprice > sellprice :
bookList.remove(author)
bookList.remove(booktitle)
else :
priceList.append(purchaseprice)
priceList.append(sellprice)
stockcount = input("In Stock: ")
if stockcount == "" :
print("Incorrect Value")
else :
priceList.append(stockcount)
margin = ((float(sellprice)-float(purchaseprice))/float(purchaseprice))*100
marginround = round(margin,2)
priceList.append(marginround)
checkContinue = True
while checkContinue == True :
continues = input("Continue? [y/n]")
continuesLower = continues.lower()
if continues == "y" :
checkContinue = False
if continues == "n" :
checkContinue = False
keepAsking = False
and I am trying to get an output like this:
output
I don't really understand array and I have tried a few methods but failed to output it as the image shows. If possible, I would need some explanation too because I want to learn rather than get the answer straight out. So, if you have a solution, I might ask for more information on it too. (you don't have to explain it if you are not comfortable, but I just wish to learn more)
Thank you for attempting to help me. I am sorry if this is just a simple task but I am less than a beginner and trying to improve myself.
I am currently not outputting anything enter image description here
my print code is
for a in bookList :
counter = 0
while counter == len(bookList) :
print(bookList[0] + bookList[1])
print("Purchase Price: " + priceList[0] + "Sell Price: " + priceList[1] + "In Stock: " + priceList [2] + "Margin: " + priceList [3])
If you want to print multiple Book names and prices, etc you should put each one of them into a separate list in this case. (with append)
If you want to print them out you can do like this:
for i in range(0, len(booklist)):
print(author[i] + ' Purchase:' + purchase[i] + ' Sell:' + sell[0]))
... etc to the right format in wich purchase and sell are all lists. Don't forget to add spaces.
To check if the person actually input numbers you can use the method .isdigit()
if purchaseprice.isdigit() != true :
print("Incorrect Value, input numbers")
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 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)
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()
I'm trying to get this problem fixed. I'm creating a program which stores the score in a spreadsheet but when it does, it does not write the score and name in different cell. I have tried adding the column string/row string but always getting error, some guide and help will be appreciated.
So far this is what I have done:
!(http://postimg.org/image/6zn9l43bj/)!
I tried to get a heading saying name and the users name below in each cell and same with score and need some starting point/help
ClassA = open('classa.csv', 'w')
ClassB = open('classb.csv', 'w')
ClassC = open('classc.csv', 'w')
start = True
while start:
user =(input("What is your name?"))
form =(input("Which Group are you in A/B or C ")).lower()
import re
import random
from random import randint
score = 0
for i in range(3):
first_num = random.randint(1,10)
second_num = random.randint(1,10)
choice = (first_num+second_num)
if choice == first_num+second_num:
print ("Question (%d)" % (i+1))
print (first_num)
print("Add (+)")
print(second_num)
check = True
while check:
answer = (input('enter the answer: '))
if not (re.match('-?[0-9]\d*(\.\d+)?$', answer)):
print("Only input numbers")
else:
check = False
answer = int(answer)
if answer == (choice):
print("It's correct!")
score +=1
else:
print("It's wrong!")
print ("The correct answer is: ", choice)
print('')
print(user)
if form == 'a':
ClassA.write("Name: "+str(user) + ' ' + "Score: "+str(score)+"/10" + '\n')
elif form == 'b':
ClassB.write("Name: "+str(user) + ' ' + "Score: "+str(score)+"/10" + '\n')
elif form == 'c':
ClassC.write("Name: "+str(user) + ' ' + "Score: "+str(score)+"/10" + '\n')
yesorno = input("Restart?, Y or N ").lower()
if yesorno == 'y':
start = True
elif yesorno == 'n':
start = False
ClassA.close()
ClassB.close()
ClassC.close()
Thanks
A bit of background: CSV stands for Comma Separated Values, oddly enough Values are quite often separated by semicolons in CSV files and, in fact, (I think) Excel won't recognise columns if you use commas, but it will if you use semicolons. Edit: As pointed out in the comments, this probably depends on regional settings, if in your country the decimal point is usually a comma (e.g. most of Europe) use ;, if it's usually a point use , as separator.
So, back to your question: you are not separating your values, use this instead (notice the semicolon):
ClassA.write("Name: "+str(user) + '; ' + "Score: "+str(score)+"/10" + '\n')
I wouldn't recommend writing the Name: and Score: prefixes either, I would go with a header row (Name; Score; Max Score) and something like this:
ClassA.write("{0}; {1}; {2}\n".format(user, score, max_score))
See also: str.format