Python 101 (part 2): If Wishes Were Pythons - Comparing Apples And Oranges
(Page 5 of 9 )
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
a = 47;
assigns the value 47 to the variable a, while
a == 47
tests whether the value of a is equal to 47.
Next: If Only... >>
More Python Articles
More By Vikram Vaswani, (c) Melonfire