Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58955

Python equivalent for a C expression

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...

Upvotes: 1

Views: 169

Answers (2)

JackCColeman
JackCColeman

Reputation: 3807

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!

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213311

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

Upvotes: 8

Related Questions