Here’s a simple Python program that can “learn” from user inputs. It stores knowledge in a dictionary and saves it to a file so it can remember past interactions. This is a very basic AI engine that learns by associating inputs with responses.
import json
import os
class SimpleAI:
def __init__(self, knowledge_file="knowledge.json"):
self.knowledge_file = knowledge_file
self.knowledge = self.load_knowledge()
def load_knowledge(self):
if os.path.exists(self.knowledge_file):
with open(self.knowledge_file, "r") as file:
return json.load(file)
return {}
def save_knowledge(self):
with open(self.knowledge_file, "w") as file:
json.dump(self.knowledge, file, indent=4)
def learn(self, question, answer):
self.knowledge[question.lower()] = answer
self.save_knowledge()
print("Got it! I'll remember that.")
def respond(self, question):
question = question.lower()
if question in self.knowledge:
return self.knowledge[question]
else:
print("I don't know the answer. Can you teach me?")
answer = input("Type the answer: ")
self.learn(question, answer)
return "Thanks! Now I know."
def main():
ai = SimpleAI()
print("Hello! I am a learning AI. Ask me anything!")
while True:
user_input = input("You: ")
if user_input.lower() in ["exit", "quit"]:
print("Goodbye!")
break
response = ai.respond(user_input)
print(f"AI: {response}")
if __name__ == "__main__":
main()
How It Works:
- The AI loads stored knowledge from a JSON file (
knowledge.json). - When a user asks a question, it checks if it already knows the answer.
- If it doesn’t, it asks the user to teach it and saves the new knowledge.
- Next time the same question is asked, it will remember and respond accordingly.
This is a simple approach to a learning AI—kind of like an evolving chatbot! You can extend it further with NLP, machine learning, or external APIs for better performance.