# 11.1.1 Python Programs

Python provides control statements for making decisions, looping, and for returning from a procedure.

If statement. Python's if statement is similar to the conditional expression in Scheme:

Unlike in Scheme, there is no need to have an alternate clause since the Python if statement does not need to produce a value. %Hence, the else is optional. The evaluation rule is similar to Scheme's conditional expression:

Python Evaluation Rule: If. First, evaluate the Expression$_{Predicate}$. If it evaluates to a true value, the consequent Block is evaluated, and none of the rest of the IfStatement is evaluated. Otherwise, each of the elif predicates is evaluated in order. If one evaluates to a true value, its Block is evaluated and none of the rest of the IfStatement is evaluated. If none of the elif predicates evaluates to a true value, the else Block is evaluated if there is one.

The main if statement in tokenize is:

if c.isspace(): ...
elif c in '()': ...
else: current = current + c

The first if predicate tests if the current character is a space. If so, the end of the current token has been reached. The consequent Block is itself an IfStatement:

if len(current) > 0:
tokens.append(current)
current = ' '

If the current token has at least one character, it is appended to the list of tokens in the input string and the current token is reset to the empty string. This IfStatement has no elif or else clauses, so if the predicate is false, there is nothing to do.

For statement. A for statement provides a way of iterating through a set of values, carrying out a body block for each value.

Its evaluation rule is: Python Evaluation Rule: For. First evaluate the Expression which must produce a value that is a collection. Then, for each value in the collection assign the Target to that value and evaluate the Block.

Other than the first two initializations, and the final two statements, the bulk of the tokenize procedure is contained in a for statement. The for statement in tokenize header is for c in s: .... The string s is the input string, a collection of characters. So, the loop will repeat once for each character in s, and the value of c is each character in the input string (represented as a singleton string), in turn.

Return statement. In Scheme, the body of a procedure is an expression and the value of that expression is the result of evaluating an application of the procedure. In Python, the body of a procedure is a block of one or more statements. Statements have no value, so there is no obvious way to decide what the result of a procedure application should be. Python's solution is to use a return statement.

The grammar for the return statement is:

A return statement finishes execution of a procedure, returning the value of the Expression to the caller as the result. The last statement of the tokenize procedure is: return tokens. It returns the value of the tokens list to the caller.