Python Logic Programming: Complete Beginner Guide to AI & kanren
By Braincuber Team
Published on May 6, 2026
Logic programming is a powerful paradigm that lets you focus on what the problem is rather than how to code it. This beginner guide walks you through Python logic programming using kanren and SymPy, showing you how to build rule-based AI systems, match mathematical expressions, and check for prime numbers with practical examples.
What You'll Learn:
- What logic programming is and how it works in Python
- Structure of logic programs: facts, rules, and the Algorithm=Logic+Control concept
- How to install and use kanren for logic-based AI development
- Expression matching with commutative and associative operations
- Checking and generating prime numbers using logic programming
What is Logic Programming in Python?
Logic programming is a way of telling the computer what we want by writing rules. In AI, this is useful when the program needs to make decisions based on facts. Python allows you to write logic-based AI using packages like PyKE and kanren. These tools help your program "think" before giving answers.
Logic programming uses statements like "if this, then that." For example, if a person is older than 18, they can vote. Python lets you create these rules and use them to solve problems. It is very helpful in building expert systems, decision-making tools, and chatbots that work based on logic.
Structure of Logic Programming
Let's talk about facts and rules. Facts are true statements — say, Bucharest is the capital of Romania. Rules are constraints that lead us to conclusions about the problem domain. These are logical clauses that express facts. We use the following syntax to write a rule (as a clause):
H :- B1, ..., Bn.
We can read this as:
H if B1 and ... and Bn.
Here, H is the head of the rule and B1, ..., Bn is the body. A fact is a rule with no body:
H.
An example would be:
fallible(X) :- human(X)
Every logic program needs facts based on which to achieve the given goal. Rules are constraints that get us to conclusions.
Logic and Control
Think of an algorithm as a combination of logic and control.
Algorithm = Logic + Control
In a pure logic programming language, the logic component gets to the solution alone. We can, however, vary the control component for other ways to execute a logic program.
Getting Started With Python Logic Programming
Gearing up for logic programming with Python, we will install a couple of packages. Let's use pip for this.
Install kanren
It lets us express logic as rules and facts, and simplifies making code for business logic. Run: pip install kanren
Install SymPy
This is a Python library for symbolic mathematics. It is nearly a full-featured Computer Algebra System. Run: pip install sympy
Example: Matching Mathematical Expressions
With logic programming, we can compare expressions and find out unknown values. The following step by step guide shows you how to match mathematical expressions using kanren.
from kanren import run, var, fact
from kanren.assoccomm import eq_assoccomm as eq
from kanren.assoccomm import commutative, associative
add = 'add' # Defining operations
mul = 'mul'
fact(commutative, mul) # Addition and multiplication are commutative and associative
fact(commutative, add)
fact(associative, mul)
fact(associative, add)
a, b, c = var('a'), var('b'), var('c') # Defining variables
# 2ab + b + 3c is the expression we have
expression = (add, (mul, 2, a, b), b, (mul, 3, c))
expression = (add, (mul, 3, -2), (mul, (add, 1, (mul, 2, 3)), -1)) # Expression
expr1 = (add, (mul, (add, 1, (mul, 2, a)), b), (mul, 3, c)) # Expressions to match
expr2 = (add, (mul, c, 3), (mul, b, (add, (mul, 2, a), 1)))
expr3 = (add, (add, (mul, (mul, 2, a), b), b), (mul, 3, c))
run(0, (a, b, c), eq(expr1, expression)) # Calls to run()
# Output: ((3, -1, -2),)
run(0, (a, b, c), eq(expr2, expression))
# Output: ((3, -1, -2),)
run(0, (a, b, c), eq(expr3, expression))
# Output: () - mathematically same but structurally different
Important Note
You'll see that the third expression gives us nothing. It is mathematically the same, but structurally different. Logic programming matches structure, not just mathematical equivalence.
Checking for Prime Numbers in Python Logic Programming
If we have a list of numbers, we can find out which ones are prime and also generate such numbers. Let's see how to build this complete tutorial example.
from kanren import isvar, run, membero
from kanren.core import success, fail, goaleval, condeseq, eq, var
from sympy.ntheory.generate import prime, isprime
import itertools as it
def prime_test(n): # Function to test for prime
if isvar(n):
return condeseq([(eq, n, p)] for p in map(prime, it.count(1)))
else:
return success if isprime(n) else fail
n = var() # Variable to use
set(run(0, n, (membero, n, (12, 14, 15, 19, 21, 20, 22, 29, 23, 30, 41, 44, 62, 52, 65, 85)), (prime_test, n)))
# Output: {41, 19, 29, 23}
run(7, n, prime_test(n))
# Output: (2, 3, 5, 7, 11, 13, 17)
Filter Prime Numbers
Extract prime numbers from any list using logic programming. The prime_test function handles both variable and value cases.
Generate Prime Numbers
Generate any number of prime numbers sequentially. Run prime_test with different counts to get the first N primes.
How Logic Programming Works Step by Step
| Component | Purpose | Example |
|---|---|---|
| Facts | True statements about the domain | fallible(X) :- human(X) |
| Rules | Constraints leading to conclusions | H :- B1, B2, ..., Bn |
| Variables | Unknown values to solve for | a, b, c = var('a'), var('b'), var('c') |
| Goals | Conditions that must be satisfied | eq(expr1, expression) |
| Run | Execute logic program to find solutions | run(0, (a,b,c), goal) |
How to Build Your First Logic Program: Step by Step Guide
Define Operations and Properties
Import kanren and define your operations (add, mul). Declare their properties like commutative and associative using fact().
Create Variables
Use var() to create variables that will hold unknown values. These are the values your logic program will solve for.
Build Expressions
Construct expressions using tuples with operation names and variables. For example: (add, (mul, 2, a), b).
Define Goals and Run
Use eq() to create equality goals and run() to execute the logic program and find all solutions that satisfy your constraints.
Frequently Asked Questions
What is the difference between logic programming and imperative programming?
Logic programming focuses on declaring what the problem is through facts and rules, while imperative programming specifies how to solve it step by step. Logic programming is declarative.
How does kanren handle mathematical expression matching?
Kanren matches expressions structurally using associative and commutative properties. It can identify equivalent expressions even when terms are reordered, as long as the structure matches.
Can I use logic programming for real-world AI applications?
Yes, logic programming is widely used in expert systems, chatbots, recommendation engines, and decision-making tools where rule-based reasoning is required.
Why do I need SymPy for logic programming in Python?
SymPy provides the mathematical functions like isprime() and prime() that we use in logic programs to test and generate prime numbers efficiently.
What does the Algorithm = Logic + Control formula mean?
This means an algorithm consists of the logic (what needs to be solved) and control (how to execute it). Logic programming separates these, letting you focus on the problem.
Need Help with AI Development?
Our experts can help you build custom AI solutions using Python, logic programming, and modern machine learning frameworks. Get started today.
