1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Controlling the Flow

From , former About.com Guide

2 of 7

Forming Conditions

Conditions in Python are expressed differently for numeric and string literals. Comparisons of numeric literals are very similar to standard algebraic statements:

Greater than: a > c
Less than: b < 6

Tests for equality, however, are slightly different. In Python, assignment of equality is done with a single equal operator ('='), but testing for equality is done with a double equal operator ('=='). Conversely, testing for inequality is done with a an exclamation point followed by an equal operator. Tests for greater-than-or-equal-to and less-than-or-equal-to are expressed analogously.

Assignment of equality: c = 6
Testing of equality: c == 6
Testing of inequality: c != 6
Greater than or equal to: c >= 6
Less than or equal to: c <= 6

For string literals, on the other hand, there is no greater or less than. It is obviously illogical to test whether 'cat' is greater than 'dog'. Rather, string literals are tested for equality and inequality as follows:

    Testing of equality: cat == 'dog'
    Testing of inequality: cat != 'dog'

There are ways to test whether parts of strings match a given value, but this requires the Python Standard Library modules 're' or 'string', something we will discuss later.

Explore Python
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.