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)
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
New to python, probably a dumb question. It's saying the "addAns" in the last line is undefined. How do I get it to use the value from the add function
def add (addL):
c = 0
while c < 4:
x = input("Type a number to add. " )
c += 1
addL.append(x)
if x == "end":
c += 5
addL.remove("end")
addStep = [int(i) for i in addL]
addAns = sum(addStep)
return addAns
userIn = input("What function would you like to perform? ")
if userIn == 'add':
add(addL)
print(addAns)
You should assign the output of the function:
if userIn == 'add':
addAns = add(addL)
print(addAns)
It doesn't need to be the same name, the scopes are independent:
if userIn == 'add':
output = add(addL)
print(output)
You can also directly use the output in print:
if userIn == 'add':
print(add(addL))
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()
Trying to figure out how to work a list of user input integers into separate categories and adding those categories together, and I'm stuck. This is what I have so far:
def main():
again = 'y'
while again == 'y':
pos_values = []
neg_values = []
value = int(input("Please enter value: "))
if value > 0:
pos_values.append(value)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
elif value < 0:
neg_values.append(value)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
else:
print(sum.pos_values)
print(sum.neg_values)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
total = 0
all_values = neg_values + pos_values
print[all_values]
print(total + pos_values)
print(total + neg_values)
main()
I'm just a first year student with no prior experience, so please be gentle!
Once you fix the logic error pointed out by Mike Scotty, the other problems are really just syntax errors. sum.pos_values will give you AttributeError: 'builtin_function_or_method' object has no attribute 'pos_values' (because sum is a built-in function and so needs () not .); and print[all_values] will give you a syntax error (because print is also a built-in function and so needs () not []). Your original code doesn't store zeroes in either list: I haven't changed that. And the output format is a guess on my part.
def main():
again = 'y'
pos_values = []
neg_values = []
while again == 'y':
value = int(input("Please enter value: "))
if value > 0:
pos_values.append(value)
elif value < 0:
neg_values.append(value)
else: #edit: terminate also on 0 input
break
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
all_values = neg_values + pos_values
print(sum(all_values),all_values)
print(sum(pos_values),pos_values)
print(sum(neg_values),neg_values)