This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
Closed last month.
How might I compress an if/else statement to one line in Python?
An example of Python's way of doing "ternary" expressions:
i = 5 if a > 7 else 0
translates into
if a > 7:
i = 5
else:
i = 0
This actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise I'm not sure it helps that much in creating readable code.
The readability issue was discussed at length in this recent SO question better way than using if-else statement in python.
It also contains various other clever (and somewhat obfuscated) ways to accomplish the same task. It's worth a read just based on those posts.
Python's if can be used as a ternary operator:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
Only for using as a value:
x = 3 if a==2 else 0
or
return 3 if a==2 else 0
There is the conditional expression:
a if cond else b
but this is an expression, not a statement.
In if statements, the if (or elif or else) can be written on the same line as the body of the block if the block is just one like:
if something: somefunc()
else: otherfunc()
but this is discouraged as a matter of formatting-style.
Related
This question already has answers here:
fit "break IF condition" statement into one line
(3 answers)
Closed 4 months ago.
I'm looking for options of shortening syntax for breaking (and continuing) a loop on a condition
for _ in range(10):
if condition:
break
...
I supposed that short curcuits should work, e.g. x == 2 and break, but they cause SyntaxError.
What are Python's options for one-line conditioning, except if condition: break?
You could use itertools.takewhile to combine aspects of a for and while loop, moving the (negated) break condition to the loop's head. The condition in the lambda can use both variables from the enclosing scope and the current item from the iterable.
from itertools import takewhile
for x in takewhile(lambda x: not condition, iterable):
...
However, while this is shorter (at least in terms of lines), I would not consider it more readable. I would just stick with the explicit break.
This question already has answers here:
Is there shorthand for returning a default value if None in Python? [duplicate]
(4 answers)
Closed 12 months ago.
def test(x):
print("in test")
if x >0:
return 1
else:
None
def whennegative():
return 6
myval =test(3) if test(3) else whennegative()
Is there anyway do this one-line if-else without execute test twice? thanks
What you're writing can be summarized as "Do test(3) if it works, and if it doesn't, then here's a fallback". Put another way, that can be summarized as "Do test(3), or else do the fallback".
myval = test(3) or whennegative()
If test(3) is truthy, it'll short circuit out. Otherwise, it'll evaluate whennegative().
There are people who will argue that this is too short and clever, and it can certainly be overused (if you ever see a = (b and c) or d then you've gone too far). But a single or in assignment to mean "here's a fallback" or a single and to mean "here's a point of failure" is pretty well understood by folks and is, indeed, more concise than the ternary alternative.
This question already has answers here:
How to reuse an expression in a comprehension expression?
(2 answers)
Closed 2 years ago.
I have a code that looks like this:
x = ["hello","world","if"]
test = [len(word) for word in x if len(word)>4]
print(test)
in my original code "len" is much complicated function, is there a way to do the calcualtion of len only once?
in a traditional for loop it can be done like this:
test = []
for word in x:
temp= len(word)
if temp > 4:
test.append(temp)
can you please advise how to achieve the same result without using a traditional for loop.
Thanks
You can use := operator (in case of Python 3.8+):
def my_len(s):
# ...other complicated computations...
return len(s)
x = ["hello","world","if"]
test = [l for word in x if (l:=my_len(word))>4]
print(test)
Note: don't overwrite default built-in functions, in this case len(). Other functions may depend on it.
This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
How do "and" and "or" act with non-boolean values?
(8 answers)
Closed 3 years ago.
I am confused with Logical 'And' and 'or' combination in python
I got some idea from Python's Logical Operator And but I couldn't understand combination of 'AND' and 'OR'
a=3
print(a%2 and 'odd' or 'even')
I understood how even was printed if a is 2 ie.,
a= 2, 2%2 = 0 => False.
Then Note String object is considered as True so 'odd' and 'even' are True.
So False and True(odd) or True(even) will give be False(even) object.
But when I didn't understand how even works. If 1st object is True then the output should be immediate True without checking other condition(or operations), how is it going further and printing 'even'
If you are thinking of trying to emulate JavaScript or other languages ternary operators, you have to do it something like this:
print("even" if a%2 == 0 else "odd")
edit: even though this question has been closed (and I don't believe it should be) I will edit it with the understanding about what your question is actually asking.
In python bool(1) == True and bool(0) == False notice how when you modulo 2 these are the only two possible values you can get.
Now go back to your origional print statement:
print(a%2 and 'odd' or 'even')
Combine the fact that 1 is true and 0 is false with the fact that the first condition of a statement ... and [...] or ... returns if the statement is true and the second returns if it is false.
It is then clear to see that when the number is odd causing the number modulo 2 to be 1 it will return the first condition "odd" and when it is 0 it will cause the second condition to be returned "even".
I hope this explains everything.
This question already has answers here:
Using statements on either side of a python ternary conditional
(4 answers)
Closed 4 years ago.
Code:
for i in range(1000):
print(i) if i%10==0 else pass
Error:
File "<ipython-input-117-6f18883a9539>", line 2
print(i) if i%10==0 else pass
^
SyntaxError: invalid syntax
Why isn't 'pass' working here?
This is not a good way of doing this, if you see this problem the structure of your code might not be good for your desires, but this will helps you:
print(i) if i%10==0 else None
This is not a direct answer to your question, but I would like suggest a different approach.
First pick the elements you want to print, then print them. Thus you'll not need empty branching.
your_list = [i for i in range(100) if i%10]
# or filter(lambda e: e%10 == 0, range(100))
for number in your_list:
print number