{"id":80171,"date":"2021-01-09T09:00:40","date_gmt":"2021-01-09T03:30:40","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=80171"},"modified":"2021-01-09T09:00:40","modified_gmt":"2021-01-09T03:30:40","slug":"python-exec-syntax-examples","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/","title":{"rendered":"Python Exec() with Syntax and Examples"},"content":{"rendered":"<p>Do you remember that fairy basket?<\/p>\n<p>Nevertheless, it has so much knowledge to give, but it has one rule, one thing at a time.<\/p>\n<p>And today&#8217;s secret of this basket is something Dynamic.<\/p>\n<p>Not taking too much time to learn this new spell, here I introduce to you Exec() function, and of course, our buddy Python is going to do it all for us again. So let&#8217;s learn about Python Exec().<\/p>\n<h2>What is Exec() function in Python?<\/h2>\n<p>Exec() function\u2019s usage is for the dynamic execution of a Python program, which can either be a string or object code in user-defined runtime.<\/p>\n<p>Do you think it is the same as Eval? Of course not.<\/p>\n<p>Did you read it is used for dynamic execution of code? It works on the principle of the dynamic execution of code, which makes it very different from Eval.<\/p>\n<p><strong>What does this mean?<\/strong><\/p>\n<p>This means if it is a string, the string is parsed as a suite of Python statements and then it is executed.<\/p>\n<p>If it is an object code, it is simply executed in a well-defined manner for any integral value in a code.<\/p>\n<p>And one needs to keep in mind that the return statements may not be used outside of function definitions.<\/p>\n<p>Neither even within the context of code which is passed to the exec() function.<\/p>\n<p>This means if it is a string, it simply doesn&#8217;t return any value, hence displays &#8216;none&#8217;.<\/p>\n<h3>Python Exec() Syntax<\/h3>\n<p>The syntax of exec() is<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">exec(object[, globals[, locals]])\n<\/pre>\n<p>Like a choosy designer who accepts only perfect fabric to make a completely lavish robe, exec() does not take everything which is assigned to it.<\/p>\n<h4>Parameters of Exec() in Python<\/h4>\n<ul>\n<li><strong>Object<\/strong>: It can be a string or object code.<\/li>\n<li><strong>Globals<\/strong>: This is a dictionary and the parameter is optional.<\/li>\n<li><strong>Locals<\/strong>: It can be a mapping object and is also optional.<\/li>\n<\/ul>\n<h4>Globals and Locals Parameters in Python Exec()<\/h4>\n<p>Using globals and locals parameters in user-specific codes, a coder can restrict what variables and methods the users can access in runtime.<\/p>\n<p>One can either provide both or just the globals, in such a case that value suffices for both- globals and the local variables can be parsed.<\/p>\n<p>At the module level, globals and locals are the same dictionaries.<\/p>\n<p><strong>Python Exec() Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&gt;&gt;&gt; exec('print(tan(45))')\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">&gt;&gt;&gt; 1<\/div>\n<p><b>Example of Python Exec() Function<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from math import \nexec('print(fact(5))', {'fact': factorial}) \n#factorial re-coded as (fact)\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">120<\/div>\n<h3>When should we use Exec in Python?<\/h3>\n<p>As a side effect, implementation of exec() may insert additional keys into dictionaries.<\/p>\n<p>Besides, the code corresponds to variable names and is set by the executed code.<\/p>\n<p><strong>Python Exec Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">a=int(input(\u201center a number\u201d))\nif: \n  a= 8\n  exec('print(a==8)') \n   If true:\n  \n       exec('print(a+3)')\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">True<br \/>\n11<\/div>\n<h4>Statement Evaluation by Exec()<\/h4>\n<p>Not only the integers, strings, as earlier mentioned, can get evaluated by exec() function. Here is an example of the same:<\/p>\n<p><strong>Python Exec Function Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">for i in range(5):\\n  \nprint('Hello world!')\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Hello world!<br \/>\nHello world!<br \/>\nHello world!<br \/>\nHello world!<br \/>\nHello world!<\/div>\n<h4>Warnings while using Python Exec()<\/h4>\n<p>Sometimes it happens when the coder uses a Unix system (macOS, Linux etc) or has simply imported an os module.<\/p>\n<p>The os module provides a static way in user defined codes to use operating system functionalities such as the read library and appending a file.<\/p>\n<h3>Exec() Vs Eval() in Python<\/h3>\n<p>Eval accepts a single expression while exec operates on Python statements: loops, try: except:, class and function\/method definitions in runtime.<\/p>\n<p>An expression is whatever you can have as the value irrespective of its original domain in the variable assignment of the code.<\/p>\n<p>Eval() returns the value of the given expression, whereas exec ignores the return value from its code, and always returns none in runtime.<\/p>\n<p>Whereas in &#8216;eval&#8217; mode, it compiles a single expression into the bytecode that returns user-specific value of that expression. In the &#8216;eval&#8217; mode the compiler raises an exception in runtime if the source code contains statements that are user static and are also beyond a single expression for any integral value in a code in a definite runtime.<\/p>\n<h4>Restricting Usage of Available Methods and Variables in Exec()<\/h4>\n<p>If both, parameters are being omitted for user-specific codes, the code executed by exec() is executed in the current scope location of the library having any integral or variable value.<\/p>\n<p>The globals and locals parameters (basically dictionaries) are used for global and local variables respectively.<\/p>\n<p>If a local dictionary is omitted, it defaults to the globals dictionary. If the coder passes an empty dictionary as globals for the search, then only the built-ins are available to the object (the first parameter to the exec()) in runtime.<\/p>\n<h2>Summary<\/h2>\n<p>Unlike any other programming language, python has a lot to offer to its coders, with the ease and efficiency function is actually what gives its coders the best in python.<\/p>\n<p>Exec() being one of them makes it so much easier for the coder to evaluate string\/integer in a simple manner.<\/p>\n<p>But unlike any other function, it performs dynamic real-time execution, which can be either for a string or a code.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Do you remember that fairy basket? Nevertheless, it has so much knowledge to give, but it has one rule, one thing at a time. And today&#8217;s secret of this basket is something Dynamic. Not&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":80173,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[3340,2242,3341,3342],"class_list":["post-80171","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-exec-in-python","tag-python","tag-python-exec","tag-python-exec-function"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Exec() with Syntax and Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"exec() function is used for dynamic execution of Python program which can either be a string or object code. Learn Exec() va Eval() in Python\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Exec() with Syntax and Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"exec() function is used for dynamic execution of Python program which can either be a string or object code. Learn Exec() va Eval() in Python\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-01-09T03:30:40+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-exec-function.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=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Exec() with Syntax and Examples - TechVidvan","description":"exec() function is used for dynamic execution of Python program which can either be a string or object code. Learn Exec() va Eval() in Python","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:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/","og_locale":"en_US","og_type":"article","og_title":"Python Exec() with Syntax and Examples - TechVidvan","og_description":"exec() function is used for dynamic execution of Python program which can either be a string or object code. Learn Exec() va Eval() in Python","og_url":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-01-09T03:30:40+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-exec-function.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Python Exec() with Syntax and Examples","datePublished":"2021-01-09T03:30:40+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/"},"wordCount":820,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-exec-function.jpg","keywords":["Exec in python","Python","Python exec","Python Exec function"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/","url":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/","name":"Python Exec() with Syntax and Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-exec-function.jpg","datePublished":"2021-01-09T03:30:40+00:00","description":"exec() function is used for dynamic execution of Python program which can either be a string or object code. Learn Exec() va Eval() in Python","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-exec-function.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-exec-function.jpg","width":1200,"height":628,"caption":"Python exec() function"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-exec-syntax-examples\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Python Exec() with Syntax and Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/80171","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=80171"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/80171\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/80173"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=80171"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=80171"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=80171"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}