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. 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: 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.
blog comments powered by Disqus |