Python 101 (part 2): If Wishes Were Pythons - If Only... (
Page 6 of 9 )
Why do you need to know all this? Well, comparison operators
come in very useful when building conditional expressions - and conditional
expressions come in very useful when adding control routines to your code.
Control routines check for the existence of certain conditions, and execute
appropriate program code depending on what they find.
The first - and
simplest - decision-making routine is the "if" statement, which looks like
this:
if condition:
do this!
The "condition" here refers to a conditional expression,
which evaluates to either true or false. For example,
if hearing spooky noises:
call Ghostbusters!
or, in Python lingo:
if spooky_noises == 1:
callGhostbusters()
If the conditional expression evaluates as true, all
statements within the indented code block are executed. If the conditional
expression evaluates as false, all statements within the indented block will be
ignored, and the lines of code following the "if" block will be
executed.
One of the unique things about Python is that it does not
require you to enclose conditional statement blocks within curly braces, like
most other languages. Instead, Python identifies code blocks according to
indentation; all Python statements with the same amount of indentation are
treated as though they belong to the same code block.
If, however, the
conditional block consists of a single statement, Python also allows you to
place it on the same line as the "if" statement. Consequently, the example above
could also be written as
if spooky_noises == 1: callGhostbusters()
Here's a simple program that illustrates the basics of the
"if" statement.
#!/usr/bin/python
# ask for a number
alpha = input("Gimme a number! ")
# ask for another number
beta = input("Gimme another number! ")
# check
if alpha == beta:
print ("Can't you read, moron? I need two *different* numbers!")
print ("Go away now!")
And they say that the popular conception of programmers as
rude, uncouth hooligans is untrue!