Using if/else statement and exit function in Python
Solution 1
You should try to make your code more concise, and with a better flow to it:
import sys
def main():
a, b = map(float, sys.argv[1:2])
if a == 0:
return 1
print b / a
if __name__ == '__main__':
sys.exit(main())
This way you will always get an exit code, and the exit code will be non-zero if a
equals 0
.
Solution 2
Both code fragments are valid and without errors. However, they express slightly different thoughts.
The first states: Depending on the value of a, do either this or that.
The second states: If a isn't fit, abort. (And continue otherwise.)
So the first sees both versions equally as part of the algorithm while the second can easily be read as "in case of this rare variant, just abort".
This has no influence on runtime or stability (as you put it). But you should consider what you want to express. The next developer maintaining your code can be helped or confused, depending on what you express.
Also, later patching of the code, extending it, etc. is influenced by how you write the code. To anticipate this is a form of higher art but it should be in the back of your head when you ask such questions.
In your case I guess that the first version is more prone to introduce later errors because it has two blocks for the second branch (the "then" branch of the if
and below that the surrounding block executing the exit(0)
). This is a slight flaw, and as soon as you want to extend it leaves room for variants. For example, if you want to underline your result, you have two options:
if a == 0.:
exit(1)
else:
print b / a
print '----'
exit(0)
and
if a == 0.:
exit(1)
else:
print b / a
print '----'
exit(0)
Which is better? Or maybe also the exit(0)
should be part of the "then" block? These are the reasons I would prefer the second versions for.
funk
Updated on June 04, 2022Comments
-
funk almost 2 years
The two cases below describe my dilemma. I would like to understand when the code is more stable.
Case A
from sys import argv a = float( argv[1] ) b = float( argv[2] ) if a == 0.: exit(1) else: print b / a exit( 0 )
Case B
from sys import argv a = float( argv[1] ) b = float( argv[2] ) if a == 0.: exit(1) print b / a exit( 0 )