Python Tutorial Part Five: Syntax and Constructs

By Simon Bluck

Table of Contents

Prelude

The sessions now broadly follow the standard python.org tutorial, but in a condensed way. You are strongly advised to refer to the tutorial and to the full language reference for complete coverage.

This session covers basic Python syntax and constructs. Please feel free to seek assistance from myself and others with understanding Python, particularly with the topics covered in these sessions.

Note

In the notes for this session, where the description splits into two columns, the right column shows examples. E.g.:

Expression a + b * (c + d)

Where the description splits into three columns, the middle column shows examples and the right column shows results of evaluation of the examples. E.g.:

Expression evaluation 2 + 3 / (4 + 6) 2.3
  2 ** 9 512

Learning Python

What do you need to know about Python?

A limited amount if you just want to be able to code programs for yourself, and you aren’t interested in the fancier features and more abstract aspects of the language. And just pick up knowledge e.g. about some useful library as and when you need to.

Lots, if you are studying other people’s programs (especially the more clever ones), perhaps with a view to tailoring them for your own use.

As much as possible if you go on to write a variety of largish programs; or if you are making what you write public and you want credibility.

How do you learn Python?

Read about it, then from memory try it out.

A lot of it is “easy to guess”, i.e. Python generally uses a common-sense way to do something, but that may not be obvious to us until Python shows us how to express it that way.

Python also follows some implicit “rules”: keep it succinct, simple and consistent across the various language constructs.

When you write code, it’s also good to be consistent with the “standard” Python style, even if you might yourself prefer some other style.

Language composition

The textual language is defined at the lowest level in terms of the lexis/lexicon/lexical structure. The Python language consists of:

keywords import   while   if   def   True   False   None
symbols (operators and delimiters) =   >=   (   *   <=   +=
names (aka identifiers) a   b   Fred   radius   b9   small_parts
literals (numbers, strings, bytes) 44   5.6   "abc"   b"abc"
separators (space, tab, newline)  
comments # Calc area

The set of keywords, symbols and separators is predefined and can’t be added to, though may differ slightly between major Python releases. Whereas you get to choose your names, literals and comments.

Symbols are just like keywords, but use non-alphabetic characters in their composition.

An identifier is a name used to identify a variable, function, class, module or other object.

An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

You should choose meaningful names for identifiers you introduce.

Syntax (syntactic structure) — is the allowable combinations of lexical items e.g.

for i in range(10): print(i)

_Semantics — is the meaning of what is written
_ e.g. loop, printing numbers from 0 to 9

Literals

These are best described with examples:

Integer literals: 29
  1234567890127896543 (any length you want!)
  0x49ae (A hexadecimal number)
Floating point literals: 3.14159
  .923
  2.3e-10 (i.e. 0.00000000023)
String literals: "abc"
  'xyz'
  """pqr"""
  "Line 1\nLine 2\nLine 3"
  "What's this?"
  'What\'s this?'
  """Three lines
"with a quote"
ok."""
  "Just one str"   # Continued below
"ing"

Objects, values and types

Python data is represented by objects.

Every object has an identity (its address in memory), a type and a value.

An object’s type determines the allowed object values and operations.

If an object is mutable, its value can be changed — e.g a list. But you can’t change the value of an immutable object — e.g. a number or string.

An object can have no value and that is represented by the constant: None

Types

Types are a fundamental aspect of the Python data model. Any distinct piece of data (i.e. an object) has a type.

integer (no limit on precision!) 42
floating point number 5.9
string "xyz"
list [1, 2, "abcdef"]

Python has numerous built-in types, i.e. types considered to be a core part of the language. You can also define new types. (See data types in the standard library).

Types are important, they tell you what you can do with the data and how you can operate on it to transform it or derive new data. For example, you can add and multiply integers and floats. You can add two strings — it achieves concatenation of the strings — but you can’t multiply two strings, although you can multiply a string by an integer.

There are three frequental list types, each with their own distinct Python syntax: list, tuple and dictionary. They are distinguished by use of distinct bracketing conventions: square, round, and curly brackets. For now, just remember that the general list type has square brackets. The list type is very flexible. The tuple is very similar, but it’s used for lists you don’t (and can’t) change (immutable). And dictionary is for lists of named things.

Sequence Types

There are a number of sequence types: string, list, tuple, and range object. Note that dictionary is not a sequence type. Sequence types can be indexed and sliced.

Use square brackets to index a sequence: [1, 2, ”abcdef”][1] 2
Use square brackets to slice a sequence: "abcdef"[2:5] "cde"
Use square brackets to look up a dictionary: {"name":"fred","age":19}["age"] 19

It can be confusing that square brackets are used to define a list, and to index!

Operating on data

There are three general syntactic ways to operate on data in Python:

An operator provides a quick and simple way to operate on data and is especially useful for mathematical expressions.

It can be a little confusing to know when you should be using a built-in function or a method. For example, there is no len method so you can’t do somestring.len(), but you can do len(somestring). However, there aren’t a huge number of commonly-used built-ins so it’s just a matter of noting the common ones such as len.

Assignment and Expressions

Assigning a value to a variable. x = 6 # Store 6 in variable x
(Or, more accurately: store 6 in a memory location identified by the name x.)
Adding to a variable x += 6 # Add 6 to x.
_(And similar operators such as *=_)
A variable has to be given a value before it can be used. x = y # Store value of variable y in x
(error reported if y has not been given a value.)
An expression is allowed on the RHS. x = a + b * b + c
_# b is multiplied by itself, added to a and c, then stored in x._
Python provides shortcuts for multiple assignment. x = y = a + b
 # Add a and b then store in x and y.
 x, y = a + 1, a – 1 
 # Store a+1 in x, and store a-1 in y.
The RHS can be a string. x = "Fred"
The RHS can be a list of things. x = [1, 5, "Freda"]

In fact, assignment is actually more subtle than as described above. Python treats the RHS as a value, or object. And the LHS as a name that identifies the RHS result.

Loops, conditions and iterators

A while loop

i = 0
while i < 3:
    print(i)
    i += 1
# Print 0, 1, then 2

The i < 3 is a condition. While that condition is true, the while statement will loop, executing its contained statements.

Some for loops

for i in [0, 1, 2]:
    # Take successive values from the list
    # [0, 1, 2] with each iteration.
    print(i)

(Achieves the same as the while example, but is clearer.)

for i in range(3):
    print(i)

(More useful in the general case)

for i in range(0, 3):
    print(i)

(Even more general)

Some if statements

# Print value of i if it is non-zero.
if i != 0:
    print(i)
if i == 0:
    print("i is 0")
elif i == 1:
    print("i is 1")
else:
    print("i is greater than", 2)

A while loop with a conditional break

# Print 0, 1, then 2
i = 0
while 1 == 1:
    if i >= 3:
        break
    print(i)
    i += 1

While, for and if are compound statements.

The range function generates an iterator that with each iteration of the loop delivers the value 0, then 1, then 2, then stops the loop.


Next -> Part Six: Functions and More

Raspberry Pi, Arduino and other embedded systems to learn and create