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.
Related
This question already has answers here:
Recursive function in simple english [duplicate]
(6 answers)
Closed 11 months ago.
I was making some exercise to train myself and the exercise asked me to do a program that calculates fractals, very simple, i've done in about 1-2 minutes and it work, but looking at his solution it return x multiplicated by the function itself? how does this run? I know maybe it's a stupid question but i think it might be useful.
def fract(x):
if x == 0:
return 1
return x * fract(x - 1)
print(fract(int(input())))
Here's a walk through of whats going on.
First, you call fract(int(input())). The input method gets a response from the user and parses that to an int. and then calls fract on that int.
Say we enter 3. So our print statement evaluates to fract(3).
fract(3) returns 3 * fract(2)
fract(2) is called and that returns 2 * fract(1)
fract(1) is called and that returns 1
So putting it altogether and substituting function calls for what they return we get fract(3) returns 3 * (2 * (1)).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Am i must to use here else: or i have opportunity to remove it and just type return True
def some_function(x):
if another_function(x) == -1:
return False
else:
return True
EDIT: I know how to make this code compact with just one return. The main question is about else:.
Should i always use 'else:' even it is not necessary?
I myself believe that they are not necessary. Returning at the beginning of the function in case of edge cases is something that allows you to skip sometimes lots of indentations caused by elses:
def some_function(x):
if edge_case_1:
return []
if edge_case_2:
return None
#a
#lot
#of
#code
#here
return result
looks better than
def some_function(x):
if edge_case_1:
return []
elif edge_case_2:
return None
else:
#a
#lot
#of
#code
#here
return result
right?
But it's not only about the looks:
Elses like that make you easily confuse the indentation levels.
The line width becomes smaller because the indentation takes those few character, you might need to format your code more to fit PEP8.
Sometimes you write the main part of the code first, only to discover the edge cases later. Version control systems such as git would mark all indented lines as changed (depending on the configuration), while the only thing you did was add those ifs at the beginning!
you can remove else and do like this:
def some_function(x):
if another_function(x) == -1:
return False
return True
Logically you can write
def some_function(x):
return another_function(x) != -1
else is not mandatory syntactically but there are few cases where you will get error
declare default value:-
var1 = some_value
if condition:
var1 = "something"
return var1
For the general case: since the return exits the function at this point and return control to the caller, the prefered idiom is :
def foo(x):
if <some_expression>:
return <something>
# we'll only ever get here if `<some_expression>`'s value is false
return <something_else>
As to why it's the prefered idiom (in python at least): the general consensus is that it makes the code more readable by 1/ flattening it (less indentation levels) and 2/ getting rid of all corner cases right from the start so the nominal case code is not polluted by such considerations. As a general rule, the simpler the code (and "flat" code is simpler than nested one, at least for the human brain) the easiest it is to understand.
Now for your own case where you are returning the boolean value of an expression, you don't even need a if statement at all - you can just directly return the result of evaluating the expression:
def foo(x):
return some_test(x) != some_value
This question already has answers here:
Check if all elements in a list are identical
(30 answers)
Closed 8 years ago.
I am trying to compare elements of a list u for equality.
A possible solution could be all(x == u[0] for x in u[1:]), or simply all(x == u[0] for x in u), but it looks rather weird.
In Python, it's possible to write a == b == c, with its usual "mathematical" meaning. So I thought I could, with the help of the operator module, write operator.eq(*u). However, the eq function takes only two arguments. Of course, functools.reduce(operator.eq, u) is of no use here, since after the first test eq(u[0], u[1]), I get a boolean, and it will fail when doing the second test, eq(<bool>, u[2]).
Is there a better way than the solution above? A more... "pythonic" way?
len(set(u)) == 1 is pretty Pythonic.
This question already has answers here:
Styling multi-line conditions in 'if' statements? [closed]
(30 answers)
Closed 8 years ago.
So I know when listing variables in object class, you can return every line to list the variables vertically for better organization:
class Thing(object):
def __init__(x,
y,
z):
Is it possible to do the same thing with conditionals in an if statement, like so?
if condition1 and
condition2 and
condition3:
Obviously that's probably not the right syntax for it since it doesn't work, but it's a good example of what I'm trying to do in order to organize my code so I don't have scroll to right when something has long names for conditional satements.
Parentheses to the rescue!
if (1 == 1 and
2 == 2 and
3 == 3):
# ...
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.