Python: If-else Conditionals

Mon 18 May 2015

Filed under Python

The regular if-else statements syntax:

if condition1:
    to_do_if_condition1_istrue
elif condition2:
    to_do_if_condition2_istrue
else:
    to_do_if_no_conditions_istrue

Some alternatives to the regular if-else statements.

Inline if-else

Everything is on one line.

expression_if_true if condition else expression_if_false

It looks at the condition.

  • If it is TRUE, then it does what is on the left.

  • If it is FALSE, then it does what is on the right.

>>> a = 2
>>> b = 3
>>> 'a is larger' if a > b else 'a is smaller'
'a is smaller'

Another example:

def add(a,b):
   return a + b

def subtract(a, b):
   return a - b

add(a, b) if mode=='add' else subtract(a, b)

mode = 'add'
a = 4
b = 6
>>>10

mode = ''
>>>-2

Inline if-else EXPRESSION must always contain else clause.

  • But if you want the variable to maintain its original value if the condition is false, then the expression_if_false can be the original variable. For example: a = 1 if b else a
    Inline also works for list comprehensions:
>>> [f if f.isdigit() else 'not digit' for f in ["1", "h", "l", "8", "9"]]
['1', 'not digit', 'not digit', '8', '9']

which is the same as:

flist =[]
for f in ["1", "h", "l", "8", "9"]:
    if f.isdigit():
        flist.append(f)
    else:
        flist.append('not digit')
return flist


Nested ifs, as inline

>>>student = True
>>>status = "S"
>>>'Freshie' if status == "F" else "not Freshie" if student == True else 'not a student'
>>>'not Freshie'

>>>student = False
>>>status = ''
>>>'Freshie' if status == "F" else "not Freshie" if student == True else 'not a student'
>>>'not a student'

How this one is evaluated:

First, evaluates the RIGHTmost if statement.

  • If it is FALSE, it returns the expression_if_false.

  • If it is TRUE, it looks to the right. In this case it encounters another if-else statement.

Then ,evaluates the next if-else.

  • If it is FALSE, it returns the expression_if_false.

  • If it is TRUE, it looks to the right. In this case it encounters the expression_if_true. And stops there.


Another way to accomplish nested ifs is with a dictionary

>>> def add(a,b):
...     return a + b
... 
>>> def multiply(a, b):
...     return a * b
... 
>>> def subtract(a, b):
...     return a - b
... 
>>>funcs_dict = {'1': add, '2': multiply, '3':subtract}


>>>s='1'
>>>a = 4
>>>b = 5
>>>funcs_dict[s](a, b)
9
>>>funcs_dict['1'](4,5)
9

This is the same as doing this:

def do_func(s,a,b):
    if s == '1':
        add(a,b)
    elif s == '2':
        multiply(a,b)
    elif s == '3':
        subtract(a,b)

do_func('1', 4, 5)

So what is happening here?

  • Defined the three functions.

  • Created a dictionary funcs_dict of the functions. The keywords - in this case a number - and the values are the functions. it a Notice that there are no quotes around the function names.

  • Then somehow (maybe an input from the user, or coming from another function, etc.) we got the value of s. And some values for a and b.

When we evaluate funcs_dict[s](a,b) is when the cool stuff happens.

  • We go into the funcs_dict and pull the value of the given keyword. In this case, we get the value for the keyword '1', which is the function add.

  • And we add the parenthesis to make it a function call. In this case we also have some arguments to pass to the function - the a and b. So what we are really doing is add(a,b)
    NOTE: We could have easily had a function that didn't use arguments, and then of course we wouldn't pass arguments; but it still needs the parentheses. It would look like this: funcs_dict[s]()

This can happen because ... Python functions are first-class objects and can be stored as values in a dictionary. Just remember not to enclose them in quotes.


Comments


DeeKras.com © Dee Kras Powered by Pelican and Twitter Bootstrap. Icons by Font Awesome and Font Awesome More