Available under Creative Commons-NonCommercial-ShareAlike 4.0 International License.
A second form of the if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this:
if x%2 == 0: print 'x is even' else: print 'x is odd'
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a message to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alternatives will be executed. The alternatives are called branches, because they are branches in the flow of execution.
- 瀏覽次數:1688