In this tutorial, we will learn how to create a simple AI (Artificial Intelligence) using Python. We will be using an AI technique called rule-based systems to create a basic AI capable of answering simple questions.
The primary focus will be on understanding the core concepts of AI rather than creating complicated AI models.
A basic understanding of Python programming will also be helpful in following this tutorial.
Step 1: Create a Python Script
First, we will create a new Python file named “simple_ai.py”. Open your favorite text editor or IDE and create a new file with the following content:
1 2 3 4 5 6 7 8 9 10 11 |
def process_input(user_input): # TODO: Implement AI logic here if __name__ == "__main__": print("Welcome to Simple AI") while True: user_input = input("Enter your question: ").strip() if user_input.lower() == "exit": break response = process_input(user_input) print("AI: ", response) |
The above code is a simple skeleton of our AI script. It reads user input in a loop and processes it using the process_input
function. It breaks the loop when the user types “exit”.
Step 2: Implement Rule-Based AI Logic
Now, let’s implement the AI logic inside the process_input
function. We will create a series of if-else conditions to process the user’s input and generate a response.
1 2 3 4 5 6 7 8 9 |
def process_input(user_input): user_input = user_input.lower() if 'hello' in user_input: return "Hello there!" elif 'how are you' in user_input: return "I am an AI, I do not have feelings." else: return "Sorry, I didn't understand your question." |
In this code snippet, we convert the user input to lowercase so that the AI is case-insensitive. Then, we match the user input with predefined rules and return the relevant reply.
Step 3: Test the AI
It’s time to test our simple AI. Run your Python script from the command line or your IDE:
1 |
python simple_ai.py |
And try asking the AI some questions.
Welcome to Simple AI Enter your question: Hello AI: Hello there! Enter your question: How are you? AI: I am an AI, I do not have feelings. Enter your question: Are you a human? AI: Sorry, I didn't understand your question.
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
def process_input(user_input): user_input = user_input.lower() if 'hello' in user_input: return "Hello there!" elif 'how are you' in user_input: return "I am an AI, I do not have feelings." else: return "Sorry, I didn't understand your question." if __name__ == "__main__": print("Welcome to Simple AI") while True: user_input = input("Enter your question: ").strip() if user_input.lower() == "exit": break response = process_input(user_input) print("AI: ", response) |
Conclusion:
In this tutorial, we learned how to create a simple rule-based AI using Python. This example was basic, but it demonstrates the core principle of AI development: processing user input, implementing logic, and generating responses.