This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
The code below works such that an array is an input in a function. This 2 element array is iterated such that it would stop if the difference between the new and previously iterated array values equals zero (or it is intended to work as such). Note that the function below is just a pseudo function.
Is using a "OR" and "AND" operator appropriate for what I want. If so, which is best to use and if not, what is a better method?
def func(array):
counter = 0
diff = True
array_i = array
while diff:
array_f = array_i + 1/array_i
diff = abs(array_i[0] - array_f[0]) or abs(array_i[1] - array_f[1]) > 0
array i = array_f
counter += 1
return array_i, counter
The logical operator or is used when you want to check a condition or another condition. The and operator is when both are to be combined.
Checks to see if either one or the other are greater than zero.
abs(array_i[0] - array_f[0]) > 0 or abs(array_i[1] - array_f[1]) > 0
checks to see if both are greater than zero.
abs(array_i[0] - array_f[0]) > 0 and abs(array_i[1] - array_f[1]) > 0
This question already has answers here:
python operator precedence of in and comparison [duplicate]
(3 answers)
Closed 9 years ago.
Consider this list:
list = [1,2,3,4,5]
I want to check if the number 9 is not present in this list. There are 2 ways to do this.
Method 1: This method works!
if not 9 in list: print "9 is not present in list"
Method 2: This method does not work.
if 9 in list == False: print "9 is not present in list"
Can someone please explain why method 2 does not work?
This is due to comparison operator chaining. From the documentation:
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
You are assuming that the 9 in list == False expression is executed as (9 in list) == False but that is not the case.
Instead, python evaluates that as (9 in list) and (list == False) instead, and the latter part is never True.
You really want to use the not in operator, and avoid naming your variables list:
if 9 not in lst:
It should be:
if (9 in list) == False: print "9 is not present in list"
I have read the links below, but it doesn't address my question.
Does Python have a ternary conditional operator? (the question is about condensing if-else statement to one line)
Is there an easier way of writing an if-elif-else statement so it fits on one line?
For example,
if expression1:
statement1
elif expression2:
statement2
else:
statement3
Or a real-world example:
if i > 100:
x = 2
elif i < 100:
x = 1
else:
x = 0
I just feel if the example above could be written the following way, it could look like more concise.
x = 2 if i>100 elif i<100 1 else 0 # [WRONG]
No, it's not possible (at least not with arbitrary statements), nor is it desirable. Fitting everything on one line would most likely violate PEP-8 where it is mandated that lines should not exceed 80 characters in length.
It's also against the Zen of Python: "Readability counts". (Type import this at the Python prompt to read the whole thing).
You can use a ternary expression in Python, but only for expressions, not for statements:
>>> a = "Hello" if foo() else "Goodbye"
Edit:
Your revised question now shows that the three statements are identical except for the value being assigned. In that case, a chained ternary operator does work, but I still think that it's less readable:
>>> i=100
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
0
>>> i=101
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
2
>>> i=99
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
1
If you only need different expressions for different cases then this may work for you:
expr1 if condition1 else expr2 if condition2 else expr
For example:
a = "neg" if b<0 else "pos" if b>0 else "zero"
Despite some other answers: YES it IS possible:
if expression1:
statement1
elif expression2:
statement2
else:
statement3
translates to the following one liner:
statement1 if expression1 else (statement2 if expression2 else statement3)
in fact you can nest those till infinity. Enjoy ;)
Just nest another if clause in the else statement. But that doesn't make it look any prettier.
>>> x=5
>>> x if x>0 else ("zero" if x==0 else "invalid value")
5
>>> x = 0
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'zero'
>>> x = -1
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'invalid value'
There's an alternative that's quite unreadable in my opinion but I'll share anyway just as a curiosity:
x = (i>100 and 2) or (i<100 and 1) or 0
More info here: https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
You can optionally actually use the get method of a dict:
x = {i<100: -1, -10<=i<=10: 0, i>100: 1}.get(True, 2)
You don't need the get method if one of the keys is guaranteed to evaluate to True:
x = {i<0: -1, i==0: 0, i>0: 1}[True]
At most one of the keys should ideally evaluate to True. If more than one key evaluates to True, the results could seem unpredictable.
yes you can by doing this :
i = int(input('type your num here : '))
x = 2 if i > 100 else ( 1 if i < 100 else 0)
print (x)
if i > 100:
x = 2
elif i < 100:
x = 1
else:
x = 0
If you want to use the above-mentioned code in one line, you can use the following:
x = 2 if i > 100 else 1 if i < 100 else 0
On doing so, x will be assigned 2 if i > 100, 1 if i < 100 and 0 if i = 100
The ternary operator is the best way to a concise expression. The syntax is variable = value_1 if condition else value_2. So, for your example, you must apply the ternary operator twice:
i = 23 # set any value for i
x = 2 if i > 100 else 1 if i < 100 else 0
Nested ternary operator is the best solution --
Example case -
4 = 1
3 = 2
2 = 3
1 = 4
a = 4
prio = 4 if a == 1 else (3 if a == 2 else (2 if a == 3 else 1))
People have already mentioned ternary expressions. Sometimes with a simple conditional assignment as your example, it is possible to use a mathematical expression to perform the conditional assignment. This may not make your code very readable, but it does get it on one fairly short line. Your example could be written like this:
x = 2*(i>100) | 1*(i<100)
The comparisons would be True or False, and when multiplying with numbers would then be either 1 or 0. One could use a + instead of an | in the middle.
It also depends on the nature of your expressions. The general advice on the other answers of "not doing it" is quite valid for generic statements and generic expressions.
But if all you need is a "dispatch" table, like, calling a different function depending on the value of a given option, you can put the functions to call inside a dictionary.
Something like:
def save():
...
def edit():
...
options = {"save": save, "edit": edit, "remove": lambda : "Not Implemented"}
option = get_input()
result = options[option]()
Instead of an if-else:
if option=="save":
save()
...
You can use nested ternary if statements.
# if-else ternary construct
country_code = 'USA'
is_USA = True if country_code == 'USA' else False
print('is_USA:', is_USA)
# if-elif-else ternary construct
# Create function to avoid repeating code.
def get_age_category_name(age):
age_category_name = 'Young' if age <= 40 else ('Middle Aged' if age > 40 and age <= 65 else 'Senior')
return age_category_name
print(get_age_category_name(25))
print(get_age_category_name(50))
print(get_age_category_name(75))
MESSAGELENGHT = 39
"A normal function call using if elif and else."
if MESSAGELENGHT == 16:
Datapacket = "word"
elif MESSAGELENGHT == 8:
Datapacket = 'byte'
else:
Datapacket = 'bit'
#similarly for a oneliner expresion:
Datapacket = "word" if MESSAGELENGHT == 16 else 'byte' if MESSAGELENGHT == 8 else 'bit'
print(Datapacket)
Thanks
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python Ternary Operator
Does Python have an equivalent of the ternary operator?:
( x < 5 ? 1 : 0 )
Or must I express the same thing with an if-else pair?
You can use a conditional expression:
1 if x < 5 else 0
In code written for very old versions of Python, you may also see:
x < 5 and 1 or 0
However, the conditional expression form is preferred for Python 2.5 and later.
Python has:
1 if x < 5 else 0
or the old style:
x < 5 and 1 or 0
This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
Closed 3 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I'm just getting into Python and I really like the terseness of the syntax. However, is there an easier way of writing an if-then-else statement so it fits on one line?
For example:
if count == N:
count = 0
else:
count = N + 1
Is there a simpler way of writing this? I mean, in Objective-C I would write this as:
count = count == N ? 0 : count + 1;
Is there something similar for Python?
Update
I know that in this instance I can use count == (count + 1) % N.
I'm asking about the general syntax.
That's more specifically a ternary operator expression than an if-then, here's the python syntax
value_when_true if condition else value_when_false
Better Example: (thanks Mr. Burns)
'Yes' if fruit == 'Apple' else 'No'
Now with assignment and contrast with if syntax
fruit = 'Apple'
isApple = True if fruit == 'Apple' else False
vs
fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True
Moreover, you can still use the "ordinary" if syntax and conflate it into one line with a colon.
if i > 3: print("We are done.")
or
field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural))
count = 0 if count == N else N+1
- the ternary operator. Although I'd say your solution is more readable than this.
General ternary syntax:
value_true if <test> else value_false
Another way can be:
[value_false, value_true][<test>]
e.g:
count = [0,N+1][count==N]
This evaluates both branches before choosing one. To only evaluate the chosen branch:
[lambda: value_false, lambda: value_true][<test>]()
e.g.:
count = [lambda:0, lambda:N+1][count==N]()
<execute-test-successful-condition> if <test> else <execute-test-fail-condition>
with your code-snippet it would become,
count = 0 if count == N else N + 1