Below is a quick example of how to use an if statement in python:
1 2 3 4 5 |
if x==3: print "We are inside an if statement" x = x + 1 print "we are no longer in an if statement" |
Note that unlike most languages, no parentheses are needed, although including parentheses does not violate python syntax. Anything indented after the if statement is included in the execution if the if statement evaluates to true. The scope is closed once indentation returns to the indent location of the original, matching if statement. Below is an example of an if, else if, else clause in python:
1 2 3 4 5 6 7 8 |
if x==3: print "we are inside the if statement" elif x==2: print "we are inside the else-if statement" else: print "we are inside the else statement" #end conditional block print "we are outside of the if-else block" |
Important notes about this functionality in python:
- Instead of a traditional "else if" statement, python uses the shorter keyword elif.
- Any elif or else keyword must be in line with a corresponding if statement. If either of these keywords are not matched in indentation to an existing if statement, python will throw an error and exit.
- Variables declared in an if statement can be used elsewhere in the code. In other words, there is no scope for variables declared in an if block. Convenient, but use wisely!




