- 2.1 Program Output, the print Statement, and Hello World!
- 2.2 Program Input and the raw_input()Built-in Function
- 2.3 Comments
- 2.4 Operators
- 2.5 Variables and Assignment
- 2.6 Numbers
- 2.7 Strings
- 2.8 Lists and Tuples
- 2.9 Dictionaries
- 2.10 Code Blocks Use Indentation
- 2.11 if Statement
- 2.12 while Loop
- 2.13 for Loop and the range() Built-in Function
- 2.14 List Comprehensions
- 2.15 Files and the open() and file() Built-in Functions
- 2.16 Errors and Exceptions
- 2.17 Functions
- 2.18 Classes
- 2.19 Modules
- 2.20 Useful Functions
- 2.21 Exercises
2.11 if Statement
The standard if conditional statement follows this syntax:
if expression: if_suite
If the expression is non-zero or True, then the statement if_suite is executed; otherwise, execution continues on the first statement after. Suite is the term used in Python to refer to a sub-block of code and can consist of single or multiple statements. You will notice that parentheses are not required in if statements as they are in other languages.
if x < .0: print '"x" must be atleast 0!'
Python supports an else statement that is used with if in the following manner:
if expression: if_suite else: else_suite
Python has an “else-if” spelled as elif with the following syntax:
if expression1: if_suite elif expression2: elif_suite else: else_suite
At the time of this writing, there has been some discussion pertaining to a switch or case statement, but nothing concrete. It is possible that we will see such an animal in a future version of the language. This may also seem strange and/or distracting at first, but a set of if-elif-else statements are not as “ugly” because of Python’s clean syntax. If you really want to circumvent a set of chained if-elif-else statements, another elegant workaround is using a for loop (see Section 2.13) to iterate through your list of possible “cases.”
You can learn more about if, elif, and else statements in the conditional section of Chapter 8.