The if and else decision statements give programmers a very powerful way to place conditions on the execution of one code block or another. Simply stated, when the expression after the if keyword evaluates to True, then the code block immediately following it will be executed; otherwise, the code block following the else keyword (when present) will be executed.

if Boolean_expression: # True => execute the following code block
    statement1
    statement2
else: # the expression is False => execute the following code block
    statement3
    statement4

Notice that each clause is defined by a code block, which is indicated by equal numbers of spaces of indentation. As previously mentioned, Python does not use explicit symbols like curly brackets or additional keywords to mark the beginning or end of each block.

Python also has elif (else if) statements. These will check multiple intervening expressions for their truth value and execute a block of code as soon as one of the conditions evaluates to True. Let’s look at an example of how these interrelated statements can be used:

The pass statement

Sometimes in the process of developing code, we want to define a code block that we intend to fill later, though for now we have to leave it empty. But leaving it in such a state would cause a syntax error. For cases like this, the pass statement can be very helpful, as it doesn’t do anything more than act as a placeholder in situations where a statement is syntatically required. For example:

will return a syntax error, but:

will not.

Mini-exercise: if/else
  • Prompt the user to enter a number; read it from the keyboard
  • If the input evaluates to an integer (type int), write "The number that you entered was: " and the number
  • Else, show the message "That is not an integer"
 
©  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Inclusivity Statement