Expressions in Python

Expressions are the hardest aspects of parsing many languages, at least for beginners. The complexity begins with the different precedence of operators: multiply and divide come before add and subtract, for example. Next, there is the issue of parentheses: grouping things in parentheses overcomes precedence rules, becoming effectively the highest precedence of all.

An expression is a hierarchy of structures based on order of evaluation. At the lowest level, with highest precedence, are the fundamental components which will be called factors. A variable (identifier) is a factor. So is a numerical con­stant. Also, so is any expression within parentheses. The grammar could be writ­ten as follows:

<factor> ::= <identifier> | <number> |    “(” expression “)”

The next lower in precedence are the multiplicative operations * and /. We’ll call this component a term, and the syntax could be

<term> ::= <factor> { “*” | “/” <factor> }

According to this, the following are terms:

pi

12.6

pi*2/6*100

The first two are also factors, because a factor can be a term if not followed by an operator.

Now we have an expression, which consists of additive operators acting on terms.

<expression> ::=   [“+” | “-“] <term> { “+”  | “-” <term> }

According to this, the following are expressions:

12.5-(a – b – c)

-77.7

(a-b)*(a-b)

Basically, any numerical expression fits this grammar. Finally, we have con­ditions, which involve a relational (comparison) operator acting on expressions. The syntax is

<condition> ::= <expression> <relop> <expression>

<relop> ::= “<”     | “<=” | “<>” | “>” | “>=” | “==”

A condition would be found in a while or if statement. So

if x < 10                      “x < 10” is a condition

while x*x > 100          “x*x > 100” is a condition.

When generating C code for expressions, the program does the obvious things. The expression a*b in PyJ generates a*b in C, for example. The PyJ com­piler always inserts parentheses to assert precedence, though. Some illustrative examples are shown in Table 14.2.

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 *