DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • The Four Pillars of Programming Logic in Software Quality Engineering
  • Building an AI Nutrition Coach With OpenAI, Gradio, and gTTS
  • Automating Kubernetes RBAC Sync With LDAP Entitlements Using Python
  • Building AI Agents With Python, LangChain, and GPT APIs

Trending

  • How Hackers Exploit Spring Core Vulnerability in 2025: Proactive Measures to Detect Emerging Cyber Threats
  • Tracing Stratoshark’s Roots: From Packet Capture to System Call Analysis
  • Building AI Agents Capable of Exploring Contextual Data for Taking Action
  • Debunking LLM Intelligence: What's Really Happening Under the Hood?
  1. DZone
  2. Coding
  3. Languages
  4. Python Logic Programming With Example

Python Logic Programming With Example

A major part of programming AI is understanding and inputting logic, and this tutorial gives some examples of doing just that in Python.

By 
Rinu Gour user avatar
Rinu Gour
·
Oct. 14, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
36.5K Views

Join the DZone community and get the full member experience.

Join For Free


AI - Python Logic Programming With Example


What is Logic Programming?

Logic programming is a programming paradigm that sees computation as automatic reasoning over a database of knowledge made of facts and rules. It is a way of programming and is based on formal logic. A program in such a language is a set of sentences, in logical form, one that expresses facts and rules about a problem domain. Among others, Datalog is one such major logic programming language family.

Structure

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

Gearing up for logic programming with Python, we will install a couple of packages. Let’s use pip for this.

  • Kanren: It lets us express logic as rules and facts and simplifies making code for business logic.
>>> pip install kanren


  • SymPy: This is a Python library for symbolic mathematics. It is nearly a full-featured Computer Algebra System.
>>> pip install sympy


Python Logic Programming Example

With logic programming, we can compare expressions and find out unknown values. Consider the following piece of code:

>>> 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()


((3, -1, -2),)


 >>> run(0,(a,b,c),eq(expr2,expression))  

((3, -1, -2),)


 >>> run(0,(a,b,c),eq(expr3,expression))  

()

You’ll see that the third expression gives us nothing. It is mathematically the same, but structurally different.

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.

>>> 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)))


{41, 19, 29, 23}


>>> run(7,n,prime_test(n))


(2, 3, 5, 7, 11, 13, 17)


So, this was all in Python Logic Programming. Hope you like our explanation.

Conclusion – Python AI Logic Programming

In this Python AI Logic Programming tutorial, we discussed the meaning of logic programming in Python. Moreover, we saw the example of Python Logic Programming. Also, we discussed the checking for Prime Numbers. Still, if you have any doubt regarding Python Logic Programming, ask in the comment tab.

Logic programming Python (language)

Published at DZone with permission of Rinu Gour. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Four Pillars of Programming Logic in Software Quality Engineering
  • Building an AI Nutrition Coach With OpenAI, Gradio, and gTTS
  • Automating Kubernetes RBAC Sync With LDAP Entitlements Using Python
  • Building AI Agents With Python, LangChain, and GPT APIs

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: