The Python Programming Language

 

Lexemes

  1. comment ::= "#" #(char end_of_line).
  2.         # This is a comment

  3. object ::= numeric | string | list | dictionary | tuple.
  4. numeric ::= integer | long | float | octal | hex | complex.
  5. integer ::= digit #(digit).
  6. long ::= integer ("l" | "L").
  7.         123L

            9999999999l

  8. exponential ::= integer O("." integer) ("e" | "E") O(sign) integer.
  9.         6e10

            9.9E-20

  10. float ::= integer "." integer | exponential.
  11.         123.0

            4E90

  12. sign ::= "+" | "-".
  13. octal ::= "0" N("0",7").
  14.         0176

  15. hex ::= ("0x" | "0X") N(hexadecimal).
  16.         0x4af

  17. complex ::= O((integer | float) sign) (integer | float) ("j" | "J").
  18.         1+2j

            3J

            5.5-1.1j

  19. string ::= (single_quote | double_quotes | triple_quotes) #(char) O(raw_string) (single_quote | double_quotes | triple_quotes).
  20. single_quote ::= "\".
  21. double_quotes ::= "\"".
  22. triple_quotes ::= "\"\"\"".
  23.         This is a string.

            "This is also a string."

            """This is a

            triple-quoted string."""

    Notice the last line: Pythons triple-quoted string constant form. Python collects all the lines in the quoted block and concatenates them in a single multiline string, putting an end-of-line character ("\012") between each line. Note that "\012" is an octal integer.

  24. raw_string ::= "\newline" | "\n" | "\\" | "\" | "\"" | "\a" | "\b" | "\e" | "\000" | "\v" | "\t" | "\r" | "\f" | "\0" octal_value | "\x" hex_value.
  25. list ::= "[" #(object) "]".
  26.         []                          #an empty list

            [1, 2, 3]

            [a, [b, c] ]     #nesting

    You can think of Python lists as arrays of pointers in C because lists only store references to other objects, not the copy of the objects. For example:

            L1 = [hi, hello, yo]

            L2 = L1

    In this case, if you make any changes to L1, it will also effect L2 because L2 is a reference of L1 (in another word, L2 is pointing to L1).

  27. dictionary ::= "{" #(object colon object "}".
  28.         {}                                                #an empty dictionary

            {a: 1, b: 2}

            {rose: {red: 1, black: 2} }     #nesting

    Note that Pyhon dictionary is implemented as hash tables. Like lists, dictionaries only store object references (not copies).

  29. tuple ::= "(" ) L(object) ")" | L(object).
  30. where L(x) ::= empty | x "," | x "," x #("," x).

            ()                            #an empty tuple

            (0,)                         #a one-item tuple (not an expression)

            (a, (b, c) )       #nesting

    Notice the second line here. If you really want a one-item tuple, you need to put a comma after the single item, before the closing parenthesis, to tell Python that it is not a simple expression.

    In some cases, Python allows us to omit the parentheses for a tuple where it is not syntactically ambiguous. For example:

            T1 = 1, 2, 3, 4        #an example of an assignment statement

    Although, the parentheses are optional, it is easier to use them every time than to figure out when they are optional.

    Note that tuples work exactly the same way as lists, however, they cannot grow or shrink like lists.

  31. operator ::= arithmetic | relational | boolean | string_op | bitwise_op.
  32. arithmetic ::= "+" | "-" | "*" | "/" | "**" | "%".
  33. ** computes an exponential number.

    % computes a division remainder.

            2**3 = 8     #same as 23

            5%2 = 1

  34. relational ::= "<" | ">" | "<=" | ">=" | "==" | "<>" | "!=".
  35. boolean ::= "and" | "or" | "not".
  36. string_op ::= "+" | "*" | "%".
  37. + is used to concatenate strings.

    * is used to repeat strings.

    % is used to format strings.

            'I am a ' + 'student'                                # 'I am a student'

            'Hello' * 3                                             #same as HelloHelloHello

            '%d %s %d you %' (99, 'beer', 4)        # 99 beer 4 you

  38. bitwise_op ::= "|" | "^" | "&" | "<<" | ">>" | "~".
  39. variable_name ::= (underscore | letter) #(underscore | letter | digit).
  40. Variable names must start with an underscore or letter, and be followed by any number of underscores, letters, or digits. Python variable names are case-sensitive (names z and Z are two different variables). For example:

    _flag                # a legal name

    flag                 # a legal name

    4_flag             # not a legal name

    flag$               # not a legal name

    @!#               # not a legal name

    Names that you define cannot be the same as reserved words.

  41. reserved_word ::= "and" | "assert" | "break" | "class" | "continue" | "def" | "del" | "elif" | "else" | "except" | "exec" | "finally" | "for" | "from" | "global" | "if" | "import" | "in" | "is" | "lambda" | "not" | "or" | "pass" | "print" | "raise" | "return" | "try" | "while".
  42.  

