5. Syntax

5.1. Indentation instead of braces

  • Python uses indentation instead of braces

  • 4 spaces indentation, no tabs

  • Python throws IndentationError exception on problem

  • Code indented on the same level belongs to block:

    if True:
        print('First line of the true statement')
        print('Second line of the true statement')
        print('Third line of the true statement')
    else:
        print('This is false')
    

5.2. End of lines

  • No semicolon (;) at the end of lines

  • \r\n and \n are good:

    print('Hello!\nHow are you?')
    print('Hello!\r\nHow are you?')
    

5.3. Comments

5.3.1. Line comments

  • Indent must be on the same level as block indent

  • Hash (#), space and then comment:

    # José Jiménez says hello
    print('My name... José Jiménez')
    

5.3.2. Inline comments

  • Source code, two spaces, hash (#), space and then comment:

    print('My name... José Jiménez')  # José Jiménez says hello
    

5.3.3. Multiline comments

  • Triple single quotes '''

  • Triple double quotes """ (more common)

  • Both ''' and """ quotes works the same

    """
    We choose to go to the Moon!
    We choose to go to the Moon in this decade and do the other things,
    not because they are easy, but because they are hard;
    because that goal will serve to organize and measure the best of our energies and skills,
    because that challenge is one that we are willing to accept, one we are unwilling to postpone,
    and one we intend to win, and the others, too.
    """
    

5.3.4. Docstring

  • Docstring is a first multiline comment in:

    • File / Module
    • Class
    • Method / Function
  • It is accessible in __doc__ property of an object

  • Used for generating help() documentation

    def apollo_dsky(noun, verb):
        """
        This is the Apollo Display Keyboard
        It takes noun and verb
        """
        print(f'Program selected. Noun: {noun}, verb: {verb}')
    
  • Used for doctest

    def add(a, b):
        """
        Sums two numbers.
    
        >>> add(1, 2)
        3
        """
        return a + b
    

5.3.5. Commented out code

  • Never!
  • Use Version Control System instead - e.g.: git blame
  • IDE has Local history (modifications) and you can compare file

5.4. Variables and constants

  • NameError when using not declared variable
  • AttributeError when cannot assign to variables
  • Names are case sensitive

5.4.1. Variable declaration

  • Lowercase letters for variable names

    name = 'José Jiménez'
    
  • Underscore _ is used for multi-word names

    first_name = 'José'
    last_name = 'Jiménez'
    

5.4.2. Constant declaration

  • Uppercase letters for constants names

    PATH = '/etc/passwd'
    
  • Underscore _ is used for multi-word names

    FILE_NAME = '/etc/shadow'
    

5.4.3. Variables vs. constants

  • Python do not distinguish between variables and constants

  • Python allows you to change “constants” but it’s a bad practice

  • Names are case sensitive

    name = 'José Jiménez'
    NAME = 'Иван Иванович'
    Name = 'Matt Kowalski'
    

5.4.4. Type inference

  • Static Typing (Java, C++, Swift)

    String name = new String("José Jiménez")
    
  • Dynamic Typing (Python, PHP, Ruby)

    # Type inference
    name = 'José Jiménez'
    name = str('José Jiménez')
    

5.4.5. Types

  • Since Python 3.5

  • SyntaxError in Python before 3.5

  • Two names: type hints and type annotations

  • Types are not required, and never will be (quote from Guido van Rossum, Python BDFL)

  • To check types you have to use IDE or modules like mypy or pyre-check

  • Types are used extensively in system libraries

  • More and more books and documentations use types

  • Declaring objects with types:

    name: str = 'José Jiménez'
    age: int = 30
    
  • Types do not enforce checking:

    # This code will run without any problems
    # Although ``mypy`` or ``pyre-check`` will throw error
    name: int = 'José Jiménez'
    age: float = 30
    

5.4.6. More advanced topics

Note

The topic will be continued in chapter: Software Engineering Conventions

5.5. print()

  • print() adds '\n' at the end

  • Prints on the screen

    print('My name... José Jiménez')
    # My name... José Jiménez
    
  • Variable substitution

    name = 'José Jiménez'
    
    print(f'My name... {name}')
    # My name... José Jiménez
    
  • Special characters

    name = 'José Jiménez'
    
    print(f'My name...\n\t{name}')
    # My name...
    #     José Jiménez
    

Note

More in Print Formatting

5.6. Assignments

5.6.1. Meet Python

  1. Create Python script
  2. Add interpreter declaration
  3. Under interpreter declaration add multiline comment with program description (copy-paste from book)
  4. Declare variable name and set its value to your name
  5. Add inline comment to variable declaration with text: “This is my name”
  6. Print variable
  7. Next line under print statement add line comment, with expected output
  8. Run script
About:
  • Filename: syntax_python.py
  • Lines of code to write: 2 lines + 2 lines of comment
  • Estimated time of completion: 5 min
The whys and wherefores:
 
  • Tworzenie skryptów Python
  • Deklaracja zmiennych
  • Komentowanie kodu
  • Wyświetlanie wartości zmiennych
Hint:
  • print()