

{"id":27197,"date":"2018-09-07T05:05:30","date_gmt":"2018-09-07T05:05:30","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=27197"},"modified":"2026-04-29T11:03:27","modified_gmt":"2026-04-29T05:33:27","slug":"python-logic-programming","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/","title":{"rendered":"AI with Python &#8211; Python Logic Programming With Example"},"content":{"rendered":"<p><span style=\"font-weight: 400\">Previously, with <strong>AI and Python<\/strong>, we learned about <strong>Computer Vision<\/strong>. Today, we will <strong>see AI with Python<\/strong> Logic Programming. We will learn how to match mathematical expressions and how to check for and generate prime numbers. Also, we will see the example of Python Logic Programming.<\/span><\/p>\n<p>So, let&#8217;s start the Python Logic\u00a0Programming Tutorial.<\/p>\n<h3>What is Logic Programming in Python?<\/h3>\n<p>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 &#8220;think&#8221; before giving answers.<\/p>\n<p>Logic programming uses statements like \u201cif this, then that.\u201d 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.<\/p>\n<h4>a. Structure of Logic Programming<\/h4>\n<h4><span style=\"font-weight: 400\">Let\u2019s 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):<\/span><br \/>\n<b><\/b><\/h4>\n<p><b>H :- B<\/b><b>1<\/b><b>, \u2026, B<\/b><b>n<\/b><b>.<\/b><br \/>\n<span style=\"font-weight: 400\">We can read this as:<\/span><br \/>\n<b>H if B<\/b><b>1<\/b><b> and \u2026 and B<\/b><b>n<\/b><b>.<\/b><br \/>\n<span style=\"font-weight: 400\">Here, H is the head of the rule and B<\/span><span style=\"font-weight: 400\">1<\/span><span style=\"font-weight: 400\">, \u2026, B<\/span><span style=\"font-weight: 400\">n<\/span><span style=\"font-weight: 400\"> is the body. A fact is a rule with no body:<\/span><br \/>\n<b>H.<\/b><\/p>\n<p><span style=\"font-weight: 400\">An example would be:<\/span><\/p>\n<p><strong>fallible(X) :- human(X)<\/strong><br \/>\n<span style=\"font-weight: 400\">Every logic program needs facts based on which to achieve the given goal. Rules are constraints that get us to conclusions.<\/span><\/p>\n<h4>b. Logic and Control<\/h4>\n<p><span style=\"font-weight: 400\">Think of an algorithm as a combination of logic and control.<\/span><\/p>\n<p><strong>Algorithm=Logic+Control<\/strong><\/p>\n<p><span style=\"font-weight: 400\">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.<\/span><\/p>\n<h3>Getting Started With Python Logic Programming<\/h3>\n<p><span style=\"font-weight: 400\">Gearing up for logic programming with Python, we will install a couple of <strong>packages<\/strong>. Let\u2019s use pip for this.<\/span><\/p>\n<p><span style=\"font-weight: 400\"><strong>1. Kanren-<\/strong> It lets us express logic as rules and facts, and simplifies making code for business logic.<\/span><\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; pip install kanren<\/pre>\n<p><span style=\"font-weight: 400\"><strong>2. SymPy-<\/strong> This is a Python library for symbolic mathematics. It is nearly a full-featured Computer Algebra System.<\/span><\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; pip install sympy<\/pre>\n<h3>Example of Logic Programming<\/h3>\n<p><span style=\"font-weight: 400\">With logic programming, we can compare expressions and find out unknown values. Consider the following piece of code:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; from kanren import run,var,fact\r\n&gt;&gt;&gt; from kanren.assoccomm import eq_assoccomm as eq\r\n&gt;&gt;&gt; from kanren.assoccomm import commutative,associative\r\n&gt;&gt;&gt; add='add' #Defining operations\r\n&gt;&gt;&gt; mul='mul'\r\n&gt;&gt;&gt; fact(commutative,mul) #Addition and multiplication are commutative and associative\r\n&gt;&gt;&gt; fact(commutative,add)\r\n&gt;&gt;&gt; fact(associative,mul)\r\n&gt;&gt;&gt; fact(associative,add)\r\n&gt;&gt;&gt; a,b,c=var('a'),var('b'),var('c') #Defining variables\r\n&gt;&gt;&gt; #2ab+b+3c is the expression we have'\r\n&gt;&gt;&gt; expression=(add, (mul, 2, a, b), b, (mul, 3, c))\r\n&gt;&gt;&gt; expression=(add,(mul,3,-2),(mul,(add,1,(mul,2,3)),-1)) #Expression\r\n&gt;&gt;&gt; expr1=(add,(mul,(add,1,(mul,2,a)),b),(mul,3,c)) #Expressions to match\r\n&gt;&gt;&gt; expr2=(add,(mul,c,3),(mul,b,(add,(mul,2,a),1)))\r\n&gt;&gt;&gt; expr3=(add,(add,(mul,(mul,2,a),b),b),(mul,3,c))\r\n&gt;&gt;&gt; run(0,(a,b,c),eq(expr1,expression)) #Calls to run()<\/pre>\n<p><strong>((3, -1, -2),)<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; run(0,(a,b,c),eq(expr2,expression))<\/pre>\n<p><strong>((3, -1, -2),)<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; run(0,(a,b,c),eq(expr3,expression))<\/pre>\n<p><strong>()<\/strong><br \/>\n<span style=\"font-weight: 400\">You\u2019ll see that the third expression gives us nothing. It is mathematically the same, but structurally different.<\/span><\/p>\n<h3>Checking for Prime Numbers in Python Logic Programming<\/h3>\n<p><span style=\"font-weight: 400\">If we have a list of numbers, we can find out which ones are prime and also generate such numbers. Let\u2019s see how.<\/span><\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; from kanren import isvar,run,membero\r\n&gt;&gt;&gt; from kanren.core import success,fail,goaleval,condeseq,eq,var\r\n&gt;&gt;&gt; from sympy.ntheory.generate import prime,isprime\r\n&gt;&gt;&gt; import itertools as it\r\n&gt;&gt;&gt; def prime_test(n): #Function to test for prime\r\nif isvar(n):\r\nreturn condeseq([(eq,n,p)] for p in map(prime,it.count(1)))\r\nelse:\r\nreturn success if isprime(n) else fail\r\n&gt;&gt;&gt; n=var() #Variable to use\r\n&gt;&gt;&gt; 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)))<\/pre>\n<p><strong>{41, 19, 29, 23}<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; run(7,n,prime_test(n))<\/pre>\n<p><strong>(2, 3, 5, 7, 11, 13, 17)<\/strong><\/p>\n<p>So, this was all in Python Logic Programming. Hope you like our explanation.<\/p>\n<h3>Conclusion<\/h3>\n<p>Overall, logic programming is a powerful tool because it lets you focus on what the problem is rather than just telling you how to code it. By using these concepts in Python, you can solve complex puzzles like identifying prime numbers by making it simpler and more logical.<\/p>\n<p>Hence, in this Python AI Logic Programming tutorial, we discussed the meaning of logic programming in Python. Moreover, we saw the example of Logic Programming in Python. Also, we discussed checking for Prime Numbers.<\/p>\n<p>Still, if you have any doubts regarding Python Logic Programming, ask in the comments tab.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Previously, with AI and Python, we learned about Computer Vision. Today, we will see AI with Python Logic Programming. We will learn how to match mathematical expressions and how to check for and generate&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":27233,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11,46],"tags":[402,417,5098,10357,10666,10927,15814],"class_list":["post-27197","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-artificial-intelligence","category-python","tag-ai-python-logic-programming","tag-ai-with-python","tag-getting-started-with-python","tag-python-ai-tutorial","tag-python-logic-programming","tag-python-with-ai","tag-what-is-logic-programming"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>AI with Python - Python Logic Programming With Example - DataFlair<\/title>\n<meta name=\"description\" content=\"Python Logic programming is a powerful tool; by using these concepts in Python, you can solve complex puzzles.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/python-logic-programming\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"AI with Python - Python Logic Programming With Example - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Python Logic programming is a powerful tool; by using these concepts in Python, you can solve complex puzzles.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/python-logic-programming\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-09-07T05:05:30+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-04-29T05:33:27+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/09\/Logic-Programming-With-Python-AI-01.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"AI with Python - Python Logic Programming With Example - DataFlair","description":"Python Logic programming is a powerful tool; by using these concepts in Python, you can solve complex puzzles.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/","og_locale":"en_US","og_type":"article","og_title":"AI with Python - Python Logic Programming With Example - DataFlair","og_description":"Python Logic programming is a powerful tool; by using these concepts in Python, you can solve complex puzzles.","og_url":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-09-07T05:05:30+00:00","article_modified_time":"2026-04-29T05:33:27+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/09\/Logic-Programming-With-Python-AI-01.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"AI with Python &#8211; Python Logic Programming With Example","datePublished":"2018-09-07T05:05:30+00:00","dateModified":"2026-04-29T05:33:27+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/"},"wordCount":590,"commentCount":4,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/09\/Logic-Programming-With-Python-AI-01.jpg","keywords":["AI - Python Logic Programming","AI with Python","Getting Started with Python","Python AI Tutorial","Python Logic Programming","Python with AI","What is Logic Programming?"],"articleSection":["Artificial Intelligence Tutorials","Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/python-logic-programming\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/","url":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/","name":"AI with Python - Python Logic Programming With Example - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/09\/Logic-Programming-With-Python-AI-01.jpg","datePublished":"2018-09-07T05:05:30+00:00","dateModified":"2026-04-29T05:33:27+00:00","description":"Python Logic programming is a powerful tool; by using these concepts in Python, you can solve complex puzzles.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/python-logic-programming\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/09\/Logic-Programming-With-Python-AI-01.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/09\/Logic-Programming-With-Python-AI-01.jpg","width":1200,"height":628,"caption":"AI - Python Logic Programming With Example"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/python-logic-programming\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Artificial Intelligence Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/artificial-intelligence\/"},{"@type":"ListItem","position":3,"name":"AI with Python &#8211; Python Logic Programming With Example"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/27197","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=27197"}],"version-history":[{"count":7,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/27197\/revisions"}],"predecessor-version":[{"id":148046,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/27197\/revisions\/148046"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/27233"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=27197"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=27197"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=27197"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}