Welcome, guest | Sign In | My Account | Store | Cart

Python has a feature called conditional expressions, similar to C's ternary operator. For example:

print n, 'is odd' if n % 2 == 1 else 'is even'

Here, the conditional expression is this part of the print statement above:

'is odd' if n % 2 == 1 else 'is even'

This expression evaluates to 'is odd' if the condition after the if keyword is True, and evaluates to 'is even' otherwise.

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.

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.

Python, 32 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
'''
File: return_with_nested_cond_exprs.py 
Purpose: Demonstrate nested conditional expressions used in a return statement, 
to classify letters in a string as lowercase, uppercase or neither.
Also demonstrates doing the same task without a function and a return, 
using a lambda and map instead.
Author: Vasudev Ram
Copyright 2017 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: https://jugad2.blogspot.com
'''

from __future__ import print_function
from string import lowercase, uppercase

# Use return with nested conditional expressions inside a function, 
# to classify characters in a string as lowercase, uppercase or neither:
def classify_char(ch):
    return ch + ': ' + ('lowercase' if ch in lowercase else \
    'uppercase' if ch in uppercase else 'neither')

print("Classify using a function:")
for ch in 'AaBbCc12+-':
    print(classify_char(ch))

print()

# Do it using map and lambda instead of def and for:
print("Classify using map and lambda:")

print('\n'.join(map(lambda ch: ch + ': ' + ('lowercase' if ch in lowercase else 
'uppercase' if ch in uppercase else 'neither'), 'AaBbCc12+-')))