Some notes about Python
Comments
# is used to add single line comments to the code; to have
multi-lines comments enclose the text in """.
Indentation
Identation (with spaces or tabs) is used to define blocks of code.
Variables
myvar = <value>
A variable is defined with the = operator (thus, every variable has a
value).
Numbers
int: integer type (5)float: floating point type (5.0)complex: complex number (5 + 3j)
Operations
+, -, *, /, %, **
/ always returns a float; the // operator performs a floor
division.
Strings
str: string type
Strings are immutable.
Literals can be enclosed in " or ' characters, or in """
if the literal spans multiple lines.
Strings can be indexed. Index starts from 0; negative index are
valid and count from the end of the string. Slicing ([<s>:<f>])is supported.
Operations
+, *
Collections
Lists
mylist = [1, 2, 3, 4]
Lists can contain items of different types (other lists as well). Can be indexed and sliced.
mylist[1] = 0
Items can be assigned (lists are mutable) and added to the list (with
the .append() method).
Operations
+ (concatenate two lists).
Note that the assignment operator (=) produces a shallow copy of a
list: the new variable contains a reference to the orginal list.
The .append() method adds an element to the end of the list; the
.pop() method removes the last element from the list (or the element
which position is passed as argument).
The del statement removes an item from a list, given its index.
List comprehension
squares = [x**2 for x in range(10)]
List comprehension is a concise way to create a list. Beside the basic
syntax, it supports one or more if clauses. The initial expression
can be any valid expression, even another list comprehension.
Tuples
t3 = 1, 2, 'three' t1 = 1, # Only one element t0 = () # Empty tuple
Tuples are immutable collections of heterogenous elements. Can be indexed and unpacked.
Sets
items = set('one', 'two', 'three')
empty = set()
Sets are unordered collections of unique elements (duplicates are removed). Sets support union, intersection, difference and symmetric difference operations.
Set comprehension is available.
Dictionaries
people = {'Wolf': 45, 'Gunnar': 23, 'Agamennonis': 60}
Dictionaries collect key, value pairs. Each item can be accessed by its key (a key can be any immutable type, and must by unique).
Dictionaries support the del statement.
The method keys() returns the keys, the method values() returns
the values and the method items() returns both.
Dictionary comprehension
c = [x: x**2 for x in range(10)]
Conditionals
if … else
if <condition>:
...
elif <condition>:
...
else:
...
The if ... else construct allows to evaluate a condition and, if it
evaluates to True, execute the corresponding block of code;
otherwise, the else block of code is executed.
Note: There can be zero or more elif statements, and the else one
is optional.
match
match <expression>:
case <pattern1.a | pattern2.b>:
...
case <pattern2>:
...
case _:
...
The match statement compares an expression against a set of
patterns; if a pattern matches, the code associated to the matching
case is executed. _ is used as a wildcard pattern (it always
matches).
Patterns can mix literals and variables, which will be binded and later used in the block of code.
case <pattern> if <condition>
Patterns supports an optional if clause (which condition must evaluate
to True for the pattern to match).
Note: patterns can be seen as something similar to what is put on the left hand side of an assignement.
Loops
While
while <condition>:
...
While loops do something until the condition evaluates to True.
For
for <var> in <sequence>:
...
The for loop iterates over the items of any sequence. The range()
function comes in handy to generate a sequence of numbers.
Break and Continue
The break statement interrupts the current (enclosing) loop. The
continue statement skips to the next iteration.
Else clause
The else clause can be also associated with for and while
loops. It is executed after the last iteration of the loop in the loop
is not preamturely interrupted.
Functions
def myfunction(<parameters>):
...
All variables assigned in the body of a function are local to that
function (unless the global statement is used to reference a global
variable, or a nonlocal statement to reference a variable in the
nearest enclosing function).
Functions with no return statement actually return None.
Function can be assigned to variables: myvar = myfunction.
Default arguments
It is possible to assign a default values to a parameter; if the call to the function omits to specify those arguments, the default values are used. Parameters with default values must follow the list of required paramenters.
Keyword arguments
Functions can be called using keyword arguments, in the form of
keyword = value. Keyword arguments must follow positional arguments.
Catch-all parameters
*<name> and/or **<name> are special catch-all parameters. In the
*<name> form, <name> will receive a tuple containg all the
positional arguments beyong the formal parameters list. Likewise, in
the **<name> form <name> will receive a dictionary with all the
keyword parameters beyond the list of formal parameters. If both
*<name> and **<name> are present, that must be the order in which
the would appear.
Unpacking argument lists
The * operator unpacks the elements from a list or a tuple. The **
does the same but on dictionaries.
Anonymous functions
lambda x, y: x + y
The lamba keyword creates an anonymous function, which is limited to a single expression.
Modules
import mymodule mymodule.myfunction()
Every .py file is a module, and can be imported with the import
keyword. The import statement does not import the name of the functions
defined in the module directly in the current namespace, so they must
be invoked using the module name as a prefix. Same goes for the module
variables.
import mymodule as mod
This version of the import statememnt allows to use an alias in place of the orginal module name.
from mymodule import myfunction1, myfunction2
This version of the import statement allow to map directly the function names into the current namespace.
if __name__ == "__main__":
...
If a module is invoked directly, the __name__ variable is set to
__main__; everything put after that line get exectuted.
Input and Output
Output formatting
f'Hello, my name is {name}'
Formatted strings allow to insert Python expressions inside
{}. Optional fomatting specifier can follow the expression (es:
:.3f).
'Total amount of noise is {:2.2%}'.format(noise)
str.format() allows detailed formatting directives inside the {}
placeholders.
Reading and Writing Files
f = open('myfile', 'r')
...
f.close()
The open() method returns a file object. The arguments represent the
file name and the mode the file is to be opened for; an optional
encoding=... argument can be passed to the the function. The modes
available for opening the file are: r, w, a (append), r+ (read
and write). Appending a b to the mode force the file to be opened in
binary mode (the default would be text mode).
with open('myfile', 'r') as f:
...
The with keyword is a convenient shortcut way to deal with file
objects.
File content can be read as bytes (.read()), lines (.readline())
or as a whole (.readlines()).
Content can be written to a file with the .write() method, which
accepts a string or a byte object.
The methods .tell() and .seek() can be used to report the current
position in the file, and to move to a specific position respectively.
Errors and Exceptions
try:
...
except [<exception>]:
...
Exceptions are run time errors and can be handled. The except clause
is considered only if the specified exception type occours (or if any
exception occours if no type is listed) while executing the try
block. More than one type of exception can be specified with a
tuple.
The try...except statment allows for the optional else clause,
which gets executed if the code in the try block does not generate
any exception.
The (optional) finally clauses allow to perform actions at the end of
the try block; these actions are executed regardless the code in the
try block generates an exception or not.
The raise statement allows for a specific exception to be raised.
Classes
class MyClass:
...
x = MyClass()
The class keyword defines a new class; the assingment creates an
empty class object.
def __init__(self):
...
The __init__ method is called whenever a new class object is
created. The self refers to the current class object and allows
arguments to further customize it.
Any assignment performed in the __init__ method creates an instance
attribute, which can be later referred with the . operator: y =
x.myval. Same goes for methods, if the class defines any: they can be
invoked (x.m()) or stored for later use (y = x.m).
Class and Instance Variables
class MyObject:
# A class variable
prop = 'custom'
def __init__(self, label):
# An instance variable
self.label = label
Class variables are defined at class level, and are shared between all
instances of the class. Instance variables are defined inside class
methods (usually inside the __init__() method), and are local to a
specific instance.
Inheritance
class MyClass(BaseClass):
...
Classes support inheritance; all attributes and methods of the base
class are available (just call BaseClass.method() or
super().method()). The derived class can override base class
methods.
Multiple inheritance is also supported.
Visibility
All class attributes and methods are public. If something needs to be
treated as private, it's name should be prefixed with _.
Standard Libray
Here are some modules provided by the Python Standard Library suited for different tasks.
Operating System Interface
- os: for operating system interaction
- shutils: for daily files and directories management
File Wildcards
- glob: make lists of files using wildcards
Program Interaction
- sys: store command line arguments, handle input/output/error channels and manage program exit status
- argparse: process command line arguments
Pattern Matching
- re: regular expression tools
Mathematics
- math: floating-point math functions
- random: random selections
- statistics: basic statistical functions
Internet
- urllib.request: retrieve data from an URL
- smtplib: send emails
Dates and Time
- datetime: manipulate dates and times
Data Compression
- zlib: handle compressed data archives
Performance Measurement
- timeit: tools to evaluate performance of blocks of code
Testing Code
- doctest: validate tests embedded in docstrings
- unittest: tools for test driven developmentk
Output Formatting
- pprint: print objects in a readable way
- textwrap: format paragraphs of text
Binary Data Records
- struct: work with variable lenght binary records
Multi-threading
- threading: tools for multi-threaded applications
Logging
- logging: logging system
Lists
- array: lists with only homogeneous data
- collection: alternative container datatypes
Floating-point Arithmetic
- decimal: decimal floating-point arithmetic