if statements with or w/o else statements

Peter Otten __peter__ at web.de
Mon Feb 23 10:26:35 EST 2004


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




More information about the Python-list mailing list