The Python Language: Hendrik Speleers
The Python Language: Hendrik Speleers
Hendrik Speleers
The Python Language
●
Overview
– IPython/Jupyter
– Data types
●
Numerics, tuples, lists and strings
– Control flow
●
Selection: if, if-elif-else
●
Repetition: while, for
– Reusing code
●
Functions
●
Scripts and modules
Lab Calc
2019-2020
The Python Language
●
IPython/Jupyter: tips and tricks
– Getting help by using ? after an object
– Tab completion to view object’s attributes (object.<TAB>)
– Magic functions, prefixed with % sign
● %run : execute python script
● %whos : overview variables
● %cd : change the current working directory
● %timeit : time the execution of short snippits
● %quickref : show a cheat-sheet
● %automagic : omit the % sign (default on)
Lab Calc
2019-2020
The Python Language
●
Special characters for instructions
– Use # to indicate comments
– Use ;
●
to suppress the printing of output
●
to separate multiple statements on the same line (discouraged)
In [1]: 1 + 1 # output
Out[1]: 2
In [2]: 1 + 1; # no output
In [3]: print(1 + 1); # output
2
Lab Calc
2019-2020
The Python Language
●
Data types: python example
– No need to declare the type of variables
In [1]: a = 3 # integer
In [2]: type(a)
Out[2]: int
In [3]: 2 * a
Out[3]: 6
In [4]: a = 'hello' # string
In [5]: type(a)
Out[5]: str
In [6]: 2 * a
Out[6]: 'hellohello'
Lab Calc
2019-2020
The Python Language
●
Data types: numerics
– Integer Float
– Complex Boolean
●
Data types: numerics
– Basic arithmetic operations
● Addition (+), subtraction (-), multiplication (*), division (/)
● Power (**), integer division (//), modulo (%)
● Self-operators (+=, -=, ...)
In [1]: 3 / 2 In [1]: 3 / 2
Out[1]: 1 Out[1]: 1.5
In [2]: 3 / 2.0
2 In [2]: 3 // 2.0
3
Out[2]: 1.5 Out[2]: 1.0
Lab Calc
2019-2020
The Python Language
●
Data types: numerics
– Type casting: conversion of one type into another
●
Explicit via type cast operator
●
Implicit via promotion to larger type in operations
In [1]: float(1)
Out[1]: 1.0
In [2]: 1 + 2.5
Out[2]: 3.5
In [3]: 1 + int(2.5)
Out[3]: 3
Lab Calc
2019-2020
The Python Language
●
Data types: tuples
– A tuple is an ordered, immutable collection of objects
●
Objects may have different types
In [1]: tup1 = 1, 2, 3
In [2]: tup2 = ('a', 'b', 'c')
In [3]: tup3 = (1, 2, 'z')
In [4]: type(tup3), len(tup3)
Out[4]: (tuple, 3)
In [5]: x, y = 10, 20 # tuple unpacking
Lab Calc
2019-2020
The Python Language
●
Data types: lists
– A list is an ordered collection of objects (may have different types)
– Indexing: zero-based
0-based: C++, Java
In [2]: colors[0], colors[1] 1-based: Fortran, Matlab
Out[2]: ('red', 'green')
In [3]: colors[-1]
Out[3]: 'blue'
Lab Calc
2019-2020
The Python Language
●
Data types: lists
– Slicing syntax: list[start:stop:step]
Lab Calc
2019-2020
The Python Language
●
Data types: lists
– Modification of objects
– Reverse order
●
Data types: lists
– Sort list
●
Data types: lists
– Assignment: pass by reference
In [1]: a = [1, 2, 3]
In [2]: b = a; b[1] = 'hi'
In [3]: a
Out[3]: [1, 'hi', 3]
to ensure a
copy of a list:
– Indexing/slicing: pass by value b = list(a)
b = a.copy()
In [4]: b[:] = ['a', 'b', 'c']
In [5]: a
Out[5]: ['a', 'b', 'c']
Lab Calc
2019-2020
The Python Language
●
Data types: lists
– Concatenation (+) and repetition (*)
●
Data types: strings
– Different syntax of quoting
●
Data types: strings
– Strings are similar to tuples (immutable lists)
●
Data types: strings
– Formatting
In [1]: value = 99
In [2]: 'filename' + str(value) + '.ext'
Out[2]: 'filename99.ext'
In [3]: 'filename%d.ext' % value
Out[3]: 'filename99.ext'
– Formatting placeholders
● %s, %d, %f : string, integer, float
● %.<number of digits>f
●
Use tuple for multiple formats Lab Calc
2019-2020
The Python Language
●
Data types: other container types
– Dictionary: maps keys to values, unordered
Lab Calc
2019-2020
The Python Language
a b a and b a or b not a
●
Control flow False False False False True
– Logical operators : and, or, not False True False True True
True False False True False
True True True True False
– Conditional expressions
● a == b : tests equality, with logics (similar for !=, <, >, >=, <= )
● a is b : tests identity, both sides are same object
● a in b : for any collection b: b contains a
Lab Calc
2019-2020
The Python Language
●
Control flow: selection
Statement
Statement Statement
Statement
YES
Statement
Statement Condition
Condition Statement
Statement
NO
Statement
Statement Statement
Statement
Lab Calc
2019-2020
The Python Language
●
Control flow: selection
Statement
Statement
NO YES
Statement
Statement Condition
Condition Statement
Statement
Statement
Statement
Lab Calc
2019-2020
The Python Language
●
Control flow: selection
– If statement
●
Control flow: selection
– If-elif-else statement
In [1]: a = 10
In [2]: if a == 0:
...: print('zero')
...: elif a == 1:
...: print('one')
...: elif a == 2:
...: print('two')
...: else:
...: print('a lot')
a lot
Lab Calc
2019-2020
The Python Language
●
Control flow: selection
– If-else expression
In [1]: a, b = 10, 20
In [2]: print(a if a > b else b)
20
In [3]: if a > b: print(a)
...: else: print(b)
20
Lab Calc
2019-2020
The Python Language
●
Control flow: repetition
Statement
Statement Statement
Statement
REPEAT
n times
Statement
Statement Statement
Statement
Statement
Statement Statement
Statement
Lab Calc
2019-2020
The Python Language
●
Control flow: repetition
– While loop
Lab Calc
2019-2020
The Python Language
●
Control flow: repetition
– While loop
Lab Calc
2019-2020
The Python Language
●
Control flow: repetition
– While loop
Lab Calc
2019-2020
The Python Language
●
Control flow: repetition
– While/for-else loop
Lab Calc
2019-2020
The Python Language
●
Control flow: repetition
– Numeric range: range(start, stop, step)
Lab Calc
2019-2020
The Python Language
●
Control flow: repetition
– Enumeration number: enumerate(collection, start)
Lab Calc
2019-2020
The Python Language
●
Control flow: repetition
– List comprehension
Lab Calc
2019-2020
The Python Language
●
Reusing code: functions
– Defining functions
def funname(arguments):
block
return expr
●
Reusing code: functions
– Defining functions
●
Reusing code: functions
– Advanced example of arguments (keywords)
Lab Calc
2019-2020
The Python Language
●
Reusing code: functions
– Varying number of arguments (* packed into tuple and ** into dictionary)
Lab Calc
2019-2020
The Python Language
●
Reusing code: functions
– Passing of variables: use reference whenever possible
●
immutable (numerics, strings, tuples) vs. mutable (lists)
Lab Calc
2019-2020
The Python Language
●
Reusing code: functions
– Local vs. global variables: scope and lifetime
In [1]: x = 5; z = 99
In [2]: def addx(y):
...: z = x + y
...: return z
In [3]: addx(10)
Out[3]: 15
In [4]: z
Out[4]: 99
Lab Calc
2019-2020
The Python Language
●
Reusing code: functions
– Local vs. global variables: scope and lifetime
In [1]: x = 5; z = 99
In [2]: def addx(y):
...: global z
...: z = x + y
...: return z
In [3]: addx(10)
Out[3]: 15
In [4]: z
Out[4]: 15
Lab Calc
2019-2020
The Python Language
●
Reusing code: scripts and modules
– Python files: filename.py
– Scripts are top-level files
●
Sequence of python instructions
● Execute as program in IPython using %run
– Modules are files intended to be (partially) loaded
●
Sequence of functions and variables
● Load what is needed using import
●
Reusing code: scripts and modules
– Example: demo.py
Lab Calc
2019-2020
The Python Language
●
Reusing code: scripts and modules
– Many built-in modules
● Mathematics (math, cmath), system (os, sys), ...
– Mathematical module: import math
● Mathematical constants: math.pi, math.e
● Number-theory functions: math.factorial(x), math.gcd(x, y)
● Power functions: math.exp(x), math.log(x), math.sqrt(x)
● Trigonometric functions: math.cos(x), math.sin(x), math.tan(x)
– Package/library: a collection of modules
● numpy, scipy, matplotlib, ...
Lab Calc
2019-2020