1.5. Python Syntax

1.5.1. Variables

  • NameError when using not declared variable

  • AttributeError when cannot assign to variables

Identifiers (variable/constant names) are case sensitive Use lowercase letters for variable names:

>>> name = 'Mark Watney'

By convention you should use use Latin characters and English names (Non-ASCII characters in an identifier):

>>> name = 'Mark'
>>> imię = 'Mark'

Underscore _ is used for multi-word names

>>> first_name = 'Mark'
>>> last_name = 'Watney'

You can also join words.

>>> firstname = 'Mark'
>>> lastname = 'Watney'

Although it works for two words, it could be hard to read for three or more:

You should always use lowercase letters:

>>> name = 'Mark Watney'
>>> Name = 'Jan Twardowski'

Capital letters by convention has different meaning. The code will run without errors or warnings, but you can mislead others. Remember code is read by 80% of a time, and written in 20%.

Not ok by convention :

>>> firstName = 'Mark'  # Camel Case - not used in Python (/C/C++/Java/JS convention)
>>> Firstname = 'Mark'  # Pascal Case - reserved for class names
>>> FirstName = 'Mark'  # Pascal Case - reserved for class names

You can put numbers in variables:

>>> name1 = 'Mark'
>>> name2 = 'Mark'

BUt the number cannot be the first character (otherwise will produce SyntaxError):

>>> 1name = 'Mark'  # doctest: +SKIP

1.5.2. Constants

Identifiers (variable/constant names) are case sensitive. Uppercase letters are used for constants (by convention):

>>> FILE = '/etc/passwd'
>>> FILENAME = '/etc/group'

Underscore _ is used for multi-word names:

>>> FILE_NAME = '/etc/shadow'

Python do not distinguish between variables and constants. Python allows you to change "constants" but it's a bad practice (good IDE will tell you):

>>> NAME = 'Mark Watney'
>>> NAME = 'Jan Twardowski'

1.5.3. Variables vs. Constants

  • Variables vs. constants - Names are case sensitive

>>> name = 'Mark Watney'        # variable
>>> NAME = 'Jan Twardowski'     # constant
>>> Name = 'José Jiménez'       # class

Definition of second, minute or hour does not change based on location or country (those values should be constants). Definition of workday, workweek and workmonth differs based on location - each country can have different work times (those values should be variables).

>>> SECOND = 1
>>> MINUTE = 60 * SECOND
>>> HOUR = 60 * MINUTE
>>> workday = 8 * HOUR
>>> workweek = 5 * workday
>>> workmonth = 4 * workweek

For physical units it is ok to use proper cased names. It is better to be compliant with well known standard, than to enforce something which will mislead everyone.

>>> Pa = 1
>>> hPa = 100 * Pa
>>> kPa = 1000 * Pa
>>> MPa = 1000 * kPa

1.5.4. Printing Values

  • Prints on the screen

  • f-string formatting for variable substitution

  • More information in Builtin Printing

>>> print('My name... José Jiménez')
My name... José Jiménez
>>> name = 'José Jiménez'
>>> print(name)
José Jiménez
>>> name = 'José Jiménez'
>>> print('My name... {name}')
My name... {name}
>>> name = 'José Jiménez'
>>> print(f'My name... {name}')
My name... José Jiménez

1.5.5. End of Lines

  • No semicolon (;) at the end of lines

  • PEP 8 -- Style Guide for Python Code: Use \n for newline

>>> print('Hello!\nHow are you?')
Hello!
How are you?

1.5.6. Line Length

  • Most controversial rule

  • PEP 8 -- Style Guide for Python Code: 79 for line with code

  • PEP 8 -- Style Guide for Python Code: 72 for line with comment

  • black: 90-ish

  • django: 120 for code, 300 for models

