HomePython Page 8 - Python 101 (part 2): If Wishes Were Pythons
Cookie-Cutter Code - 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 "if-else" construct certainly offers a smidgen more flexibility than the basic "if" construct, but still limits you to only two possible courses of action. If your Python script needs to be capable of handling more than two possibilities, you should reach for the "if-elif-else" construct, which is a happy combination of the two constructs you've just been reading about.
if first condition is true:
elif second condition is true:
elif third condition is true:
... and so on ...
There's one important point to be noted here - as soon as one
of the "if" statements within the block is found to be true, Python will execute the corresponding code, skip the remaining "if" statements in the block, and jump immediately to the lines following the entire "if-elif-else" block.
Take a look at it in action:
print "Welcome to the Amazing Fortune Cookie Generator";
# get input
day = raw_input("Pick a day, any day: ");
# check day and assign fortune
if day == "Monday":
fortune = "Never make anything simple and efficient when a way can
be found to make it complex and wonderful."
elif day == "Tuesday":
fortune = "Life is a game of bridge -- and you've just been
elif day == "Wednesday":
fortune = "What sane person could live in this world and not be
elif day == "Thursday":
fortune = "Don't get mad, get interest."
elif day == "Friday":
fortune = "Just go with the flow control, roll with the crunches,
and, when you get a prompt, type like hell."
fortune = "Sorry, closed on the weekend"
You'll notice that in this case, I've used the raw_input()
function instead of the regular input() function. The difference between the two is minor: raw_input() stores user input as is, while input() attempts to convert user input into a Python expression.
Since Python does not support PHP- or JSP-style "switch/case" conditional statements, the "if-elif-else" construct is the only way to route program control to multiple code blocks.