WHILE Statements in Python

Here is the syntax of a while statement in PyJ:

<while statement> ::= “while” <condition> <statement>+ “end”

The structure is that is starts with the while symbol whileSy, which is fol­lowed by a <condition>, followed by a number of statements until end is seen. A condition is a relational expression that results in true or false, such as a < b. So long as the result of that condition is true, the loop will continue to repeat. A basic parser would be

if sy == whileSy:                      # While statement

sy = nextSy()

condition()                       # The condition part

while sy != endSy:                # Statements until the END

statement()

sy = nextSy()

Note that the fact that a while statement is coming is indicated by the fact that the current symbol is whileSy. It is skipped, then a condition is parsed by the function condition(). Then, as long as the current symbol is not endSy, a statement is parsed using the statement() function. Using this particular parsing scheme, which is simple but not the only parsing scheme, each non-terminal sym­bol is parsed by a function of the same name. Thus, according to the grammar, a while statement will call functions condition and statement, because they are non-terminal symbols. “While” and “end” are terminal symbols, and are skipped over.

One job of a compiler (not a parser) is to create a translation for the text being parsed. The translation is created while the text is parsed by generating
code or some other text that allows the text that is being parsed to be executed or interpreted. In the case of PyJ, we will generate an equivalent C program. This makes it easy to test the compiler, as C can be converted by a C compiler into an executable file.

A PyJ while loop has correspondences to a C while loop:

while x < 10                     while (x < 10)

                               {

statement;                      statement;

statement;                      statement;

end                                                             }

The above parse with code translation to C included in it is as follows:

if sy == whileSy:                  # While statement

print (“while (“)

sy = nextSy()

condition()                        # The condition part

print (“)    {“)

while sy != endSy:                  # The condition part

statement()

print (“}”)

sy = nextSy()

In general, for a legal input we get the following output:

while ( <condition>

) {

<statements>

}

This should work if the condition and statements are legal.

Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.

Leave a Reply

Your email address will not be published. Required fields are marked *