What is equivalent to Python x = (10 <n)? 10: n;

I was wondering what the equivalent in python for 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 the if statement, but I was curious if there is a shorter syntax.

Thanks.

+4
source share
6 answers
 x = min(n, 10) 

Or more generally:

 x = 10 if 10<n else n 
+17
source

Here is the ternary operator in Python (also known as conditional expressions in documents).

 x if cond else y 
+7
source

There are various ways to do a triple operation, the first is an expression added with 2.5:

 n = foo if condition else bar 

If you want to be compatible with versions below 2.5, you can use the fact that boolean are subclasses of int and that True behaves like 1 , while False behaves like 0 :

 n = [bar, foo][condition] 

Another possibility is to use the way operators behave in Python or more precisely how and and or behave:

 n = condition and foo or bar 
+4
source
 >>> n = 100 >>> x = 10 if n > 10 else n >>> x 10 
+1
source
+1
source
 x = 10 if (10 < n) else n 

(python 2.5 required)

+1
source

Source: https://habr.com/ru/post/1337663/


All Articles