Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions




The if-else Operator

There are situations where an expression involves a simple condition and a full-sized if statement is distracting syntatic overkill. Python has a handy logic operator that evalutes a condition, then returns either of two values depending on that condition.

Most arithmetic and logic operators have either one or two values. An operation that applies to a single value is called unary. For example -a and abs(b) are examples of unary operations: unary negation and unary absolute value. An operation that applies to two values is called binary. For example, a*b shows the binary multiplication operator.

The if-else operator trinary. It involves a conditional expression and two alternative expressions. Consequently, it doesn't use a single special character, but uses two keywords: if and else.

The basic form of the operator is expression if condition else expression . Python evaluates the condition first. If the condition is True, then the left-hand expression is evaluated, and that's the value of the operation. If the condition is False, then the else expression is evaluated, and that's the value of the operation.

Here are a couple of examples.

  • average = sum/count if count != 0 else None
  • oddSum = oddSum + ( n if n % 2 == 1 else 0 )

The intent is to have an English-like reading of the statement. "The average is the sum divided by the count if the count is non-zero; otherwise the average is None".

The wordy alterative to the first example is the following.

if count != 0:
    average= sum/count
    average= None

This seems like three extra lines of code to prevent an error in the rare situation of there being no values to average.

Similarly, the wordy version of the second example is the following:

if n % 2 == 0:
    oddSum = oddSum + n

For this second example, the original statement registered our intent very clearly: we were summing the odd values. The long-winded if-statement tends to obscure our goal by making it just one branch of the if-statement.

  Published under the terms of the Open Publication License Design by Interspire