{"id":75193,"date":"2020-01-15T11:29:16","date_gmt":"2020-01-15T05:59:16","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=75193"},"modified":"2020-01-15T11:29:16","modified_gmt":"2020-01-15T05:59:16","slug":"python-switch","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-switch\/","title":{"rendered":"Python Switch &#8211; Learn approaches to implement switch case statement"},"content":{"rendered":"<p><strong>Switch-case statements<\/strong> are a <strong>strong tool<\/strong> for <strong>control<\/strong> in programming. Switch-case statement may be a <strong>powerful programming<\/strong> feature that <strong>permits<\/strong> you <strong>control the flow<\/strong> of your program supported the <strong>worth<\/strong> of a <strong>variable<\/strong> or an <strong>expression<\/strong>.<\/p>\n<p>The core <strong>Python<\/strong> doesn\u2019t support <strong>switch statements<\/strong> which are available in other popular languages like <strong>C\/C++<\/strong> or <strong>Java<\/strong>.<\/p>\n<p>So in this article, we are going to see a <strong>workaround<\/strong> of how we can implement Python <strong>switch statements<\/strong> on our own.<\/p>\n<h3>Python Switch Approaches<\/h3>\n<p>To implement the <strong>switch statement<\/strong> in Python, we will be using <strong>two approaches<\/strong>.<\/p>\n<h3>1. Python Switch-Case Statement<\/h3>\n<p>First, let us understand how a <strong>switch-case statement<\/strong> works.<\/p>\n<p>If you have come from a <strong>C\/C++<\/strong> or <strong>Java background<\/strong>, then you might already know how <strong>switch case<\/strong> looks like. Here, is a simple C++ program that makes <strong>use<\/strong> of a switch-case statement.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">#include &lt;iostream&gt;\nusing namespace std;\n\nint main()\n{\n   char operator;\n   float num1, num2;\n\n   cout &lt;&lt; \"Enter an operator (+, -, *, \/): \";\n   cin &gt;&gt; operator;\n\n   cout &lt;&lt; \"Enter two numbers: \";\n   cin &gt;&gt; num1 &gt;&gt; num2;\n\nswitch (operator)\n{\n       case '+':\n           cout &lt;&lt; num1 &lt;&lt; \" + \" &lt;&lt; num2 &lt;&lt; \" = \" &lt;&lt; num1+num2;\n           break;\n       case '-':\n           cout &lt;&lt; num1 &lt;&lt; \" - \" &lt;&lt; num2 &lt;&lt; \" = \" &lt;&lt; num1-num2;\n           break;\n       case '*':\n           cout &lt;&lt; num1 &lt;&lt; \" * \" &lt;&lt; num2 &lt;&lt; \" = \" &lt;&lt; num1*num2;\n           break;\n       case '\/':\n           cout &lt;&lt; num1 &lt;&lt; \" \/ \" &lt;&lt; num2 &lt;&lt; \" = \" &lt;&lt; num1\/num2;\n           break;\n       default:\n           \/\/ operator is doesn't match any case constant (+, -, *, \/)\n           cout &lt;&lt; \"Error! Invalid operator\";\n           break;\n}\n\n   return 0;\n}<\/pre>\n<p>The switch statement <strong>allows<\/strong> us to <strong>execute<\/strong> different <strong>operations<\/strong> for different possible <strong>values<\/strong> of a <strong>single variable<\/strong>.<\/p>\n<p>We can define multiple cases for a <strong>switch variable<\/strong>.<\/p>\n<p><strong>Switch case<\/strong> for Python was <strong>proposed<\/strong> but it was <strong>rejected<\/strong>. Since Python doesn\u2019t have this <strong>switch statement<\/strong>, we can implement the switch in Python using <strong>dictionary mappings<\/strong>.<\/p>\n<h3>Implementing Python Switch using Functions<\/h3>\n<p>In python switch, the first way to implement things is the<strong> if-elif ladder<\/strong>. But here we are going to <strong>create a function<\/strong> and use the <strong>Python dictionary<\/strong> to get the functionality similar to <strong>switch-case statements<\/strong>.<\/p>\n<h4>1. Simple Dictionary Mapping<\/h4>\n<p>Let\u2019s implement a function that will take a <strong>number<\/strong> as an <strong>argument<\/strong> and <strong>return<\/strong> us the day of the week.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">def days_of_week(day):\n\n    switcher ={\n        1: 'Monday',\n        2: 'Tuesday',\n        3: 'Wednesday',\n        4: 'Thursday',\n        5: 'Friday',\n        6: 'Saturday',\n        7: 'Sunday'\n    }\n\n    return switcher.get(day,\"Invalid day \")\n\n\nprint( days_of_week(5))\nprint( days_of_week(2))\nprint( days_of_week(7))\nprint( days_of_week(10))<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Friday<br \/>\nTuesday<br \/>\nSunday<br \/>\nInvalid day<\/div>\n<p>Here in python switch, we created the function <strong>days_of_week()<\/strong> and it has a <strong>switcher dictionary<\/strong> that works like a switch where its <strong>keys<\/strong> are the case to <strong>match<\/strong> and its <strong>values<\/strong> are what we want to get <strong>returned<\/strong>.<\/p>\n<p>The <strong>get()<\/strong> method of <strong>dictionary returns<\/strong> us the <strong>value<\/strong> of the <strong>key<\/strong> from the dictionary and if the key does not <strong>exist<\/strong> then it returns the <strong>second argument<\/strong>.<\/p>\n<h4>2. Using Lambdas for Dynamic Functions<\/h4>\n<p>In python switch, Lambda functions are <strong>anonymous functions<\/strong> that can perform operations on a <strong>single expression<\/strong>. Using lambdas functions, we can calculate <strong>different things<\/strong> based on the <strong>input<\/strong>.<\/p>\n<p><strong>Python lambda syntax :<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">lambda arguments : expression<\/pre>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">def calculate(n1, n2, operator):\n\n    switcher ={\n        '+': lambda n1,n2: n1+n2,\n        '-': lambda n1,n2: n1-n2,\n        '*': lambda n1,n2: n1*n2,\n        '\/': lambda n1,n2: n1\/n2,\n\n    }\n\n    return switcher.get(operator)(n1,n2)\n\n\nprint( calculate(10,20,'+'))\nprint( calculate(10,20,'-'))\nprint( calculate(10,20,'*'))\nprint( calculate(10,20,'\/'))<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">30<br \/>\n-10<br \/>\n200<br \/>\n0.5<\/div>\n<h3>Implementing Python Switch-Case using Classes<\/h3>\n<p>It is also easy to implement a <strong>switch case<\/strong> with <strong>class<\/strong>.<\/p>\n<p>Let\u2019s see an example program.<\/p>\n<p>In the below example we call the <strong>switch() <\/strong>method which takes the day of the week and appends it to a <strong>string<\/strong>. Here, we use <strong>getattr()<\/strong> to match method name and in the end, we call the method to get the <strong>desired output<\/strong>.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">class SwitchCase:\n\n    def switch(self, dayOfWeek):\n        default = \"Invalid day\"\n        return getattr(self, 'case_' + str(dayOfWeek), lambda: default)()\n\n    def case_1(self):\n        return \"Monday\"\n\n    def case_2(self):\n        return \"Tuesday\"\n\n    def case_3(self):\n        return \"Wednesday\"\n\n    def case_4(self):\n        return \"Thursday\"\n\n    def case_5(self):\n        return \"Friday\"\n\n    def case_6(self):\n        return \"Saturday\"\n\n    def case_7(self):\n        return \"Sunday\"\n\nday = SwitchCase()\n\nprint(day.switch(1))\nprint(day.switch(0))\nprint(day.switch(3))<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Monday<br \/>\nInvalid day<br \/>\nWednesday<\/div>\n<h3>Summary<\/h3>\n<p>Hence we conclude that even though Python <strong>does not<\/strong> <strong>support<\/strong> the <strong>switch-case decision-making<\/strong> statements, we can <strong>implement<\/strong> them on our own.<\/p>\n<p>We saw two types of implementations in <strong>Python switch<\/strong>, first, we used <strong>dictionary mapping<\/strong> to implement switch with <strong>functions<\/strong> and then implemented the <strong>switch<\/strong> using a <strong>class<\/strong>.<\/p>\n<p>This was all about TechVidvan&#8217;s Python Switch article.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Switch-case statements are a strong tool for control in programming. Switch-case statement may be a powerful programming feature that permits you control the flow of your program supported the worth of a variable or&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":75527,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[1305,1306,1307,1308,1309,1310,1311,1312,1313],"class_list":["post-75193","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-lambdas-for-dynamic-functions","tag-python-switch","tag-python-switch-case","tag-python-switch-case-statement","tag-python-switch-statement","tag-simple-dictionary-mapping","tag-switch-in-python","tag-switch-statement-in-python","tag-switch-case-statement-in-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Switch - Learn approaches to implement switch case statement - TechVidvan<\/title>\n<meta name=\"description\" content=\"Python Switch - Explore how to implement Python switch statements on your own using two approaches, that is, implementing switch using functions &amp; classes.\" \/>\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-switch\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Switch - Learn approaches to implement switch case statement - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Python Switch - Explore how to implement Python switch statements on your own using two approaches, that is, implementing switch using functions &amp; classes.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-switch\/\" \/>\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=\"2020-01-15T05:59:16+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/python-switch.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\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 Switch - Learn approaches to implement switch case statement - TechVidvan","description":"Python Switch - Explore how to implement Python switch statements on your own using two approaches, that is, implementing switch using functions & classes.","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-switch\/","og_locale":"en_US","og_type":"article","og_title":"Python Switch - Learn approaches to implement switch case statement - TechVidvan","og_description":"Python Switch - Explore how to implement Python switch statements on your own using two approaches, that is, implementing switch using functions & classes.","og_url":"https:\/\/techvidvan.com\/tutorials\/python-switch\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-01-15T05:59:16+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/python-switch.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-switch\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-switch\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Python Switch &#8211; Learn approaches to implement switch case statement","datePublished":"2020-01-15T05:59:16+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-switch\/"},"wordCount":512,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-switch\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/python-switch.jpg","keywords":["Lambdas for Dynamic Functions","python switch","python switch case","Python Switch Case Statement","python switch statement","Simple Dictionary Mapping","switch in python","switch statement in python","Switch-case statement in python"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-switch\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-switch\/","url":"https:\/\/techvidvan.com\/tutorials\/python-switch\/","name":"Python Switch - Learn approaches to implement switch case statement - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-switch\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-switch\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/python-switch.jpg","datePublished":"2020-01-15T05:59:16+00:00","description":"Python Switch - Explore how to implement Python switch statements on your own using two approaches, that is, implementing switch using functions & classes.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-switch\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-switch\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-switch\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/python-switch.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/01\/python-switch.jpg","width":802,"height":420,"caption":"python switch"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-switch\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Python Switch &#8211; Learn approaches to implement switch case statement"}]},{"@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\/75193","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=75193"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/75193\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/75527"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=75193"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=75193"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=75193"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}