Python Language Syntax

  • Python was originally developed as a teaching language

  • The cleanliness of Python's syntax has led some to call it "executable pseudocode"

Syntax refers to the structure of the language (i.e., what constitutes a correctly-formed program). For the time being, we'll not focus on the semantics - the meaning of the words and symbols within the syntax - but will return to this at a later point.

Example


In [1]:
# set the midpoint
midpoint = 5

# make two empty lists
lower = []; upper = []

# split the numbers into lower and upper
for i in range(10):
    if (i < midpoint):
        lower.append(i)
    else:
        upper.append(i)
        
print("lower:", lower)
print("upper:", upper)


lower: [0, 1, 2, 3, 4]
upper: [5, 6, 7, 8, 9]

This script is a bit silly, but it compactly illustrates several of the important aspects of Python syntax. Let's walk through it and discuss some of the syntactical features of Python

Comments Are Marked by #

The script starts with a comment (this means that python won't read this line....very useful!):

# set the midpoint

Comments in Python are indicated by #, and anything on the line following the numbers sign is ignored by the interpreter.

This means, for example, that you can have stand-alone comments like the one just shown, as well as inline comments that follow a statement. For example:

x += 2  # shorthand for x = x + 2

So above, Python reads the first bit of code, but ignores the 'comment'

End-of-Line Terminates a Statement

The next line in the script is

midpoint = 5

This is an assignment operation, where we've created a variable named midpoint and assigned it the value 5. Notice that the end of this statement is simply marked by the end of the line.

In Python, if you'd like a statement to continue to the next line, it is possible to use the "\" marker to indicate this:


In [2]:
x = 1 + 2 + 3 + 4 +\
    5 + 6 + 7 + 8

It is also possible to continue expressions on the next line within parentheses (or brackets), without using the "\" marker:


In [3]:
x = (1 + 2 + 3 + 4 +
     5 + 6 + 7 + 8)

The best way is to use the line continuation (within parentheses).

Semicolon Can Optionally Terminate a Statement

Sometimes it can be useful to put multiple statements on a single line.

The next portion of the script is

lower = []; upper = []

This shows the example of how the semicolon (;) familiar in C can be used optionally in Python to put two statements on a single line.

This is exactly the same as writing the below in python:

lower = []
upper = []

Using a semicolon to put multiple statements on a single line is generally discouraged by most Python style guides, though occasionally it proves convenient.

Indentation: Whitespace Matters!

  • we must use indentation (or more specific - 4 spaces!)

  • The top line will be the controlling statement.

  • indented code blocks are always preceded by a colon (:)

  • Anything indended below this top line will occur within it.

For example, the following two snippets will produce different results!


In [4]:
x = 5
if x < 4:
    y = x * 2
    print(x)

In [5]:
x = 5
if x < 4:
    y = x * 2
print(x)


5

Python's use of meaningful whitespace leads to much more consistent and readable code than languages that do not enforce indentation of code blocks.

Whitespace Within Lines Does Not Matter

While the mantra of meaningful whitespace holds true for whitespace before lines (which indicate a code block), white space within lines of Python code does not matter. For example, all three of these expressions are equivalent:


In [6]:
x=1+2
x = 1 + 2
x             =        1    +                2

Abusing this flexibility can lead to issues with code readibility – in fact, abusing white space is often one of the primary means of intentionally obfuscating code (which some people do for sport). Using whitespace effectively can lead to much more readable code, especially in cases where operators follow each other – compare the following two expressions for exponentiating by a negative number:

x=10**-2

to

x = 10 ** -2

I find the second version with spaces much more easily readable at a single glance. Most Python style guides recommend using a single space around binary operators, and no space around unary operators. We'll discuss Python's operators further in Basic Python Semantics: Operators.

Parentheses Are for Grouping or Calling

In the previous code snippet, we see two uses of parentheses. First, they can be used in the typical way to group statements or mathematical operations:


In [7]:
2 * (3 + 4)


Out[7]:
14

They can also be used to indicate that a function is being called.


In [8]:
# example
L = [4,2,3,1]
L.sort()
print(L)


[1, 2, 3, 4]

The "()" after sort indicates that the function should be executed, and is required even if no arguments are necessary.

Strings!

One of the most simple and important aspects of python you will be using constantly, will be strings!

Strings are designated by single or double quotation marks.

"This is my python string" 

'This is my second python string'

We will be using 'strings' throughout our whole python lifetime.

Things to remember: 1) Strings are not numbers. You'd have to convert them to a number.


In [9]:
x = "4" 
print("String: ", type(x),      x)

x = int(x)
print("Integer: ", type(x),    x)

x = float(x)
print("Float: ", type(x),    x)


String:  <class 'str'> 4
Integer:  <class 'int'> 4
Float:  <class 'float'> 4.0

Aside: A Note on the print() Function

Above we used the example of the print() function. The print() function is one piece that has changed between Python 2.x and Python 3.x. In Python 2, print behaved as a statement: that is, you could write

# Python 2 only!
>> print "first value:", 1
first value: 1

For various reasons, the language maintainers decided that in Python 3 print() should become a function, so we now write

# Python 3 only!
>>> print("first value:", 1)
first value: 1

This is one of the many backward-incompatible constructs between Python 2 and 3.

References

  • The most widely used style guide in Python is known as PEP8, and can be found at https://www.python.org/dev/peps/pep-0008/.

  • A Whirlwind Tour of Python by Jake VanderPlas (O’Reilly). Copyright 2016 O’Reilly Media, Inc., 978-1-491-96465-1