Statement

  1. statement ::= assignment_statement | expression_statement | print_statement | if_statement | loop_statement.
  2. assignment_statement ::= variable_name O("=" variable_name) "=" object.
  3. Assignment statement stores references to objects in variable names or data structure slots.

            hello = 'Hello World'                #Basic form

            today, tomorrow = 13, 14        #Tuple assignment

            lunch = dinner = 'junk food'     #Multiple-target

    In the second line, name today is assigned to integer 13, and name tomorrow is bound to integer 14. In the last line, names lunch and dinner are both assigned a reference to the string junk food.

  4. expression_statement ::= basic_expression | function_call | method_call | interactive_print | compound_expression | range_test.
  5. basic_expression ::= (variable_name | object) operator (variable_name | object).
  6.         1 + 1

            'Hello' + 'World'

            a == b

  7. function_call ::= function_name "(" L(variable_name | object) ")".
  8.         play()

            len(d3,d4)

  9. method_call ::= object "." method_name "(" L(variable_name | object) ")".
  10.         x.run()

            L.append(L)

  11. compound_expression ::= basic_expression N(operator basic_expression) | range_test.
  12.         tom < dan and dan == john

  13. range_test ::= (variable_name | object) "<" (variable_name | object) "<" (variable_name | object).
  14.         A < B < C         #tests whether B is between A and C

  15. print_statement ::= "print" O(space (variable_name | object | basic_expression) #(comma ("+" | "*") (variable_name | object | basic_expression) ) ).
  16.         >>> print "What sup world"

            "What sup world"

            >>> print "How", "are", "you?"

            "How are you"

            >>> print "a" + "b"

            ab

  17. if_statement ::= "if" test_condition colon end_of_line block #(elif_clause) O(else_clause).
  18. Here is a general form of an if statement:

            if <test1>:

                    <statements1>

            elif <test2>:         #any number of elif

                    <statements2>

            else:                    #optional else

                    <statements3>

    For example:

            >>> x = 0

            >>> if x == 1:

           ...          print true

           ... elif x == 0:

           ...          print false

           ... else:

           ...          print x

           ...

            false

  19. test_condition ::= relational_expression | boolean_expression.
  20. block ::= N(indent statement).
  21. indent ::= N(space | tab).
  22. elif_clause ::= "elif" test_condition colon end_of_line block.
  23. else_clause ::= "else" colon end_of_line block.
  24. relational_expression ::= (variable_name | object) relational (variable_name | object).
  25.         A > B

            C != D

  26. boolean_expression ::= (variable_name | object) boolean (variable_name | object).
  27.         A and B

            C or D

  28. loop_statement ::= while_statement | for_statement.
  29. while_statement ::= "while" test_condition colon end_of_line block O(else_clause).
  30. Here is a general form of a while statement:

            while <test>:

                    <statements1>

            else: #optional

                    <statements2>

    For example:

            >>> x = 0; y =10

            >>> while x < y:

           ...          print x,

           ...          x = x +1

           ...

            0 1 2 3 4 5 6 7 8 9

  31. for_statement ::= "for" variable_name "in" object colon end_of_line block O(else_clause).

Here is a general form of a for statement:

for <target> in <object>:

        <statements1>

else: #optional

        <statements2>

For example:

>>> total = 0

>>> for x in [1, 2, 3, 4, 5]:

...         total = total + x

...

>>> total

15