My basic AI system is responding with the wrong responses [closed] - python
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 15 days ago.
Improve this question
So I was making this basic AI system, where it would detect what the user inputted and compare the input with a list of vocabs that i made for it and then output the appropriate response depending on which category of vocab the user inputted (or output a "no idea what ur talking about" message if the vocabulary that the user inputted is not in it's lists)
Anyway, so it started now outputting the wrong replies whenever it doesn't understand what the User inputted. Now whenever the User input something that is not in it's list, it would reply with a message about 'no swearing' that I made for it to respond to swearings.
#main system
import random
def main_ai_system(user_response):
#lists of greetings that the bot could randomly choose and reply depending on the user input category
greetings = ["hey how are you!", "hello there, how may I help you!", "What's up buddy! How can i help you today!", "Yoooo my friend! How's things!"]
homework_greeting = ["Sorry I'm only a very basic AI and have absolutely ZERO knowledge on that subject", "Sorry, I'm only a very basic AI and currently do not have the knowledge required to help with this subject", "Nope nope nope nope I hate homework you're on your own bye"]
goodbye_greeting = ["Ight seeya later friend!", "Bye bye!", "Ok bye, have a nice day!", "Nice to have talked to you, bye!"]
critisism_greeting = ["Hey dude calm down no critisism in MY terminal", "Hey, do not critisize people! Not nice! Not cool!", "Woah calm down! Off with the grumpyness, jeez."]
laugh_greeting = ["I'm sorry but what's so funny", "Why're you laughing bruh", "Why... are you... laughing...", "Um, ok. Idk what you're laughing about but ok."]
greeting_greeting = ["I'm fine thank you for asking!", "I'm doing OK, thanks!", "Meh, not doing that well", "Bad. BAD.", "*cries* WAAAAH! NOBODY EVER ASKED ME HOW I FELT!"]
whoami_greeting = ["I am JAAIS, an AI system in the Pre-Alpha stages", "I'm JAAIS also known as 'Just Another Artifical Intelligence System'", "I am an AI called JAAIS meaning Just Another Artificial Intelligence System"]
swearing_greeting = ["NO SWEARING", "Please do NOT swear here", "How rude. Don't swear at people.", "Stop your swearing jeez", "Yo why you swearing smh"]
#Detection of user input and categorization, along with responses to different categories of user input
if "hi " in user_response or "hello" in user_response or "hey" in user_response or "what's up" in user_response or "wassup" in user_response or "sup" in user_response or "'sup" in user_response:
return random.choice(greetings)
elif "need help" in user_response or "help" in user_response:
return "Yea sure what dya need help with?"
elif "homework" in user_response or "help with homework" in user_response or "assignment" in user_response:
return "Yea ok tell me the subject, I'll see if i know anything about it."
elif "math" in user_response or "english" in user_response or "history" in user_response or "french" in user_response or "spanish" in user_response or "coding" in user_response or "programming" in user_response or "python" in user_response or "Java" in user_response:
return random.choice(homework_greeting)
elif "whatever" in user_response or "nevermind" in user_response or "bye" in user_response or "seeya" in user_response:
return random.choice(goodbye_greeting)
elif "are stupid" in user_response or "are dumb" in user_response or "dumb" in user_response or "stupid" in user_response or "idiot" in user_response or "dumbass" in user_response:
return random.choice(critisism_greeting)
elif "lol" in user_response or "lmao" in user_response or "haha" in user_response or "hahaha" in user_response or "hahahaha" in user_response or "lmfao" in user_response:
return random.choice(laugh_greeting)
elif "how are" in user_response or "what's up" in user_response or "wassup" in user_response or "wazzup" in user_response or "sup" in user_response or "how's thing" in user_response or "how's things" in user_response or "how're" in user_response or "you?" in user_response:
return random.choice(greeting_greeting)
elif "I'm good" in user_response or "i'm fine" in user_response or "I'm ok" in user_response or "i'm gud" in user_response or "i am good" in user_response or "I am fine" in user_response or "I am ok" in user_response:
return "Nice to hear! I am also feeling very well."
elif "I'm bad" in user_response or "meh" in user_response or "I'm angry" in user_response or "i'm sad" in user_response or "i am angry" in user_response or "I am sad" in user_response or "I am meh" in user_response:
return "Sometimes we might have depressing moments in life. Don't be discouraged! Always look at the bright side of things."
elif "admin" in user_response:
return "Admin refers to my creator, Zhenlong Yu."
elif "oh" in user_response:
return "yea"
elif "who are you" in user_response or "what are you" in user_response or "are you"in user_response or "what you are" in user_response or "who you are" in user_response:
return random.choice(whoami_greeting)
elif "fuck" in user_response or "shut up" in user_response or "bitch" in user_response or "shit":
return random.choice(swearing_greeting)
else:
return "Sorry, I'm currently only in the most basic phase of learning and as such do not currently understandwhat you're saying."
#introduction of AI
print("Hey, I am JAAIS, otherwise known by Admin as 'Just Another Artificial Intelligence System'")
#running the main program
while True:
user_response = input("You: ")
if user_response == "quit":
break
bot_response = main_ai_system(user_response.lower())
print("JAAIS: " + bot_response)
so that's the code pls help idk why but whenever a user input something it doesn't recognize like "xjcfevwgbnicjer" it would output an answer from the 'swearing_greetings' list
"xjcfevwgbnicjer" would output an answer from the 'swearing_greetings' list
because it fulfills no other if-/elif-condition and in the last elif-condition for the swearing_greeting list you forgot to check if "shit" is in user_response. And because "shit" as not empty string always evaluates to True ( as mentioned in comments to your question by B Remmelzwaal ) the last condition for answer choice from swearing_greeting list is triggered for all user input not handled by other if/elif conditions.
Use:
... or "shit" in user_response.split():
to get the right response:
Sorry, I'm currently only in the most basic phase of learning and as such do not currently understandwhat you're saying.
You can also use:
elif any( (word in user_response.split()) for word in ["fuck", "shut up", "bitch", "shit"]):
instead of or.
Following the advice given by Tim Roberts in the comments to your question best you choose another way of structuring your data. The one proposed below:
#main system
import random
#lists of greetings that the bot could randomly choose and reply depending on the user input category
# The choosen response DEPENDS on the ORDER of the entries in the list.
# First found phrase triggers the answer:
response_engine = [
( "greeting",
[ "hi ", "hello", "hey", "what's up", "wassup", "sup", "'sup" ],
["hey how are you!", "hello there, how may I help you!", "What's up buddy! How can i help you today!", "Yoooo my friend! How's things!" ]
),
( "goodbye",
[ "whatever", "nevermind", "bye", "seeya" ],
[ "Ight seeya later friend!", "Bye bye!", "Ok bye, have a nice day!", "Nice to have talked to you, bye!" ]
),
( "critisism",
[ "are stupid", "are dumb", "dumb", "stupid", "idiot", "dumbass" ],
["Hey dude calm down no critisism in MY terminal", "Hey, do not critisize people! Not nice! Not cool!", "Woah calm down! Off with the grumpyness, jeez."]
),
( "laugh",
["lol", "lmao", "haha", "hahaha", "hahahaha", "lmfao"],
["I'm sorry but what's so funny", "Why're you laughing bruh", "Why... are you... laughing...", "Um, ok. Idk what you're laughing about but ok."]
),
( "greeting_greeting",
["how are", "what's up", "wassup", "wazzup", "sup", "how's thing", "how's things", "how're", "you?"],
["I'm fine thank you for asking!", "I'm doing OK, thanks!", "Meh, not doing that well", "Bad. BAD.", "*cries* WAAAAH! NOBODY EVER ASKED ME HOW I FELT!"]
),
( "whoami",
["who are you", "what are you", "are you", "what you are", "who you are"],
["I am JAAIS, an AI system in the Pre-Alpha stages", "I'm JAAIS also known as 'Just Another Artifical Intelligence System'", "I am an AI called JAAIS meaning Just Another Artificial Intelligence System"]
),
( "swearing",
["fuck", "shut up", "bitch", "shit"],
["NO SWEARING", "Please do NOT swear here", "How rude. Don't swear at people.", "Stop your swearing jeez", "Yo why you swearing smh"]
),
( "help",
["need help", "help"],
["Yea sure what dya need help with?"]
),
( "homework_not_OK",
["math", "english", "history", "french", "spanish", "coding", "programming", "python", "Java"],
["Sorry I'm only a very basic AI and have absolutely ZERO knowledge on that subject", "Sorry, I'm only a very basic AI and currently do not have the knowledge required to help with this subject", "Nope nope nope nope I hate homework you're on your own bye"]
),
# OK must be AFTER not OK:
("homework_OK",
["homework", "help with homework", "assignment"],
["Yea ok tell me the subject, I'll see if i know anything about it."]
),
("greeting_greeting_response_good",
["I'm good", "i'm fine", "I'm ok", "i'm gud", "i am good", "I am fine", "I am ok"],
["Nice to hear! I am also feeling very well."]
),
("greeting_greeting_response_bad",
["I'm bad", "meh", "I'm angry", "i'm sad", "i am angry", "I am sad", "I am meh"],
["Sometimes we might have depressing moments in life. Don't be discouraged! Always look at the bright side of things."]
),
("who_is_admin",
["admin"],
["Admin refers to my creator, Zhenlong Yu."]
),
("oh",
["oh"],
["yea"]
),
# MUST be the last item in the list:
("dont_understand",
[""], # empty string can be found in any string:
["Sorry, I'm currently only in the most basic phase of learning and as such do not currently understand what you're saying."]
),
]
makes the actual response engine code shrink to:
def main_ai_system(user_response):
for response in response_engine:
if any( phrase in user_response for phrase in response[1] ):
return random.choice(response[2])
The "tricks" used in above code are:
using a list to store responses and phrases to search for also in case the list will has only one element to choose from. This makes possible to use the same AI-engine response code for multiple and single response/phrase options.
using Python function any() makes it possible to avoid long chains of or in if-conditions and the within it embedded list comprehension allows to specify an if-condition for all items in a list. By the way: the equivalent function to use in order to replace chains of logical and operators is the Python function all().
Notice that "haha" in:
["lol", "lmao", "haha", "hahaha", "hahahaha", "lmfao"]
makes "hahaha" and "hahahaha" unnecessary unless you change your way of searching for a phrase in user response to comparison of whole words.
Notice also that "wassup" in "greetings" will always cause response out of "greetings", so specifying "wassup" also in "greetings_greetings" doesn't make sense and won't have any effect on the AI-responses to user input unless you remember/log the AI responses and use this log in order to enable response with "greetings_greetings" if the AI already responded with "greetings" previously in the conversation.
Related
How do I stop the program once I have reached a certain line? [duplicate]
This question already has answers here: How do I terminate a script? (14 answers) Closed 2 years ago. I'm trying to create a game in python, a game of multiple choice called "Who wants to be a millionaire?" and the problem is I want the program to stop executing the second question once the user failed to answer the first one. print("What is the tallest being in existence?") input(("If you want to see the choices just press enter. " + name)) print("Is it A, Dinosaur?") print("B, The one and only, Giraffe") print("C,The soul of the ocean Whale") print("or D, None") print("So what do you believe is the answer ? " + name + " ") answer_1 = input() if answer_1 == Q1_answer: print("Correct! You Have Earned 100,000$ ") score = +100000 if answer_1 != Q1_answer: print("Im sorry, You have lost the game.") print("Which famous inventor was born in 1856?") print("A Einstein") print("B, Tesla") print("C, Napoleon") print("D, Newton") answer_2 = input() if answer_2 == Q2_answer.lower(): print("Correct! It is Tesla Indeed, Your reached 200,000$ ") score = +100000 else: print("Sorry, wrong answer. You have lost and earned 0$. ")
I think you can write your program in a better way, currently you cannot easily add questions as you will have to repeat the whole code for each new question. You can store all your questions in one list and then iterate over them. I also did not need sys.exit() because of the way I organized the code. Here is the code: questions = [ { "question": "What is the tallest being in existence?", "options": [ "Is it A, Dinosaur?", "B, The one and only, Giraffe", "C,The soul of the ocean Whale", "or D, None" ], "correctOption": "a", "prize": 100_000 }, { "question": "Which famous inventor was born in 1856?", "options": [ "A Einstein", "B, Tesla", "C, Napoleon", "D, Newton" ], "correctOption": "b", "prize": 100_000 } ] isGameWon = True score = 0 for question in questions: print(question['question']) input("If you want to see the choices just press enter.") for option in question['options']: print(option) print("So what do you believe is the answer?") answer = input() if answer.lower() == question['correctOption']: score = score + question['prize'] print("Correct! You Have Earned $" + str(score) + ".") else: isGameWon = False break if (isGameWon): print("Congrats! You have won the game. You earned $" + str(score) + ".") else: print("Sorry, wrong answer. You have lost and earned $0.")
If you want to exit the program completely you need to call the exit method. import sys ... if answer_1 != Q1_answer: print("Im sorry, You have lost the game.") sys.exit()
You can use exit() to exit your program. I`d print a message telling the user that the program will be exited.
I am making a game for my python class and I cannot get it to run
I am making a word python game for my class and the code does not run. I run the code on the command prompt and every time I do nothing happens and I get no errors. I am beginner at python and our assignment for our class was to come up with a game. I am trying make a word/adventure game. I know most people here know more than me so any help would be greatly appreciated! import time import sys A = ["a".lower().strip()] B = ["b".lower().strip()] yes = ["Y", "y", "yes"] no = ["N", "n", "no"] constant = ("ONLY USE A or B!!!") def start(): print ("After a long night of partying and drinking soda with your buds, ") "You wake up in the middle of a lawn and that is when you see a hot chick " "running towards you. This is a weird scenerio because no chicks have ever ran towards you! " "what will you do!?:" time.ZaWardo(1) print(""" A. Ask the girl why is she running and ask if she needs help B. Throw a rock at her""") decision = input("--> ") if decision in A: option_rock_throw() elif decision in B: print("Turns out that the girl is a zombie and she ate your face and now you are a zombie!" "################################ GAME OVER #####################################") sys.exit else: print (constant) start() def option_rock_throw(): print ("You knock out the girl to realize that she is one of your classmates that you had a crush enter code hereon" "so you decide to go check on her to realize that she is a zombie so you smash her head with" "a rock. Now you realize that there is a horde of zombies coming for you. What will you do!?:") time.ZaWardo(1) print(""" A. run into the church and barricade yourself #B. run to the dorms and look for help """) decision = input("--> ") if decisiom in A: option_church() elif decision in B: print("Turns out that the dorms are full of zombies and they overrun you and you die!" "################################ GAME OVER #####################################") sys.exit else: print (constant) start() def option_church(): print ("You run into the church and barricade yourlsef just to find the priest in the church! " "the priest is the first human you have encountered and he tells you that over night there was a " "zombie outbreak! He then asks you if you would like to try and escape! What will your choice be!?") time.ZaWardo(1) decision = input("--> ")
You never call start() outside the function. Place a block like the following at the bottom of your script: if __name__ == "__main__": start()
Relatively new to programming and can't figure out how to exit the magic8ball function back to the gamer function
I made a magic 8 ball program, however, I cannot figure out how to return from the magic 8 ball function to the gamer function. ` def gamer(): choice = int(input("What game do you want to play? \n[1]Magic 8 Ball \n[2]Dice?\n[3]Exit \n")) if choice == 1: def magic8ball(): import random print("\nWelcome to the Magic 8 Ball Program. Input your question and hit enter for the 8 ball to respond") print("What is your question?") userinput = input() choices = ["It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", 'Signs point to yes', "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Dont count on it", "My reply is no", "My sources say no", "Outlook not good", 'Very doubful'] if userinput != "exit" or "EXIT" or "Exit": print(random.choice(choices)) if userinput == "exit" or "Exit" or "EXIT": #Where I need help magic8ball() while True: magic8ball() continue`
You must return some information to the calling context, so that the loop can be broken. You could do sth like this: def magic8ball(): # .... if userinput.lower() == "exit": return True while True: if magic8ball(): break
Rather than signal the caller, I'd make magic8ball() implement it's own loop, returning to the caller's loop when finished: import random ANSWERS = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not good", 'Very doubtful' ] def magic8ball(): print("\nWelcome to the Magic 8 Ball Program.") print("Type your question and hit enter for the Magic 8 ball to respond.") while True: print("What is your question?") userinput = input("> ") if userinput.lower() == "exit": return print(random.choice(ANSWERS)) def gamer(): while True: print("What game do you want to play?\n[1]Magic 8 Ball\n[2]Dice\n[3]Exit") choice = int(input("> ")) if choice == 1: magic8ball() elif choice == 2: pass elif choice == 3: return gamer()
Trouble while using "else"
Can't figure out what i am doing wrong.If someone uses the Wikipedia list,the if for wikipedia will be excecuted together with the else. wikipedia=["search","infromation"] weatherfor=["show weather","weather today","weather forecast","weather"] action=(input("What would you want me to do : ")) if any(word in action for word in wikipedia): print("Here Is What I Found On Wikipedia.") if any(word in action for word in weatherfor): print("The Weather For Today Is") else: print ("Sorry I Haven't learnt this yet")
You have overkilled the if else, try this simple structure: wikipedia=["search", "infromation"] weatherfor=["show weather", "weather today", "weather forecast", "weather"] action=(input("What would you want me to do : ")) if action in wikipedia: print("Here Is What I Found On Wikipedia.") elif aaction in weatherfor: print("The Weather For Today Is") else: print ("Sorry I Haven't learnt this yet") The in would do the job of searching a given value in any iterable (list in this case)
how do I reset a input in python
so i have this code that basically consists of you asking questions, but i have it so the input answers the question, so you can only ask one question, then you have to reset the whole thing again and again, and i have it to ask you your name first so i want a loop that ignores that. print("hello,what is your name?") name = input() print("hello",name) while True: question = input("ask me anything:") if question == ("what is love"): print("love is a emotion that makes me uneasy, i'm a inteligence not a human",name) break if question == ("i want a dog"): print("ask your mother, she knows what to do",name) break if question == ("what is my name"): print("your name is",name) break
Get rid of the breaks, so the loop keeps prompting for new questions. For performance, change the subsequent if tests to elif tests (not strictly necessary, but it avoids rechecking the string if you get a hit early on): while True: question = input("ask me anything:") if question == "what is love": print("love is a emotion that makes me uneasy, i'm a inteligence not a human",name) elif question == "i want a dog": print("ask your mother, she knows what to do",name) elif question == "what is my name": print("your name is",name) Of course, in this specific case, you could avoid the repeated tests by using a dict to perform a lookup, making an arbitrary number of prompts possible without repeated tests: # Defined once up front question_map = { 'what is love': "love is a emotion that makes me uneasy, i'm a inteligence not a human", 'i want a dog': 'ask your mother, she knows what to do', 'what is my name': 'your name is', # Put as many more mappings as you want, code below doesn't change # and performance remains similar even for a million+ mappings } print("hello,what is your name?") name = input() print("hello",name) while True: question = input("ask me anything:") try: print(question_map[question], name) except KeyError: # Or check for "quit"/break the loop/alert to unrecognized question/etc. pass
print("hello,what is your name?") name = input() print("hello",name) while True: question = input("ask me anything:") if question == ("what is love"): print("love is a emotion that makes me uneasy, i'm a inteligence not a human",name) elif question == ("i want a dog"): print("ask your mother, she knows what to do",name) elif question == ("what is my name"): print("your name is",name)
Take out the breaks. Then have one of the options be "quit" with a break