HomePython Page 5 - Python 101 (part 2): If Wishes Were Pythons

Comparing Apples And Oranges - Python

Begin your tour of Python with a look at its number and stringtypes, together with examples of how they can be used in simple Pythonprograms. Along the way, you'll also learn how to build conditionalexpressions, slice and dice strings, and accept user input from the commandline

The examples you've just seen are very rudimentary. To really add some punch, you need to know how to construct what the geeks call a conditional statement. And the very basis of a conditional statement is comparison - for example, "if this is equal to that, do thus and such".

Python comes with a bunch of useful operators designed specifically for use in conditional statements. Here's a list:

Assume delta = 12 and omega = 9
Operator What It Means Expression Evaluates To
------------------------------------------------------------------------------
== is equal to delta == omega False
!= is not equal to delta != omega True
> is greater than delta > omega True
< is less than delta < omega False
>= is greater than or equal to delta >= omega True
<= is less than or equal to delta <= omega False

These comparison operators can be used for both
strings and numbers. A positive result returns true (1), while a negative result returns false (0).

An important point to note - and one which many novice programmers fall foul of - is the difference between the assignment operator (=) and the equality operator (==). The former is used to assign a value to a variable, while the latter is used to test for equality in a conditional expression. So