0

This is a question from a book but the return confuses me.
It has a function with three variables and return stuff below:

return (str(a) if b == 0 or a != 1  else '') + ('' if b == 0 else c +('+'+str(b) if b != 1 else ''))

Can anyone separate it into normal way to make it clearer to me? The parentheses with + confused me a lot.

  • This is using ternary form; see here for details: http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator – musical_coder Nov 03 '14 at 03:48
  • which part of it is confusing you? try breaking the statement up remembering that brackets are resolved first. `if x else y` is effectively python's way of putting an if else block on a single line - the ternary operation – Matt Coubrough Nov 03 '14 at 03:49
  • i am clear with condition if and else which is those in the parentheses. but the second part ( + ()) confused me – Mr.Elephant Nov 03 '14 at 03:55

2 Answers2

4

Here's what the code is doing:

def someFunc(a,b,p):
    if b==0 or a!=1:
        part1 = str(a)
    else:
        part1 = ''
    if p==0:
        part2 = ''
    else:
        if b!=1:
            part2 = c + '+'+str(b)
        else:
            part2 = ''
    return part1 + part2
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • 1
    @BillLynch: because `elsif` is not a thing in python. I didn't use `elif`, just to keep things super simple and readable for OP – inspectorG4dget Nov 03 '14 at 03:52
0

The statement returns a string.

The first part evaluates to str(a) if b is 0 or a is not 1. If that statement is false, it evaluates to ".

The second part evaluates to " if b is 0. If that statement is false, it evaluates to c + '+' str(b) if b is not 1. If that statement is false, it evaluates to ".

So you either get "", str(a) + ", str(a) + str(c) + '+'(str(b)), or " + str(c) + '+'(str(b)).

Tetramputechture
  • 2,911
  • 2
  • 33
  • 48