473,549 Members | 2,746 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

if statements with or w/o else statements

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

Jul 18 '05 #1
6 2492
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
Jul 18 '05 #2
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
Jul 18 '05 #3
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.Option Parser(
usage="usage: \%ifstats [-v] [-r] folder1 ... folderN",
description="sc an python scripts for if statements with or without
else branch")
parser.add_opti on("-v", "--verbose", action="store_t rue",
help="print info about every processed file")
parser.add_opti on("-r", "--recursive", action="store_t rue",
help="recursive ly collect files")
options, args = parser.parse_ar gs()

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(".p y"):
fp = os.path.join(pa th, fn)
try:
a = compiler.parseF ile(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.writ e(".")
sys.stdout.flus h()
totalIf += stats.total
totalWithElse += stats.withElse
totalFiles += 1
if not options.recursi ve: 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

Jul 18 '05 #4
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
Jul 18 '05 #5
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.Option Parser(
usage="usage: \%ifstats [-v] [-r] folder1 ... folderN",
description="sc an python scripts for if statements with or without
else branch")
parser.add_opti on("-v", "--verbose", action="store_t rue",
help="print info about every processed file")
parser.add_opti on("-r", "--recursive", action="store_t rue",
help="recursive ly collect files")
options, args = parser.parse_ar gs()

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(".p y"):
fp = os.path.join(pa th, fn)
try:
a = compiler.parseF ile(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.writ e(".")
sys.stdout.flus h()
totalIf += stats.total
totalWithElse += stats.withElse
totalFiles += 1
if not options.recursi ve: 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.

Jul 18 '05 #6
"Diez B. Roggisch" <no**********@w eb.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 "enumeratio n" 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
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2318
by: Brittany | last post by:
can someone explain to me what if else staments do and what while statements do.
11
97171
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 have written a theme in python for the superkaramba theme engine on kde (see http://netdragon.sourceforge.net - if you are a kde/linux user, it is...
3
3876
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 understand why this 'Expected 'End'' error is called! Here is my code: <%
35
2688
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 I'm pretty sure the rest of the program is working just fine. The only thing I could think might be wrong is that the if statement can only hold so...
24
3625
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 (val2 == -1)
3
3926
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 right direction about what I am not doing correctly? 1.. Write an If Then Else statement that displays the string "Pontiac" in the CarMakeLabel...
17
2632
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(); }
0
1903
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 can think of to the list you are asking for. On the other hand, what's wrong with constructing the list as you did in your example above?
0
1438
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 keyword module will help me Thanks again Ohad Frand
0
7451
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7720
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
6048
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5372
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5089
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3483
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1944
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1061
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
766
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.