1.5.7. Comments

  • PEP 8 -- Style Guide for Python Code: for line comments: Hash (#), space and then comment

  • PEP 8 -- Style Guide for Python Code: for inline comments: code, two spaces, hash (#), space and then comment

  • Commented out code: Never!

  • Use Version Control System instead - e.g.: git blame

  • IDE has Local history (modifications) and you can compare file

Line comments:

>>> # Mark thinks he is...
>>> print('Mark Watney: Space Pirate')
Mark Watney: Space Pirate

Inline comments:

>>> print('Mark Watney: Space Pirate')  # This is who Mark Watney is
Mark Watney: Space Pirate

1.5.8. Docstring and Doctests

  • Docstring is a first multiline comment in: File/Module, Class, Method/Function

  • Used for doctest

  • More information in Function Doctest

  • PEP 257 -- Docstring Conventions: For multiline str always use three double quote (""") characters

>>> # doctest: +SKIP
...
... """
... This is my first Python script
...
... >>> result
... 12
... """
>>>
>>> result = 10 + 2

1.5.9. Indentation

  • Python uses indentation instead of braces

  • Code indented on the same level belongs to block

  • PEP 8 -- Style Guide for Python Code: 4 spaces indentation, no tabs

  • Python throws IndentationError exception on problem

>>> if True:
...     print('True statement, first line')
... else:
...     print('Else statement, first line')
True statement, first line
>>> if True:
...     print('True statement, first line')
...     print('True statement, second line')
...     print('True statement, third line')
... else:
...     print('Else statement, first line')
...     print('Else statement, second line')
...     print('Else statement, third line')
True statement, first line
True statement, second line
True statement, third line
>>> if True:
...     print('Outer block, true statement, first line')
...     if True:
...         print('Inner block, true statement, first line')
...     else:
...         print('Inner block, else statement, fist line')
... else:
...     print('Outer block, else statement, first line')
Outer block, true statement, first line
Inner block, true statement, first line
>>> if True:
...     print('Outer block, true statement, first line')
...     print('Outer block, true statement, second line')
...     print('Outer block, true statement, third line')
...
...     if True:
...         print('Inner block, true statement, first line')
...         print('Inner block, true statement, second line')
...         print('Inner block, true statement, third line')
...     else:
...         print('Inner block, else statement, fist line')
...         print('Inner block, else statement, second line')
...         print('Inner block, else statement, third line')
...
... else:
...     print('Outer block, else statement, first line')
...     print('Outer block, else statement, second line')
...     print('Outer block, else statement, third line')
Outer block, true statement, first line
Outer block, true statement, second line
Outer block, true statement, third line
Inner block, true statement, first line
Inner block, true statement, second line
Inner block, true statement, third line

1.5.10. Good practices

The Zen of Python, by Tim Peters

  • Beautiful is better than ugly.

  • Explicit is better than implicit.

  • Simple is better than complex.

  • Complex is better than complicated.

  • Flat is better than nested.

  • Sparse is better than dense.

  • Readability counts.

  • Special cases aren't special enough to break the rules.

  • Although practicality beats purity.

  • Errors should never pass silently.

  • Unless explicitly silenced.

  • In the face of ambiguity, refuse the temptation to guess.

  • There should be one-- and preferably only one --obvious way to do it.

  • Although that way may not be obvious at first unless you're Dutch.

  • Now is better than never.

  • Although never is often better than right now.

  • If the implementation is hard to explain, it's a bad idea.

  • If the implementation is easy to explain, it may be a good idea.

  • Namespaces are one honking great idea -- let's do more of those!

1.5.11. Assignments

"""
* Assignment: About Syntax HelloWorld
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

English:
    1. Define `result` with text 'Hello World'

Polish:
    1. Zdefiniuj zmienną `result` z tekstem 'Hello World'

Hint:
    * Either quotes (") or apostrophes (') will work

Tests:
    >>> import sys
    >>> sys.tracebacklimit = 0

    >>> assert type(result) is str, \
    'Variable `result` has invalid type, should be str'

    >>> 'Hello' in result
    True
    >>> 'World' in result
    True
"""

# Given

result = ...  # str: with Hello and World

"""
* Assignment: About Syntax Newline
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

English:
    1. Define `result` with text 'Hello World'
    2. 'Hello' must be in a first line
    3. 'World' must be in a second line

Polish:
    1. Zdefiniuj zmienną `result` z tekstem 'Hello World'
    2. 'Hello' ma być w pierwszej linii
    3. 'World' ma być w drugiej linii

Hint:
    * Either quotes (") or apostrophes (') will work

Tests:
    >>> import sys
    >>> sys.tracebacklimit = 0

    >>> assert type(result) is str, \
    'Variable `result` has invalid type, should be str'

    >>> 'Hello' in result
    True
    >>> '\\n' in result
    True
    >>> 'World' in result
    True
"""

# Given

result = ...  # str: with Hello and World in separate lines

"""
* Assignment: About Syntax Interpolation
* Complexity: easy
* Lines of code: 2 lines
* Time: 2 min

English:
    1. Define variable `name` and set its value to 'Mark Watney'
    2. Define `result` with text 'Hello World {name}',
       where "Mark Watney" is the value of `name` variable

Polish:
    1. Zdefiniiuj zmienną `name` i ustaw jej wartość na 'Mark Watney'
    2. Zdefiniiuj `result` z tekstem 'Hello World {name}',
       gdzie "Mark Watney" jest wartością zmiennej `name`

Hint:
    * Either quotes (") or apostrophes (') will work
    * Use f-string

Tests:
    >>> import sys
    >>> sys.tracebacklimit = 0

    >>> assert type(name) is str, \
    'Variable `name` has invalid type, should be str'

    >>> assert type(result) is str, \
    'Variable `result` has invalid type, should be str'

    >>> 'Mark Watney' in result
    True

    >>> name
    'Mark Watney'

    >>> result
    'Hello World Mark Watney'
"""

name = ...  # str: with Mark Watney
result = ...  # str: with Hello World {name}

"""
* Assignment: About Syntax Comments
* Complexity: easy
* Lines of code: 4 lines
* Time: 3 min

English:
    1. Add first comment:
       a. line comment
       b. content: This is my first Python script
    2. Add second comment:
       a. multiline comment
       b. first line: This is first line of a multiline comment
       c. second line: This is second line of a multiline comment
    3. Add third comment:
       a. inline comment to `name` variable
       b. content: Space Pirate
    4. Run tests and check if solution is correct

Polish:
    1. Dodaj pierwszy komentarz:
       a. komentarz liniowy
       b. treść: This is my first Python script
    2. Dodaj drugi komentarz:
       a. komentarz wieloliniowy
       b. pierwsza linia: This is first line of a multiline comment
       c. druga linia: This is second line of a multiline comment
    3. Dodaj trzeci komentarz:
       a. komentarz na końcu linii
       b. treść: Space Pirate
    4. Uruchom testy i sprawdź czy rozwiązanie jest poprawne

Tests:
    >>> import sys
    >>> sys.tracebacklimit = 0

    >>> assert type(left_alone_on_mars) is str, \
    'Variable `left_alone_on_mars` has invalid type, should be str'

    >>> left_alone_on_mars
    'Mark Watney'
"""

left_alone_on_mars = 'Mark Watney'