Python Grammar - Rules and Expressions 1

Wordane | Python Grammar - Expressions and Rules

In order to get a valid Language with a certain logic, it is crucial to follow general rules. In English language we follow grammar, and similarly in any computer language. Computer languages cannot be ambiguous and verbose, hence they follow a strict grammar.
In this blog post, I discuss the Python grammar.

Generally in English, we follow the following rules AKA Backus Naur Form.

Rule 1: Subject -> Subject Verb Object

The Subject can be Noun, Object can be a Noun; hence

Rule 2: Subject -> Noun
Rule 3: Object -> Noun
Rule 4: Verb -> Like, Play, Dance ()
Further the Noun can be described as

Rule 5: Noun -> I, John Doe, Baseball

The purpose of Backus Naur Form is to precisely describe the language structure.
In general we follow

-> replacement (this can be sequence of Sentence, subject, Noun, Object, Verb or a )

is something that we are not finished with. i.e. Sentence, Subject, Object, Noun; but not Like, Play, Dance ()

In any language our goal is to start with Non-terminals and finish with terminals.

So, we start with
Sentence -> Subject Verb Object

Following the above rules 2 and 3
Sentence -> Noun Verb Noun
above is still a non-terminal, so we keep on going.

Sentence -> I Like Baseball
Above is a valid Expression in English

Following the same Grammar rules in English, the valid English expressions can be

I Play Baseball
John Doe Play Baseball
I Dance John Doe
Baseball Like John Doe

For Python, the grammar rule holds like so:

Rule 1: Expression -> Expression Operator Expression
Rule 2: Expression ->  Number
Rule 3: Operator -> +, * ...
Rule 4: Numbers -> 0,1 ...
Rule 5: Expression -> (Expression)

Starting with

Expression -> Expression Operator Expression
Expression -> Number Operator Number
Expression -> 1 + 1

Above is a valid Python Grammar

We can
Expression -> Expression Operator Expression

Now using the Rule 1:
Expression -> Expression Operator Expression Operator Expression

We can use Rule 1 and build complicated expressions. Continuing from above

Expression -> (Expression) Operator (Expression) Operator Expression

Expression -> (Number) Operator (Number) Operator Number

Expression -> (4) + (5) - 9
Above is a valid expression with all terminals, hence we cannot go further

Below are all valid expression
Expression -> 3
Expression ->  (1+ (2 * 3) - 5 + (4 * 20))
Expression -> (((((5)))))

Below are NOT valid expressions:
Expression -> - 55
For above Rule 1 is not followed}

Expression -> ((6)))
For above Rule 5 is not followed.

Expression -> )((6))
For above Rule 5 is not followed

Post a Comment