{"id":115245,"date":"2020-07-10T06:01:42","date_gmt":"2020-07-10T06:01:42","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=10641"},"modified":"2020-07-10T06:01:42","modified_gmt":"2020-07-10T06:01:42","slug":"python-one-line-ternary","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/10\/python-one-line-ternary\/","title":{"rendered":"Python One Line Ternary"},"content":{"rendered":"<p><strong>Ternary<\/strong> (from Latin <em>ternarius<\/em>) is an adjective meaning <em>&#8220;composed of three items&#8221;<\/em>. (<a href=\"https:\/\/en.wikipedia.org\/wiki\/Ternary\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/en.wikipedia.org\/wiki\/Ternary\">source<\/a>) So, literally, the ternary operator in Python is composed of three operands.<\/p>\n<p><strong>Syntax<\/strong>: The three operands are written in an intuitive combination <code>... if ... else ...<\/code>.<\/p>\n<pre class=\"wp-block-preformatted\">&lt;On True> if &lt;Condition> else &lt;On False><\/pre>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<thead>\n<tr>\n<th>Operand<\/th>\n<th>Description<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>&lt;On True><\/td>\n<td>The return expression of the operator in case the condition evaluates to <code>True<\/code><\/td>\n<\/tr>\n<tr>\n<td>&lt;Condition><\/td>\n<td>The condition that determines whether to return the &lt;On True> or the &lt;On False> branch.<\/td>\n<\/tr>\n<tr>\n<td>&lt;On False><\/td>\n<td>The return expression of the operator in case the condition evaluates to <code>False<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table><figcaption><em>Operands of the Ternary Operator<\/em><\/figcaption><\/figure>\n<p>Let&#8217;s have a look at a minimum example in our interactive code shell:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/42f3df6ddd\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Run the code and input your age. What&#8217;s the output? Run the code again and try to change the output!<\/em><\/p>\n<p>Let&#8217;s dive into the different variants of the Ternary operator in Python!<\/p>\n<h2>Python Ternary Examples<\/h2>\n<p>Let&#8217;s have a quick overview of a few examples on different methods to use the ternary operator:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\nage = 17 # Method 1: Basic Ternary\nprint('wtf' if age&lt;20 else 'What?') 'wtf' # Method 2: Ternary Tuple\n# (onFalse, onTrue) [condition]\nprint(('wtf', 'What?') [age&lt;20]) 'What?' # Method 3: Ternary Dictionary\n# Use Dictionary True\/False values\nprint({True: 'wtf', False: 'What?'} [age&lt;20]) 'wtf' # Method 4: Ternary Lambda\n# Lambda function with 0 arguments\n# Execute only one branch expression --> more efficient\nprint((lambda: 'wtf', lambda:'What?') [age&lt;20]()) 'What?'\n<\/pre>\n<p>Some of them are pretty confusing, right? Stay with me for a moment because you&#8217;ll learn about each of those next! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/72x72\/1f642.png\" alt=\"\ud83d\ude42\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<h2>Python Ternary Tuple<\/h2>\n<\/p>\n<\/p>\n<h2>Python Ternary Dictionary<\/h2>\n<h2>Python Ternary Lambda<\/h2>\n<h2>Python Ternary Multiple Lines<\/h2>\n<h2>Python Ternary Elif<\/h2>\n<h2>Python Ternary Nested<\/h2>\n<h2>Python Ternary Plot<\/h2>\n<h2>Python Ternary Diagram<\/h2>\n<h2>Python Ternary Evaluation Order<\/h2>\n<h2>Python Ternary Try Except<\/h2>\n<h2>Python Ternary Tree<\/h2>\n<h2>Python Ternary in List Comprehension<\/h2>\n<h2>Python Ternary Pep8 Pythonic<\/h2>\n<h2>Python Ternary Can&#8217;t Assign to Conditional Expression<\/h2>\n<h2>Python Ternary For Loop<\/h2>\n<h2>Python Ternary Break<\/h2>\n<h2>Python Ternary None<\/h2>\n<h2>Python Ternary Multiple Conditions<\/h2>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?<\/p>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n<h2>Python One-Liners Book<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<figure class=\"wp-block-image size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-1024x944.jpg\" alt=\"Python One-Liners\" class=\"wp-image-10007\" width=\"512\" height=\"472\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-300x277.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-768x708.jpg 768w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<p><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\"><em>Python One-Liners<\/em> <\/a>will teach you how to read and write &#8220;one-liners&#8221;: concise statements of useful functionality packed into a single line of code. You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You&#8217;ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You&#8217;ll also learn how to:<\/p>\n<p><strong>\u2022<\/strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy\/nongreedy operators<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting<\/p>\n<p>By the end of the book, you&#8217;ll know how to write Python at its most refined, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<p><strong><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\"><em>Get your Python One-Liners Now!!<\/em><\/a><\/strong><\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"Python One-Liners - Trick 3 Lambda, Map, and Ternary Operator\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/mPowPkO1KSw?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Ternary (from Latin ternarius) is an adjective meaning &#8220;composed of three items&#8221;. (source) So, literally, the ternary operator in Python is composed of three operands. Syntax: The three operands are written in an intuitive combination &#8230; if &#8230; else &#8230;. &lt;On True> if &lt;Condition> else &lt;On False> Operand Description &lt;On True> The return expression of [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-115245","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115245","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=115245"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115245\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=115245"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=115245"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=115245"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}