[Tutor] Python "well-formed formulas"

Dave Angel davea at davea.name
Tue May 28 19:25:21 CEST 2013


On 05/28/2013 09:45 AM, Citizen Kant wrote:
>
>
>    <SNIP>
>
> I'm trying to figure out the rules on how to recognize when a combination
> of symbols is considered a well formed expression in Python. Since I
> couldn't find any doc that lists all Python syntax rules --or maybe the doc
> is too long to be managed by me right now--, stating all kinds of legal
> combination among its symbols, I had this idea that well formed expressions
> must respond to truth tables. I think I'm not pretty much interested on how
> each symbol like 9 or Z or + come to be truth (maybe I'm wrong) but in the
> truth of their combinations. Do I am in the correct path? Understanding the
> truth tables (which I'm not very familiarized with) would help me on
> writing Python in a more intuitive way?
>

Read the first 3 pages of the link Walter sent you:
 
http://homepage.divms.uiowa.edu/~sriram/16/spring12/lectureNotes/Feb8-2012.pdf

Then tell us what didn't you understand.  It's quite informal, and maybe 
not quite complete.  But it covers most of the grammar informally.

When an expression is not well-formed, you'll get a syntax error, which 
happens at compile time.

Later parts of the pdf are describing evaluation, which doesn't happen 
till the code runs.  These are two distinct phases, even if much of your 
code may be running immediately after compiling.  It's at evaluation 
time that you MAY be interested in truth tables.  And then only if parts 
of the expression are boolean.  There's no truth-table involvement in 
deciding the result of 12+3*4, but there is operator precedence, covered 
in the above pdf file.

The full grammar, in BNF, can be found at:

   http://docs.python.org/2/reference/grammar.html

Notice there's lots more to the language than expressions.  And that 
reading BNF is difficult without training.  It's a language, also, one 
that's used for describing the syntax of computer languages.  And some 
language constructs end up with a very confusing BNF.

I'm still bothered that all your symbol examples are single-character. 
But a symbol is 1 OR MORE characters, with certain restrictions on what 
they can be.  And the first phase of compilation is to tokenize the 
source code.  For a simple language, that might be splitting the text by 
white space.  In Python, there are other rules applied for tokenizing. 
For example, in an expression, a * symbol that doesn't have another one 
immediately next to it is a multiply operator.  But if there are two, 
it's the exponentiation operator.

-- 
DaveA


More information about the Tutor mailing list