1

Dear fellow C programmers, sorry to ask such a basic question to you, but what would be the equivalent of this:

val = dim == 0 ? 1 : S(dim) * pow(radius * 0.5, dim) / dim

in Python? I am wrapping some C code and I need to know what is going on in this line in order to compare with the Python results...

Adi Inbar
  • 12,097
  • 13
  • 56
  • 69
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
  • 6
    Should't this be addressed "Dear fellow **Python** programmers" ? (I know plenty C programmers, including myself, that know zilch about python). – WhozCraig Aug 24 '13 at 19:02
  • possible duplicate of [Ternary conditional operator in Python](http://stackoverflow.com/questions/394809/ternary-conditional-operator-in-python) – dawg Aug 24 '13 at 19:11

2 Answers2

8

Python Conditional Expression:

From Python 2.5 onwards, the conditional expression - a ? b : c can be written like this:

b if a else c

So, your expression will be equivalent to:

val = 1 if dim == 0 else S(dim) * pow(radius * 0.5, dim) / dim
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

For most languages, including Python(without braces(?) and correct indentation), the following C statement:

val = (dim == 0) ? 1 : S(dim) * pow(radius * 0.5, dim) / dim;

can be written as something like: (minor differences are language specific, etc.)

if (dim == 0)
   {
      val = 1;
   } else {
      val = S(dim) * pow(radius * 0.5, dim) / dim;
   }

However, the Python code given in a previous answer is very nice!

JackCColeman
  • 3,777
  • 1
  • 15
  • 21