Python Course
Session 2
The sessions now broadly follow the standard tutorial https://docs.python.org/3/tutorial, but in a very condensed way. You are very much advised to refer to the tutorial for a fuller coverage of the language; and indeed, to the full language reference for complete coverage.
This session covers basic Python syntax and constructs.
Please feel free to seek assistance with understanding Python, particularly with the topics covered in the course 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 |
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.
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.
The textual language is defined at the lowest level in terms of the lexis/lexicon/lexical structure. The Python language consists of:
import while if def True False None | |
symbols (operators and delimiters) | = >= ( * >= += |
names (aka identifiers) | a b Fred radius b9 small_parts |
44 5.6 "abc" b"abc" | |
separators (space, tab, newline) |
|
# 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 (or syntactic structure) is the allowable combinations of lexical items. | for i in range(10): print(i) |
Semantics is the meaning of what is written. | Loop, printing numbers from 0 to 9. |
Best described with examples ...
29 | |
| 1234567890123456789012345678901234567890 (any length you want!) |
| 0x49ae A hexadecimal number |
3.14159 | |
| .923 |
| 2.3e-10 (i.e. 0.00000000023) |
“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” |
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 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. E.g. see data types in the standard library.
Types are important – they tell you what you can do with the data, how you can operate on it to transform it or derive new data. E.g. you can add and multiply integers and floats. And 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 frequently used list types with their own distinct Python syntax: list, tuple and dictionary. They are distinguished by use of distinct bracketing conventions – square brackets, round brackets 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 for constant lists – lists you don't (and can't) change (immutable). And dictionary is for lists of named things.
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 braackets to lookup a dictionary: | {“name”:”fred”, “age”:19}[“age”] | 19 |
It can be confusing that square brackets are used to define a list, and to index!
There are three general syntactic ways to operate on data in Python:
•Using an operator e.g. 4 + 2
•Using a built-in function, e.g. abs(x)
•Using a method defined for the type, e.g.: “abc”.upper()
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 if you should be using a built-in function or a method. E.g. 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.
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.
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 usefully 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.