![]() |
---|
Image Generated Using Canva |
Rule-based systems are at the heart of many decision-making engines; from medical diagnosis to recommendation engines. These systems apply a set of predefined "if-then" rules to derive conclusions. In this article, you'll learn how to build a basic rule-based engine in Python that mimics real-world decision-making.
What is a rule-based system
How to represent rules in Python
Building a mini inference engine
Testing it on a real-world example
# Step 1: Define rules as functions
def is_fever(temp):
return temp > 99.5
def is_cough(symptoms):
return 'cough' in symptoms
def is_sore_throat(symptoms):
return 'sore throat' in symptoms
# Step 2: Define the rule engine
def diagnose(symptoms, temperature):
rules = {
"Flu": is_fever(temperature) and is_cough(symptoms),
"Common Cold": is_cough(symptoms) and is_sore_throat(symptoms),
"Healthy": not is_fever(temperature) and not is_cough(symptoms)
}
for condition, result in rules.items():
if result:
return condition
return "Unknown Condition"
# Step 3: Run the engine
symptoms = ['cough', 'sore throat']
temperature = 100.2
diagnosis = diagnose(symptoms, temperature)
print("Diagnosis:", diagnosis)
Diagnosis: Flu
You’ve just built a basic rule-based system, the backbone of many early AI applications. While this example is simple, the principles can be extended with complex logic, probabilistic reasoning, or even natural language processing for intelligent decision-making systems. Thanks for reading my article, let me know if you have any suggestions or similar implementations via the comment section. Until then, see you next time. Happy coding!