Web Developer's Virtual Library: Encyclopedia of Web Design Tutorials, Articles and Discussions


WDVL Newsletter

jobs.webdeveloper.com

e-commerce
Partner With Us















Developer Channel
FlashKit.com
JavaScript.com
JavaScriptSource
Developer Jobs
ScriptSearch
StreamingMediaWorld
Web Developer's Journal
Web Developer's Virtual Library
WebDeveloper.com
Webreference
Web Hosts
XMLfiles.com

internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Python Control Structures and Functions - Chapt. 4

February 24, 2009

Come along as we learn how to harness the power of control structures and functions in Python.

Excerpted from Programming in Python 3: A Complete Introduction to the Python Language by Mark Summerfield. ISBN: 0137129297, Copyright 2009. Used with the permission of Addison-Wesley Professional.

Control Structures

Python provides conditional branching with if statements and looping with while and for ... in statements. Python also has a conditional expression—this is a kind of if statement that is Python’s answer to the ternary operator (?:) used in C-style languages.

Conditional Branching

As we saw in Chapter 1, this is the general syntax for Python’s conditional branch statement:

if boolean_expression1:
   suite1
elif boolean_expression2:
   suite2
...
elif boolean_expressionN:
   suiteN
else:
   else_suite

There can be zero or more elif clauses, and the final else clause is optional. If we want to account for a particular case, but want to do nothing if it occurs, we can use pass (which serves as a "do nothing" place holder) as that branch’s suite.

In some cases, we can reduce an if...else statement down to a single conditional expression. The syntax for a conditional expression is:

expression1 if boolean_expression else expression2

If the boolean_expression evaluates to True, the result of the conditional expression is expression1; otherwise, the result is expression2.

One common programming pattern is to set a variable to a default value, and then change the value if necessary, for example, due to a request by the user, or to account for the platform on which the program is being run. Here is the pattern using a conventional if statement:

offset = 20
if not sys.platform.startswith("win"):
   offset = 10

The sys.platform variable holds the name of the current platform, for example, "win32" or "linux2". The same thing can be achieved in just one line using a conditional expression:

offset = 20 if sys.platform.startswith("win") else 10

No parentheses are necessary here, but using them avoids a subtle trap. For example, suppose we want to set a width variable to 100 plus an extra 10 if margin is True. We might code the expression like this:

width = 100 + 10 if margin else 0 # WRONG!

What is particularly nasty about this, is that it works correctly if margin is True, setting width to 110. But if margin is False, width is wrongly set to 0 instead of 100. This is because Python sees 100 + 10 as the expression1 part of the conditional expression. The solution is to use parentheses:

width = 100 + (10 if margin else 0) 

The parentheses also make things clearer for human readers.

Conditional expressions can be used to improve messages printed for users. For example, when reporting the number of files processed, instead of printing "0 file(s)", "1 file(s)", and similar, we could use a couple of conditional expressions:

print("{0} file{1}".format((count if count != 0 else "no"),
       ("s" if count != 1 else "")))

This will print "no files", "1 file", "2 files", and similar, which gives a much more professional impression.

Control Structures and Functions - Chapter 4
Looping - Page 2


Up to => Home / Authoring / Tutorials / Python




Jupiter Online Media: internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and Jupiter Online Media

Jupitermedia Corporate Info


Legal Notices, Licensing, & Permissions, Privacy Policy.

Web Hosting | Newsletters | Tech Jobs | Shopping | E-mail Offers