x*x if x>10

S

ssecorp

I have seen somewhere that you can write something like:

x*x if x>10

but exactly that doesn't work and I can't get any variation to work.

it is possible to nest with an else too.


how do you write it?


and also, is it idiomatic? doesn't seem to add functionality, just
another way of doing the same thing which is quite unpythonic but I
remember reading it was added because it helped simplify the
expression of a certain type of operation.
 
D

Diez B. Roggisch

ssecorp said:
I have seen somewhere that you can write something like:

x*x if x>10

but exactly that doesn't work and I can't get any variation to work.

it is possible to nest with an else too.


how do you write it?


and also, is it idiomatic? doesn't seem to add functionality, just
another way of doing the same thing which is quite unpythonic but I
remember reading it was added because it helped simplify the
expression of a certain type of operation.


It's a ternary operator as found in e.g. C or Java like this;


foo = <condition> ? <true-value> : <false-value>;

And it's become available in python2.5, anything below that version will
throw an error.

Diez
 
A

alex23

I have seen somewhere that you can write something like:

x*x if x>10

but exactly that doesn't work and I can't get any variation to work.

It's called a ternary operator. The format is:

it is possible to nest with an else too.

Sure. You can extend the <false-value> with another ternary operator:

<label> = <value1> if <condition1> else <value2> if <condition2> else
<value3>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,904
Messages
2,570,003
Members
46,359
Latest member
thejackson123

Latest Threads

Top