Top-rated recipes tagged "classification" Code RecipesClassifying characters using nested conditional expressions (Python) 2017-04-27T21:26:00-07:00Vasudev Ram <p style="color: grey"> Python recipe 580792 by <a href="/recipes/users/4173351/">Vasudev Ram</a> (<a href="/recipes/tags/characters/">characters</a>, <a href="/recipes/tags/classification/">classification</a>, <a href="/recipes/tags/conditional_expressions/">conditional_expressions</a>, <a href="/recipes/tags/expressions/">expressions</a>, <a href="/recipes/tags/join/">join</a>, <a href="/recipes/tags/lambda/">lambda</a>, <a href="/recipes/tags/map/">map</a>). </p> <p>Python has a feature called conditional expressions, similar to C's ternary operator. For example:</p> <p>print n, 'is odd' if n % 2 == 1 else 'is even'</p> <p>Here, the conditional expression is this part of the print statement above:</p> <p>'is odd' if n % 2 == 1 else 'is even'</p> <p>This expression evaluates to 'is odd' if the condition after the if keyword is True, and evaluates to 'is even' otherwise.</p> <p>The Python Language Reference section for conditional expressions shows that they can be nested. This recipe shows that we can use nested conditional expressions (within a return statement in a user-defined function) to classify characters into lowercase letters, uppercase letters, or neither.</p> <p>It also shows how to do the same task using map, lambda and string.join, again with a nested conditional expression, but without using return or a user-defined function.</p>