1 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”

  • This is a third bullet point

Syntax refers to the structure of the language (i.e., what constitutes a correctly-formed program).

1.1 Example

Code
# 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]

At this point in time, this script might not make a lot of sense to you, but it compactly illustrates several of the important aspects of the Python syntax. Let’s walk through it and discuss some of the syntactical features of Python

1.2 Comments Are Marked by #

The script starts with a comment (this means that python won’t read this line….but this is very useful to provide information about your code):

# 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’

1.3 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:

Code
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:

Code
x = (1 + 2 + 3 + 4 +
     5 + 6 + 7 + 8)

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

1.4 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 (;) can be used optionally in Python to put two statements on a single line.

This is exactly the same as writing the below:

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.

1.5 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 indented below this top line will occur within it.

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

Code
x = 5
if x < 4:
    y = x * 2
    print(x)
Code
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.

1.6 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:

Code
x=1+2
x = 1 + 2
x             =        1    +                2

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

1.7 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:

Code
2 * (3 + 4)
14

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

Code
# 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.

1.8 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:

  • Strings are not numbers. You’d have to convert them to a number if you want to use them in math operations.

  • Floating numbers are needed due to memory limitations: we cannot have infinitely precise numbers! - They take the form of scientific notation. We can represent extremely large and small numbers in a very compact and efficient way.

Code
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

1.9 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.

1.10 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

1.11 License

Open MIT License, adapted from the Python Course 2020 developed by Cefas (Centre for Environment, Fisheries and Aquaculture Science) and Python Course for SENSE (Centre for Satellite Data in Environmental Science) PhD students 2020.