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

Forum statistics

Threads
473,816
Messages
2,569,713
Members
45,502
Latest member
Andres34P

Latest Threads

Top