Should an if statement have a corresponding else statement? Or, is it OK
to have an if statement by itself. For completeness, it seems the two
should be together, but from experience I know that a if statement by
itself works just fine. Below is an example:
if x >=0:
DO SOMETHING
Would it be better, or perhaps more complete, written like this:
if x >=0:
DO SOMETHING
else:
DO SOMETHING ELSE 6 2464
Bart Nessux wrote: Should an if statement have a corresponding else statement? Or, is it OK to have an if statement by itself. For completeness, it seems the two should be together, but from experience I know that a if statement by itself works just fine. Below is an example:
Only if you actually have s/t senseful to do in the else. Otherwise you end
up with s/t like this:
if <cond>:
...
else:
pass
--
Regards,
Diez B. Roggisch
On Mon, 2004-02-23 at 07:31, Bart Nessux wrote: Should an if statement have a corresponding else statement?
Syntactically, the answer is no--the else statement is optional.
Logically, though, consider this:
if preCondition:
doSomething()
That is, e.g., you're testing for a pre-condition that, if false,
indicates failure. In that case, NOT having an else statement is likely
to mask subtle bugs and it's probably better to have:
if preCondition:
doSomething()
else:
raise RuntimeError('X must be true.')
which itself can be expressed differently so that you don't need the
else, e.g.,
if not preCondition:
raise RuntimeError(...)
doSomething()
;-)
Cheers,
// m
Bart Nessux wrote: Should an if statement have a corresponding else statement? Or, is it OK to have an if statement by itself. For completeness, it seems the two should be together, but from experience I know that a if statement by itself works just fine. Below is an example:
if x >=0: DO SOMETHING
Would it be better, or perhaps more complete, written like this:
if x >=0: DO SOMETHING else: DO SOMETHING ELSE
No direct answer, but a good way to learn about this kind of questions is to
study real code, and the best way to learn from the masters would probably
be to look into the python library.
Now, from the pointless statistics department, a little script that counts
occurences of both if and if...else:
<ifstats.py>
#!/usr/bin/env python
""" Analyse if statements in python scripts
"""
__author__ = "Peter Otten"
__category__ = "Pointless statistics"
import compiler
class IfStats:
def __init__(self):
self.total = 0
self.withElse = 0
def __str__(self):
return "%d of %d if statements have an else branch" %
(self.withElse, self.total)
def visitIf(self, node):
self.total += 1
if node.else_:
self.withElse += 1
if __name__ == "__main__":
import os, sys, optparse
parser = optparse.OptionParser(
usage="usage: \%ifstats [-v] [-r] folder1 ... folderN",
description="scan python scripts for if statements with or without
else branch")
parser.add_option("-v", "--verbose", action="store_true",
help="print info about every processed file")
parser.add_option("-r", "--recursive", action="store_true",
help="recursively collect files")
options, args = parser.parse_args()
totalFiles = 0
totalIf = 0
totalWithElse = 0
failed = 0
for root in args:
for path, folders, files in os.walk(root):
for fn in files:
if fn.endswith(".py"):
fp = os.path.join(path, fn)
try:
a = compiler.parseFile(fp)
except:
failed += 1
print >> sys.stderr, "%s --> FAILED" % fp
else:
stats = IfStats()
compiler.walk(a, stats)
if options.verbose:
print "%s --> %s" % (fp, stats)
else:
sys.stdout.write(".")
sys.stdout.flush()
totalIf += stats.total
totalWithElse += stats.withElse
totalFiles += 1
if not options.recursive: break
print
print "%d of %d if statements with else branch" % (totalWithElse,
totalIf)
print "in %d files" % totalFiles
if failed:
print "parsing failed for %d files" % failed
</ifstats.py>
It turns out that only 2039 of 11157 if statements in the standard library
have an else branch. Now draw your own conclusions...
Peter
On Mon, 23 Feb 2004 08:03:40 -0600, Mark McEahern <ma**@mceahern.com>
wrote: That is, e.g., you're testing for a pre-condition that, if false, indicates failure. In that case, NOT having an else statement is likely to mask subtle bugs and it's probably better to have:
if preCondition: doSomething() else: raise RuntimeError('X must be true.')
which itself can be expressed differently so that you don't need the else, e.g.,
if not preCondition: raise RuntimeError(...) doSomething()
In general, I recommend avoiding "negative" test conditions like this.
However, I recommend them for testing preconditions at the start (or
as early as possible) of a method. When there are multiple,
related/dependent preconditions, using positive tests can lead to
having the *useful* code nested in a confusing bunch of conditions.
Using a linear sequence of negative test conditions at the top makes
it more clear that it is indeed the preconditions being tested
(because the code exits/returns/raises when the condition is true),
rather than business logic. Plus, the business logic is not
unnecessarily indented, which also help avoid long lines wrapping
(your editor and printer prefences may vary).
--dang
Peter Otten wrote: Bart Nessux wrote:
Should an if statement have a corresponding else statement? Or, is it OK to have an if statement by itself. For completeness, it seems the two should be together, but from experience I know that a if statement by itself works just fine. Below is an example:
if x >=0: DO SOMETHING
Would it be better, or perhaps more complete, written like this:
if x >=0: DO SOMETHING else: DO SOMETHING ELSE
No direct answer, but a good way to learn about this kind of questions is to study real code, and the best way to learn from the masters would probably be to look into the python library.
Now, from the pointless statistics department, a little script that counts occurences of both if and if...else:
<ifstats.py> #!/usr/bin/env python """ Analyse if statements in python scripts """ __author__ = "Peter Otten" __category__ = "Pointless statistics"
import compiler
class IfStats: def __init__(self): self.total = 0 self.withElse = 0 def __str__(self): return "%d of %d if statements have an else branch" % (self.withElse, self.total) def visitIf(self, node): self.total += 1 if node.else_: self.withElse += 1
if __name__ == "__main__": import os, sys, optparse parser = optparse.OptionParser( usage="usage: \%ifstats [-v] [-r] folder1 ... folderN", description="scan python scripts for if statements with or without else branch") parser.add_option("-v", "--verbose", action="store_true", help="print info about every processed file") parser.add_option("-r", "--recursive", action="store_true", help="recursively collect files") options, args = parser.parse_args()
totalFiles = 0 totalIf = 0 totalWithElse = 0 failed = 0 for root in args: for path, folders, files in os.walk(root): for fn in files: if fn.endswith(".py"): fp = os.path.join(path, fn) try: a = compiler.parseFile(fp) except: failed += 1 print >> sys.stderr, "%s --> FAILED" % fp else: stats = IfStats() compiler.walk(a, stats) if options.verbose: print "%s --> %s" % (fp, stats) else: sys.stdout.write(".") sys.stdout.flush() totalIf += stats.total totalWithElse += stats.withElse totalFiles += 1 if not options.recursive: break print print "%d of %d if statements with else branch" % (totalWithElse, totalIf) print "in %d files" % totalFiles if failed: print "parsing failed for %d files" % failed </ifstats.py>
It turns out that only 2039 of 11157 if statements in the standard library have an else branch. Now draw your own conclusions...
Peter
Thanks Peter. That's an easy conclusion to come to.
"Diez B. Roggisch" <no**********@web.de> writes: Bart Nessux wrote:
Should an if statement have a corresponding else statement? Or, is it OK to have an if statement by itself. For completeness, it seems the two should be together, but from experience I know that a if statement by itself works just fine. Below is an example:
Only if you actually have s/t senseful to do in the else. Otherwise you end up with s/t like this:
if <cond>: ... else: pass
-- Regards,
Diez B. Roggisch
The question is, why do you need a branch? There are several reasons:
1. Exhaustive enumeration of valid paths, with an exception if none is
detected.
The "enumeration" might be just one item:
if x:
do_x
else:
raise Ex01
It might be a few:
if x:
do_x
elif y:
do_y
else:
raise Ex02
It might be a whole lot of choices, in which case some table lookup
should be used with the exception raised if no lookup case is
found.
2. Partial Enumeration. For this, we do not know that an exception
has occurred if we fall off the list. So we leave off the "else".
Or for clarity, to make very clear that it is optional, we can use
else:
pass
However, I only do that if there confusion on whether or not it
really ought to be full enumeration.
-- ha************@boeing.com
6-6M21 BCA CompArch Design Engineering
Phone: (425) 342-0007 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Brittany |
last post by:
can someone explain to me what if else staments do and what while statements
do.
|
by: dmbkiwi |
last post by:
I am new to this group, and relatively new to python programming, however,
have encountered a problem I just cannot solve through reading the
documentation, and searching this group on google.
I...
|
by: Patrice |
last post by:
Hi,
I need to do multi-conditional statements like below, but this error is
displayed :
Expected 'End'
/myFilepath, line x
else response.write(arrCorpo(sparam,sdiv)) end if
I don't...
|
by: David Cleaver |
last post by:
Hello all,
I was wondering if there were some sort of limitations on the "if"
statement? I'm writing a program which needs to check a bunch of
conditions all at the same time (basically). And...
|
by: sureshjayaram |
last post by:
In some functions where i need to return multiple error codes at
multiple places, I use multiple return statements. Say for ex.
if (Found == 1)
{
if (val == -1)
return error1;
}
else
{
if...
|
by: Amy |
last post by:
Hi,
I have 6 If Then Else statements I was supposed to write. I did so but I
know that they have to be wrong because they all look the same. Could
someone take a look at them and point me in the...
|
by: Navodit |
last post by:
So I have some code like:
if (document.Insurance.State.selectedIndex == 1)
{
ifIll();
}
else if (document.Insurance.State.selectedIndex == 2)
{
elseKan();
}
|
by: Gary Herron |
last post by:
Ohad Frand wrote:
There is no way you can consider 'elif', 'else', 'except', and 'from'
statements. However, as someone pointed out, the kwlist from the
keyword module is the closest thing we...
|
by: Ohad Frand |
last post by:
Hi
Thanks a lot for your reply
I think the main uses for it is to study the language and to see that I
didn't miss anything else or that something is changed from one version
to another.
The...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM).
In this month's session, the creator of the excellent VBE...
|
by: MeoLessi9 |
last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
|
by: DolphinDB |
last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation.
Take...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: Aftab Ahmad |
last post by:
Hello Experts!
I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
|
by: Aftab Ahmad |
last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below.
Dim IE As Object
Set IE =...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
| |