Best structure for if statement in Python [closed] - python

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 7 years ago.
Improve this question
I was wondering what is the recommended way or the best way for optimization between the two different functions.
The first one (that I would personally choose):
def myFunction1(aParameter):
if aParameter == 0:
result = 42
elif aParameter == 1:
result = 0
else:
result = None
return result
The second one:
def myFunction2(aParameter):
if aParameter == 0:
return 42
if aParameter == 1:
return 0
return None
If I'm not mistaken, the behaviour of both functions should be the same, so which one would you recommend?
Thank you in advance! :)
Edit:
Thank you for your quick answers. I understand that this question may be opinion-based.
I was just wondering if there is any PEP recommendation about this or one of the two ways which is seen really more often than the other. Furthermore, about performance, I wanted to know if bytecode generated is the same or not.

If it's just the three paths, either way is probably fine. The generally accepted pythonic way when you start having more paths (which would be handled by a switch statement in other languages) is typically with a hash.
def myFunction1(aParameter):
values = {0:42,1:0}
return values.get(aParameter,None)

I prefer the second one because it should be faster, it's cleaner, and easier to read and debug.

Related

What is the most pythonic way to check if a variable is not None? [closed]

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 last year.
Improve this question
When I want to check if an object x is not None, I can either use
if x:
do_something()
or
if x is not None:
do_something()
The first variant feels more pythonic but I think the second variant is easier to read. What is the consensus here?
The two have a different meaning, the first one won't be triggered by most falsy objects ('', False, 0, etc.), the second will. So the logic is different. If you really care about not being None, use the second one.
x = False
if x:
print('one')
if x is not None:
print('two')
output:
two

Best practices on python conditionals [closed]

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 1 year ago.
Improve this question
When it comes to best practices on conditionals, which of the following examples is recommended?
def sum(arg1,arg2):
if arg1>3:
return
else:
return arg1+agr2
or
def sum(arg1,arg2):
if arg1<3:
return arg1+agr2
else:
return
Thanks in advance!
Consider using a ternary expression:
def sum(arg1, arg2):
return arg1 + arg2 if arg1 < 3 else None
As an addendum, if one of the cases is unexpected or undesirable, I like to follow the guard pattern, which involves checking for these cases first before performing your normal logic.
For example,
def safe_divide(a, b):
# Check preconditions at top of function definition
if b == 0:
return None
# Checks passed, perform normal logic
return a / b

Passing a string to eval in method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Struggling with passing a variable reference to a nested function. Using a dictionary is not an option in my use case. It's a much simplified MRE (real use passes an object with many nested objects).
def func(reference):
eval('trueVal=' + reference)
print(trueVal) #Expecting trueVal=15000
trueValue = 15000
reference = 'trueValue'
func(reference)
eval evaluates expressions. The result of your expression in your example can then be assigned to trueVal explicitly:
trueVal = eval(reference)
I would not endorse using eval or exec, 99 times out of 100, there is a better way to do it, dictionary is not the only option but without posting your question its impossible to provide a better way to approach it. below is for reference as an example that works without hardcoding the variable name. But really there is always likely a better approach thatn eval or exec.
def func(reference, value):
exec(reference + '="' + str(value) +'"')
print(reference, ":", eval(reference)) #Expecting trueVal=15000
trueValue = 15000
reference = 'trueVal'
func(reference, trueValue)

According to style is it right to put a funcion like parameter when ending an aplication with sys.exit() in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have seen a code written like this:
if __name__ == "__main__":
#...
result = someFunction(someParameter)
sys.exit(result)
and even like this, where you write the call of the function in the sys.exit() function:
if __name__ == "__main__":
#...
sys.exit(someFunction(someParameter))
Which is the most correct option according to style?
Both are equivalent, but I think you know this. If you are asking from a style perspective, I'd say you should always favour the option that is more readable. In this case, I think the first one is more readable.
Python uses snake_case by convention so you might consider also using that to define your variables and functions.
You might also want to change the name of the result variable to be more descriptive.
exit_status = some_function(some_parameter)
sys.exit(exit_status)
Hopefully, this was what you were after.
Edit: #AnttiHaapala made a good point that succeeded isn't the best variable name either as 0 is Falsy in Python but considered a pass as an exit code. I've renamed it to exit_status.

Is "retval" good python style? [closed]

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 8 years ago.
Improve this question
Is there a strong reason to use a retval variable vs just returning a calculation?
def add(self, x, y):
return x + y
versus
def add(self, x, y):
retval = x + y
return retval
I feel like I usually see retval (or some other named variable) in code examples but it seems like a (small) waste to me.
In this example it won't make a difference but in longer functions it can be beneficial (for subjective reasons) to have one result or retval variable and only return that value at the end. This can make the code easier to understand (provided it is structured well) by only having one return location.
That being said, it depends on the developer's preferences and in some functions multiple return locations are equally readable.
The only reason to use it is when you want to use the value before you return it. for example, printing it before you return.

Categories