4

I was wondering what the equivalent in python to this would be:

n = 100
x = (10 < n) ? 10 : n;
print x;

For some reason this does not work in Python. I know I can use an if statement but I was just curious if there is some shorter syntax.

Thanks.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
David
  • 41
  • 2
  • What made you think that `?` and `:` formed a legal operator in Python? Where have you seen code like that? What tutorial are you using? – S.Lott Jan 30 '11 at 14:02
  • 1
    I have not; I was basing this on JavaScript syntax; – David Feb 07 '11 at 02:14

6 Answers6

17
x = min(n, 10)

Or, more generally:

x = 10 if 10<n else n
Thomas K
  • 39,200
  • 7
  • 84
  • 86
7

Here is the ternary operator in Python (also know as conditional expressions in the docs).

x if cond else y
istruble
  • 13,363
  • 2
  • 47
  • 52
Jahan Zinedine
  • 14,616
  • 5
  • 46
  • 70
4

There are various ways to make a ternary operation, the first one is the expression added with 2.5:

n = foo if condition else bar

If you want to be compatible with versions lower than 2.5 you can exploit the fact that booleans are subclasses from int and that True behaves like 1 whereas False behaves like 0:

n = [bar, foo][condition]

Another possibility is to exploit the way operators in Python behave or more exactly how and and or behave:

n = condition and foo or bar
DasIch
  • 2,549
  • 1
  • 15
  • 23
  • I like the first and last methods you used, but the middle one wouldn't be immediately obvious to most people reading your code. I find your last method interesting, because it's exactly the same as the `? :` syntax, but with the symbols replaced with `and` and `or`, and it's not hard to read if you understand how `and` and `or` work – Sotanaht Aug 13 '13 at 09:36
1
>>> n = 100
>>> x = 10 if n > 10 else n
>>> x
10
user225312
  • 126,773
  • 69
  • 172
  • 181
1
10 if 10 < n else n 

see http://en.wikipedia.org/wiki/Ternary_operation

1
x = 10 if (10 < n) else n

(requires python 2.5)

Femaref
  • 60,705
  • 7
  • 138
  • 176