Python 3 Language Basics John Quinn 1
Python 3 Language Basics
John Quinn
1
Useful Cheat Sheet
• https://perso.limsi.fr/pointal/_media/python:cours:mementopython3-english.pdf
2
Numbers• Numbers:
• integer numbers (base 2, 8, 10 (default), 16), e.g.
• x=15
• x=0b1111 # binary = 15 in decimal
• x=0o17 # octal = 15 in decimal
• x=0xF # hexadecimal = 15 in decimal
• floating point numbers, e.g. y=11.2, y=3.0e8
• complex numbers, e.g. z=1+2j
• The real, imaginary and conjugate of a complex number can be accessed:
• z.real, z.imag, z.conjugate()
• Note: you can use the python function type(variable) to get the type of a variable, e.g. type(z)
3
3
Boolean
• There is a Boolean type (Python type: bool) that can have the value of either “True” or “False”
• Normal logic rules apply to the bools.
4
• The following also get evaluated as False in Python: • numerical zero values (0, 0L, 0.0, 0.0+0.0j), • empty strings, • empty lists and empty tuples, • empty dictionaries. • plus the special value None.
4
Common Number OperatorsOperator Description Example
+,- Addition, Subtraction
*,% Multiplication, Modulo 27 % 7Result: 6
/ Division (Note: Python 2 does floor division)
>>> 10 / 33.3333333333333335
// Truncation/floor division 27 // 7 Result: 3
** Power 10 ** 3Result: 1000
or, and, not Boolean (a or b) and c
<, <=, >, >=, !=, ==
Comparison, returns a Boolean type 2 <= 3
%=, =, /=, //=, -=, +=, *=, **=
assignment x+=2 # add 2x-=3 # subtract 3 5
5
Operator Precedent
https://www.tutorialspoint.com/python/python_basic_operators.htm
Note: == checks if two variables have the same values while is checks of they are the same object.
6
Variable type and reassignments• Variables may be changed to store other types than what they were created with:
>>> x = 3 # x has value 3, stored in some memory location>>> y = x # y now points to the same memory as x>>> y = 2 # y now points to a new memory location, x is unchanged
i = 42 # data type is implicitly set to integeri = 42 + 0.11 # data type is changed to floati = "forty" # and now it will be a string
• Python automatically tidies up the memory left behind.
• Assignment of variables in Python might be a little different to what you’d expect:
7
Test two objects the same with id(var) or is
7
Mutable -vs- Immutable
• Mutable objects are objects that can have their size and/or values changed (e.g. lists, dictionaries)
• Immutable objects cannot be changed.
• If two variables refer to the same mutable object then a change to one is seen by both.
• Note: this does not apply to reassignment.
• Examples:….
8
Containers
• The most common Python containers (e.g. see https://docs.python.org/3.4/tutorial/datastructures.html) are listed below with the ones in blue the ones that we will use:
• strings: ordered sequence of characters, fast access, repeatable values, immutable
• tuples: ordered sequence, fast access, repeatable values, immutable, faster than lists, use if data is not to be changed
• lists: ordered sequence, fast access, repeatable values, mutable
• dictionaries: no a priori order, unique key, fast key access, mutable.
• sets: unordered collection with no duplicate elements, mutable.
9
9
Strings• Strings:
• strings are sequences of characters.
• strings are not changeable (“immutable”)
• strings are made with:
• single quotes (') 'This is a string with single quotes'
• double quotes (") "Obama's dog is called Bo"
• triple quotes, both single (''') and (""") '''String in triple quotes can extend over multiple lines, like this on, and can contain 'single' and "double" quotes.'''
10
10
Lists & Strings
• Indexing and slicing strings (& lists, tuples, sets….):
• s=”Python”
• s[0] is “P”
• s[-1] is “n” (-1 is last character)
• s[1:3] is “yt”
• s[3:5] is “ho”
• s[1:] is “ython”
• s[:3] is “Pyt”
• s[:] is “Python”
• s[0:5:2] is “Pto”Note: slicing strings always returns a copy of the elements in question.
11
11
Lists & Strings• Lists & Strings can be concatenated with “+”
• s='Hello ' + 'World'
• Lists & Strings can be repeated with “*”
• >>> 'hello '*5
• 'hello hello hello hello hello'
• Strings have lots of functions that act on them: e.g. ⇒
>>> s="Hello World">>> s.lower()'hello world'
>>> s.upper()'HELLO WORLD'
>>> s.count('o')2
>>> s.find('w')-1
>>> s.find('W')6
• Note: functions like upper() return a new string and do not change the original one.
https://docs.python.org/3/library/stdtypes.html#string-methods
• Note: strings can be compared with the “==“ operator.
12
12
Joining and Splitting Strings
Sequences indexing
Base Types
Python 3 Cheat Sheet©2012-2013 - Laurent PointalLicence Creative Commons Attribution 2
Official Python documentation on
http://docs.python.org/py3k
0783 -192int
9.23 -1.7e-60.0float
True Falsebool
"One\nTwo" 'I\'m'str
"""X\tY\tZ1\t2\t3"""
10-6
tab char
new line
multiline
Container Types
list [1,5,9] ["x",11,8.9] ["word"] []tuple (1,5,9) 11,"y",7.4 ("word",) ()
dict{1:"one",3:"three",2:"two",3.14:"π"}{"key":"value"}
set
{}
{1,9,3,0}
◾ ordered sequence, fast index access, repeatable values
set()
◾ no a priori order, unique key, fast key access ; keys = base types or tuples
{"key1","key2"}
immutable
Variables assignment
x = 1.2+8+sin(0)
y,z,r = 9.2,-7.6,"bad"
value or computed expression
variable name (identifier)
a‥zA‥Z_ followed by a‥zA‥Z_0‥9◽ diacritics allowed but should be avoided◽ language keywords forbidden◽ lower/UPPER case discrimination
expression with just comas
immutable,ordered sequence of chars
dictionary
integer, float, boolean, string
container with severalvalues (here a tuple)
variablesnames
Identifiers
☺ a toto x7 y_max BigOne☹ 8y and
x+=3 x-=2incrementdecrement
Conversions
for lists, tuples, strings, …
int("15")
float("-11.24e8")
bool
str(78.3) repr("Text")
can specify integer number base in 2nd parameter
int(15.56) truncate decimal part (round(15.56) for rounded integer)
and for litteral representation
type(expression)
use comparators (with ==, !=, <, >, …), logical boolean result
see other side for string formating allowing finer control
":".join(['toto','12','pswd']) 'toto:12:pswd'joining string sequence of strings
"words with spaces".split() ['words','with','spaces']
"1,4,8,2".split(",") ['1','4','8','2']splitting string
dict([(3,"three"),(1,"one")]) {1:'one',3:'three'}
list("abc") ['a','b','c']use each element
from sequence
set(["one","two"]) {'one','two'}use each element
from sequence
lst=[11, 67, "abc", 3.14, 42, 1968] lst[1]→67lst[-2]→42
0 1 2 3 54
-6 -5 -4 -3 -1-2
individual access to items via [index]positive index
negative index
0 1 2 3 54 6
-6 -5 -4 -3 -1-2negative slice
positive slice
access to sub-sequences via [start slice:end slice:step]
len(lst) 6
lst[1:3]→[67,"abc"]
lst[::2]→[11,"abc",42]lst[-3:-1]→[3.14,42]lst[:3]→[11,67,"abc"]
lst[:-1]→[11,67,"abc",3.14,42]
lst[4:]→[42,1968]
lst[1:-1]→[67,"abc",3.14,42]
lst[:]→[11,67,"abc",3.14,42,1968]Missing slice indication → from start / up to end.
Conditional Statement
if x==42: # block if logical expression x==42 is true print("real truth")elif x>0: # else block if logical expression x>0 is true print("be positive")elif bFinished: # else block if boolean variable bFinished is true print("how, finished")else: # else block for other cases print("when it's not")
Boolean Logic Statements Blocks
parent statement: statements block 1… ⁝ parent statement: statements block 2… ⁝
next statement after block 1
ind
enta
tio
n !
Comparators: < > <= >= == !=≠=≥≤
a and b
a or b
not a
logical and
logical or
logical notone or other or both
both simultaneously
if logical expression: statements block
statements block executed
only if a condition is true
TrueFalse
true constant value
false constant value
can go with several elif, elif... and only one final else,example :
lst[-1]→1968
lst[0]→11
last one
first one
x=None « undefined » constant value
Maths
Operators: + - * / // % **× ÷
integer ÷ ÷ remainder ab
from math import sin,pi…
' escaped
abs(-3.2)→3.2
round(3.57,1)→3.6
☝ floating point numbers… approximated values!
sin(pi/4)→0.707…cos(2*pi/3)→-0.4999…
sqrt(81)→9.0 √log(e**2)→2.0
angles in radians
acos(0.5)→1.0471…
etc. (cf doc)
(1+5.3)*2→12.6
for variables, functions,
modules, classes… names
Mémento v1.2.2
str as an ordered sequence of chars
On mutable sequences, usable to remove del lst[3:5] and to modify with assignment lst[1:4]=['hop',9]
key/value associations
Sequences indexing
Base Types
Python 3 Cheat Sheet©2012-2013 - Laurent PointalLicence Creative Commons Attribution 2
Official Python documentation on
http://docs.python.org/py3k
0783 -192int
9.23 -1.7e-60.0float
True Falsebool
"One\nTwo" 'I\'m'str
"""X\tY\tZ1\t2\t3"""
10-6
tab char
new line
multiline
Container Types
list [1,5,9] ["x",11,8.9] ["word"] []tuple (1,5,9) 11,"y",7.4 ("word",) ()
dict{1:"one",3:"three",2:"two",3.14:"π"}{"key":"value"}
set
{}
{1,9,3,0}
◾ ordered sequence, fast index access, repeatable values
set()
◾ no a priori order, unique key, fast key access ; keys = base types or tuples
{"key1","key2"}
immutable
Variables assignment
x = 1.2+8+sin(0)
y,z,r = 9.2,-7.6,"bad"
value or computed expression
variable name (identifier)
a‥zA‥Z_ followed by a‥zA‥Z_0‥9◽ diacritics allowed but should be avoided◽ language keywords forbidden◽ lower/UPPER case discrimination
expression with just comas
immutable,ordered sequence of chars
dictionary
integer, float, boolean, string
container with severalvalues (here a tuple)
variablesnames
Identifiers
☺ a toto x7 y_max BigOne☹ 8y and
x+=3 x-=2incrementdecrement
Conversions
for lists, tuples, strings, …
int("15")
float("-11.24e8")
bool
str(78.3) repr("Text")
can specify integer number base in 2nd parameter
int(15.56) truncate decimal part (round(15.56) for rounded integer)
and for litteral representation
type(expression)
use comparators (with ==, !=, <, >, …), logical boolean result
see other side for string formating allowing finer control
":".join(['toto','12','pswd']) 'toto:12:pswd'joining string sequence of strings
"words with spaces".split() ['words','with','spaces']
"1,4,8,2".split(",") ['1','4','8','2']splitting string
dict([(3,"three"),(1,"one")]) {1:'one',3:'three'}
list("abc") ['a','b','c']use each element
from sequence
set(["one","two"]) {'one','two'}use each element
from sequence
lst=[11, 67, "abc", 3.14, 42, 1968] lst[1]→67lst[-2]→42
0 1 2 3 54
-6 -5 -4 -3 -1-2
individual access to items via [index]positive index
negative index
0 1 2 3 54 6
-6 -5 -4 -3 -1-2negative slice
positive slice
access to sub-sequences via [start slice:end slice:step]
len(lst) 6
lst[1:3]→[67,"abc"]
lst[::2]→[11,"abc",42]lst[-3:-1]→[3.14,42]lst[:3]→[11,67,"abc"]
lst[:-1]→[11,67,"abc",3.14,42]
lst[4:]→[42,1968]
lst[1:-1]→[67,"abc",3.14,42]
lst[:]→[11,67,"abc",3.14,42,1968]Missing slice indication → from start / up to end.
Conditional Statement
if x==42: # block if logical expression x==42 is true print("real truth")elif x>0: # else block if logical expression x>0 is true print("be positive")elif bFinished: # else block if boolean variable bFinished is true print("how, finished")else: # else block for other cases print("when it's not")
Boolean Logic Statements Blocks
parent statement: statements block 1… ⁝ parent statement: statements block 2… ⁝
next statement after block 1
ind
enta
tio
n !
Comparators: < > <= >= == !=≠=≥≤
a and b
a or b
not a
logical and
logical or
logical notone or other or both
both simultaneously
if logical expression: statements block
statements block executed
only if a condition is true
TrueFalse
true constant value
false constant value
can go with several elif, elif... and only one final else,example :
lst[-1]→1968
lst[0]→11
last one
first one
x=None « undefined » constant value
Maths
Operators: + - * / // % **× ÷
integer ÷ ÷ remainder ab
from math import sin,pi…
' escaped
abs(-3.2)→3.2
round(3.57,1)→3.6
☝ floating point numbers… approximated values!
sin(pi/4)→0.707…cos(2*pi/3)→-0.4999…
sqrt(81)→9.0 √log(e**2)→2.0
angles in radians
acos(0.5)→1.0471…
etc. (cf doc)
(1+5.3)*2→12.6
for variables, functions,
modules, classes… names
Mémento v1.2.2
str as an ordered sequence of chars
On mutable sequences, usable to remove del lst[3:5] and to modify with assignment lst[1:4]=['hop',9]
key/value associations
13
13
Read from the keyboard
• To read a string from the keyboard use input(‘Prompt: ‘), e.g.
• s=input('Please enter something: ')
• To convert use the functions: float(), int(), complex(), e.g.
• s=float(input('Please enter a number: ‘))
• Or one can split the string and convert different parts of the list individually.
• If you try to convert something that is incompatible (e.g. characters to a float) an error will occur.
• Catching and handling errors (try, except) is beyond the scope of this tutorial!
14
14
Tuples• Tuples are immutable lists of Python objects.
• They are created with (), e.g.
• tup1 = ('physics', 'chemistry', 1997, 2000);
• tup2 = (1, 2, 3, 4, 5, 6, 7 );
• The are indexed using the [] notation, e.g.
• tup1[0]: physics
• tup2[1:5]: [2, 3, 4, 5]
• They cannot be changed. i.e. (immutable) elements cannot be changed, nor can elements be deleted or appended) but mutable elements may be modified.
15
Lists
• Lists:
• Store ordered sequences of elements and may be accessed via indices using the [] notation
• Create with “[]”
>>> l = ["London", "Paris", "Strasbourg", "Zurich"]
>>> print(l[1], l[2])Paris Strasbourg
• Lists may store arbitrary types, e.g. x=[1, "hello", 3.4]
• Lists may be nested.
• Lists are mutable - items can be removed, added, changed., e.g. 16
16
Lists>>> cubes = [1, 8, 27, 65, 125][1, 8, 27, 65, 125]
>>> cubes[3]=64[1, 8, 27, 64, 125]
>>> cubes=cubes+[216, 343, 512][1, 8, 27, 64, 125, 216, 343, 512]
>>> cubes.append(729)[1, 8, 27, 64, 125, 216, 343, 512, 729]
>>> cubes[2:4]=[] # removing elements[1, 8, 125, 216, 343, 512, 729]
>>> cubes[2:2]=[27,64] # inserting elements[1, 8, 27, 64, 125, 216, 343, 512, 729]
17
17
Dictionaries• Dictionaries contain (key: value) pairs.
• Dictionaries are created with {} and indexed using [key] notation.
• Items are access via their key and not their position (as withs strings and lists)
• They can be easily changes and shrink and grow as needed….
• Example: city: populations
18
>>> city = {"New York City”: 8175133, “Los Angeles": 3792621, ”Washington”: 632323, "Chicago": 2695598, “Toronto”: 2615060, “Montreal": 11854442, “Ottawa": 883391, “Boston": 626000}
18
Dictionaries>>> city = {"New York City":8175133, "Los Angeles": 3792621, "Washington":632323, "Chicago": 2695598, "Toronto":2615060, "Montreal":11854442, "Ottawa":883391, "Boston":62600}
>>> city["New York City"]8175133
>>> city["Toronto"]2615060
>>> city["Halifax"] = 390096
>>> city{'Toronto': 2615060, 'Ottawa': 883391, 'Los Angeles': 3792621, 'Chicago': 2695598, 'New York City': 8175133, 'Halifax': 390096, 'Boston': 62600, 'Washington': 632323, 'Montreal': 11854442}
>>> city = {}>>> city{}
19
19
Operations on Containers
Display / Inputprint("v=",3,"cm :",x,",",y+4)
print options:
◽ sep=" " (items separator, default space)
◽ end="\n" (end of print, default new line)
◽ file=f (print to file, default standard output)
items to display: litteral values, variables, expressions
loop on dict/set = loop on sequence of keys
Conditional loop statementstatements block executed as long
as condition is true
while logical expression: statements block
s = 0i = 1
while i <= 100: # statement executed as long as i ≤ 100 s = s + i**2 i = i + 1
print("sum:",s)
initializations before the loop
condition with at least one variable value (here i)
s= ∑i=1
i=100
i2
☝ make condition variable change
Iterative loop statementstatements block executed for each
item of a container or iterator
for variable in sequence: statements block
s = "Some text"cnt = 0
for c in s: if c == "e": cnt = cnt + 1print("found",cnt,"'e'")
Go over sequence's values
Count number of
e in the string
Go over sequence's index
◽ modify item at index
◽ access items around index (before/after)
lst = [11,18,9,12,23,4,17]lost = []for idx in range(len(lst)): val = lst[idx] if val > 15: lost.append(val) lst[idx] = 15print("modif:",lst,"-lost:",lost)
Limit values greater
than 15, memorization
of lost values.
☝ be careful of inifinite loops !
initializations before the loop
loop variable, value managed by for statement
use slices to go over a subset of the sequence
computed result after the loop
Generator of int sequences
Files
s = input("Instructions:")☝ input always returns a string, convert it to required type
(cf boxed Conversions on on ther side).
frequently used in
for iterative loops
range returns a « generator », converts it to list to see
the values, example:
print(list(range(4)))
range(5) 0 1 2 3 4range(3,8) 3 4 5 6 7range(2,12,3) 2 5 8 11
range([start,]stop [,step])
f = open("fil.txt","w",encoding="utf8")storing data on disk, and reading it back
opening mode
◽ 'r' read
◽ 'w' write
◽ 'a' append…
encoding of
chars for text
files:
utf8 ascii
latin1 …
name of file
on disk
(+path…)
file variable
for operations
f.write("hello")writing
☝ text file → read /write only
strings, convert from/to required
type.
reading
s = f.read(4)
for line in f : # line processing block
cf functions in modules os and os.path
if char count not
specified, read
whole file
s = f.readline()
read next
line
f.close() ☝ don't forget to close file after use
Pythonic automatic close : with open(…) as f:
very common: iterative loop reading lines of a text file
Function definition
def fctname(p_x,p_y,p_z): """documentation""" # statements block, res computation, etc. return res
function name (identifier)
result value of the call.
if no computed result to
return: return None☝ parameters and all of this bloc
only exist in the block and during
the function call ("black box")
named parameters
Function callr = fctname(3,i+2,2*i)
one argument per parameter
retrieve returned result (if necessary)
empty string if end of file
not includeddefault 0
"model {} {} {}".format(x,y,r)"{selection:formating!conversion}"◽ Selection :
2 x 0.nom 4[key] 0[2]
str
Strings formatingvalues to formatformating directives
"{:+2.3f}".format(45.7273)→'+45.727'"{1:>10s}".format(8,"toto")→' toto'"{!r}".format("I'm")→'"I\'m"'
◽ Conversion : s (readable text) or r (litteral representation)
< > ^ = 0 at start for filling with 0
integer: b binary, c char, d decimal (default), o octal, x or X hexa…
float: e or E exponential, f or F fixed point, g or G appropriate (default),
% percent
string : s …
◽ Formating :
fillchar alignment sign minwidth.precision~maxwidth type
+ - space
Ex
am
ple
s
Operations on containerslen(c)
min(c) max(c) sum(c)sorted(c)
reversed(c)
☝ modify original list
lst.append(item)
lst.pop(idx)lst.sort() lst.reverse()
c.index(val) c.count(val)
→ items count
→ sorted copy
→ reverse iterator
→ position → events count
lst.extend(seq) add item at end
add sequence of items at end
lst.insert(idx,val) insert item at index
lst.remove(val) remove first item with value
remove item at index and return its value
sort / reverse list in place
Operations on dictionaries Operations on setsOperators:
| → union (vertical bar char)
& → intersection
- ^ → difference/symetric diff
< <= > >= → inclusion relations
d.update(d2) update/add
associations
Note: For dictionaries and set, these
operations use keys.
Special for sequence containeurs (lists, tuples, strings) :
val in c → boolean, membersihp operator in (absence not in)
Operations on lists
d[key]→value del d[clé]d[key]=value
d.keys()
d.clear()
d.items()d.values() views on keys, values
associations
d.pop(clé)
s.update(s2)s.add(key) s.remove(key)s.discard(key)
c*5 → duplicate c+c2→ concatenate
Loop control
break
continue
immediate exit
next iteration
Go simultaneously over sequence's index and values:for idx,val in enumerate(lst):
enumerate(c)→ iterator on (index,value)
20
20
Operations on Lists & Dictionaries
Display / Inputprint("v=",3,"cm :",x,",",y+4)
print options:
◽ sep=" " (items separator, default space)
◽ end="\n" (end of print, default new line)
◽ file=f (print to file, default standard output)
items to display: litteral values, variables, expressions
loop on dict/set = loop on sequence of keys
Conditional loop statementstatements block executed as long
as condition is true
while logical expression: statements block
s = 0i = 1
while i <= 100: # statement executed as long as i ≤ 100 s = s + i**2 i = i + 1
print("sum:",s)
initializations before the loop
condition with at least one variable value (here i)
s= ∑i=1
i=100
i2
☝ make condition variable change
Iterative loop statementstatements block executed for each
item of a container or iterator
for variable in sequence: statements block
s = "Some text"cnt = 0
for c in s: if c == "e": cnt = cnt + 1print("found",cnt,"'e'")
Go over sequence's values
Count number of
e in the string
Go over sequence's index
◽ modify item at index
◽ access items around index (before/after)
lst = [11,18,9,12,23,4,17]lost = []for idx in range(len(lst)): val = lst[idx] if val > 15: lost.append(val) lst[idx] = 15print("modif:",lst,"-lost:",lost)
Limit values greater
than 15, memorization
of lost values.
☝ be careful of inifinite loops !
initializations before the loop
loop variable, value managed by for statement
use slices to go over a subset of the sequence
computed result after the loop
Generator of int sequences
Files
s = input("Instructions:")☝ input always returns a string, convert it to required type
(cf boxed Conversions on on ther side).
frequently used in
for iterative loops
range returns a « generator », converts it to list to see
the values, example:
print(list(range(4)))
range(5) 0 1 2 3 4range(3,8) 3 4 5 6 7range(2,12,3) 2 5 8 11
range([start,]stop [,step])
f = open("fil.txt","w",encoding="utf8")storing data on disk, and reading it back
opening mode
◽ 'r' read
◽ 'w' write
◽ 'a' append…
encoding of
chars for text
files:
utf8 ascii
latin1 …
name of file
on disk
(+path…)
file variable
for operations
f.write("hello")writing
☝ text file → read /write only
strings, convert from/to required
type.
reading
s = f.read(4)
for line in f : # line processing block
cf functions in modules os and os.path
if char count not
specified, read
whole file
s = f.readline()
read next
line
f.close() ☝ don't forget to close file after use
Pythonic automatic close : with open(…) as f:
very common: iterative loop reading lines of a text file
Function definition
def fctname(p_x,p_y,p_z): """documentation""" # statements block, res computation, etc. return res
function name (identifier)
result value of the call.
if no computed result to
return: return None☝ parameters and all of this bloc
only exist in the block and during
the function call ("black box")
named parameters
Function callr = fctname(3,i+2,2*i)
one argument per parameter
retrieve returned result (if necessary)
empty string if end of file
not includeddefault 0
"model {} {} {}".format(x,y,r)"{selection:formating!conversion}"◽ Selection :
2 x 0.nom 4[key] 0[2]
str
Strings formatingvalues to formatformating directives
"{:+2.3f}".format(45.7273)→'+45.727'"{1:>10s}".format(8,"toto")→' toto'"{!r}".format("I'm")→'"I\'m"'
◽ Conversion : s (readable text) or r (litteral representation)
< > ^ = 0 at start for filling with 0
integer: b binary, c char, d decimal (default), o octal, x or X hexa…
float: e or E exponential, f or F fixed point, g or G appropriate (default),
% percent
string : s …
◽ Formating :
fillchar alignment sign minwidth.precision~maxwidth type
+ - space
Ex
am
ple
s
Operations on containerslen(c)
min(c) max(c) sum(c)sorted(c)
reversed(c)
☝ modify original list
lst.append(item)
lst.pop(idx)lst.sort() lst.reverse()
c.index(val) c.count(val)
→ items count
→ sorted copy
→ reverse iterator
→ position → events count
lst.extend(seq) add item at end
add sequence of items at end
lst.insert(idx,val) insert item at index
lst.remove(val) remove first item with value
remove item at index and return its value
sort / reverse list in place
Operations on dictionaries Operations on setsOperators:
| → union (vertical bar char)
& → intersection
- ^ → difference/symetric diff
< <= > >= → inclusion relations
d.update(d2) update/add
associations
Note: For dictionaries and set, these
operations use keys.
Special for sequence containeurs (lists, tuples, strings) :
val in c → boolean, membersihp operator in (absence not in)
Operations on lists
d[key]→value del d[clé]d[key]=value
d.keys()
d.clear()
d.items()d.values() views on keys, values
associations
d.pop(clé)
s.update(s2)s.add(key) s.remove(key)s.discard(key)
c*5 → duplicate c+c2→ concatenate
Loop control
break
continue
immediate exit
next iteration
Go simultaneously over sequence's index and values:for idx,val in enumerate(lst):
enumerate(c)→ iterator on (index,value)
21
Display / Inputprint("v=",3,"cm :",x,",",y+4)
print options:
◽ sep=" " (items separator, default space)
◽ end="\n" (end of print, default new line)
◽ file=f (print to file, default standard output)
items to display: litteral values, variables, expressions
loop on dict/set = loop on sequence of keys
Conditional loop statementstatements block executed as long
as condition is true
while logical expression: statements block
s = 0i = 1
while i <= 100: # statement executed as long as i ≤ 100 s = s + i**2 i = i + 1
print("sum:",s)
initializations before the loop
condition with at least one variable value (here i)
s= ∑i=1
i=100
i2
☝ make condition variable change
Iterative loop statementstatements block executed for each
item of a container or iterator
for variable in sequence: statements block
s = "Some text"cnt = 0
for c in s: if c == "e": cnt = cnt + 1print("found",cnt,"'e'")
Go over sequence's values
Count number of
e in the string
Go over sequence's index
◽ modify item at index
◽ access items around index (before/after)
lst = [11,18,9,12,23,4,17]lost = []for idx in range(len(lst)): val = lst[idx] if val > 15: lost.append(val) lst[idx] = 15print("modif:",lst,"-lost:",lost)
Limit values greater
than 15, memorization
of lost values.
☝ be careful of inifinite loops !
initializations before the loop
loop variable, value managed by for statement
use slices to go over a subset of the sequence
computed result after the loop
Generator of int sequences
Files
s = input("Instructions:")☝ input always returns a string, convert it to required type
(cf boxed Conversions on on ther side).
frequently used in
for iterative loops
range returns a « generator », converts it to list to see
the values, example:
print(list(range(4)))
range(5) 0 1 2 3 4range(3,8) 3 4 5 6 7range(2,12,3) 2 5 8 11
range([start,]stop [,step])
f = open("fil.txt","w",encoding="utf8")storing data on disk, and reading it back
opening mode
◽ 'r' read
◽ 'w' write
◽ 'a' append…
encoding of
chars for text
files:
utf8 ascii
latin1 …
name of file
on disk
(+path…)
file variable
for operations
f.write("hello")writing
☝ text file → read /write only
strings, convert from/to required
type.
reading
s = f.read(4)
for line in f : # line processing block
cf functions in modules os and os.path
if char count not
specified, read
whole file
s = f.readline()
read next
line
f.close() ☝ don't forget to close file after use
Pythonic automatic close : with open(…) as f:
very common: iterative loop reading lines of a text file
Function definition
def fctname(p_x,p_y,p_z): """documentation""" # statements block, res computation, etc. return res
function name (identifier)
result value of the call.
if no computed result to
return: return None☝ parameters and all of this bloc
only exist in the block and during
the function call ("black box")
named parameters
Function callr = fctname(3,i+2,2*i)
one argument per parameter
retrieve returned result (if necessary)
empty string if end of file
not includeddefault 0
"model {} {} {}".format(x,y,r)"{selection:formating!conversion}"◽ Selection :
2 x 0.nom 4[key] 0[2]
str
Strings formatingvalues to formatformating directives
"{:+2.3f}".format(45.7273)→'+45.727'"{1:>10s}".format(8,"toto")→' toto'"{!r}".format("I'm")→'"I\'m"'
◽ Conversion : s (readable text) or r (litteral representation)
< > ^ = 0 at start for filling with 0
integer: b binary, c char, d decimal (default), o octal, x or X hexa…
float: e or E exponential, f or F fixed point, g or G appropriate (default),
% percent
string : s …
◽ Formating :
fillchar alignment sign minwidth.precision~maxwidth type
+ - space
Ex
am
ple
s
Operations on containerslen(c)
min(c) max(c) sum(c)sorted(c)
reversed(c)
☝ modify original list
lst.append(item)
lst.pop(idx)lst.sort() lst.reverse()
c.index(val) c.count(val)
→ items count
→ sorted copy
→ reverse iterator
→ position → events count
lst.extend(seq) add item at end
add sequence of items at end
lst.insert(idx,val) insert item at index
lst.remove(val) remove first item with value
remove item at index and return its value
sort / reverse list in place
Operations on dictionaries Operations on setsOperators:
| → union (vertical bar char)
& → intersection
- ^ → difference/symetric diff
< <= > >= → inclusion relations
d.update(d2) update/add
associations
Note: For dictionaries and set, these
operations use keys.
Special for sequence containeurs (lists, tuples, strings) :
val in c → boolean, membersihp operator in (absence not in)
Operations on lists
d[key]→value del d[clé]d[key]=value
d.keys()
d.clear()
d.items()d.values() views on keys, values
associations
d.pop(clé)
s.update(s2)s.add(key) s.remove(key)s.discard(key)
c*5 → duplicate c+c2→ concatenate
Loop control
break
continue
immediate exit
next iteration
Go simultaneously over sequence's index and values:for idx,val in enumerate(lst):
enumerate(c)→ iterator on (index,value)
21
Check it an item is in a container
• To check if an item is in a container use in or not in:
>>> abc = ["a","b","c","d","e"]
>>> "a" in abcTrue
>>> "a" not in abcFalse
>>> "e" not in abcFalse
>>> "f" not in abcTrue
22
22
Conditional Statements• The general form of the if statement is:
if condition_1: statement_block_1elif condition_2: statement_block_2else: statement_block_3
• The following get evaluated as False in Python: • numerical zero values (0, 0L, 0.0, 0.0+0.0j), • the Boolean value False, • empty strings, • empty lists and empty tuples, • empty dictionaries. • plus the special value None.
23
23
Conditional Statements
• Equivalent common short form of if statement in Python:
if (a > b) max=aelse max=b
• Consider calculation of maximum of two numbers a, b:
max = a if (a > b) else b
24
24
Conditional Statements
# Program to convert dog years to human years:
age = int(input("Age of the dog: "))print()
if age < 0:print("This can hardly be true!")
elif age == 1:print("about 14 human years")
elif age == 2:print("about 22 human years")
elif age > 2:human = 22 + (age -2)*5print("Human years: ", human)
25
25
while Loops
• A while loop is executed while some condition is True, execution ceases and the program continues after the while loop when the condition becomes False.
• It is also possible to
• break out of while loop with the break command or to • skip the rest of the code block and jump straight to testing the expression with
the continue command.
n = 100sum = 0counter = 0
while counter < n: sum = sum + counter counter += 1
print("Sum=",sum)
while True: value=int(input("Guess: ")) if value==42 break
print("Congratulations! ")
26
26
for Loops
• The general syntax for a for loop is: for <variable> in <sequence>: <statements>
>>> languages = ["C", "C++", "Perl", "Python"] >>> for x in languages:... print(x)... CC++PerlPython>>>
27
• It is also possible to
• break out of for loop with the break command or to
• skip the rest of the code block and jump straight to testing the expression with the continue command.
27
for and while Loops• for and while loops both have optional else statements, that get executed
when the loop has not terminated by a break.
• See documentation on line at:
• https://docs.python.org/3/reference/compound_stmts.html#while
• https://docs.python.org/3/reference/compound_stmts.html#for
28
28
for Loops• The range() function is very useful for for loops.
• range() is a generator - it produces a different integer each time it is called.
• range() takes at least 1 but up to 3 arguments:
• range(begin=0, end, step=1)
for i in range(5): print(i) Produces numbers 0, 1, 2, 3, 4
for i in range(4,8): Produces numbers 4, 5, 6, 7
for i in range(0,11,2): Produces numbers 0, 2, 4, 6, 8,10
29
29
for Loops: range and enumerate
• A range can be converted to a list: >>> list(range(0,11,2)[0, 2, 4, 6, 8, 10]
• When looping over a list it is dangerous to modify the list - instead loop over a copy of the list.
>>> for x in a[:]: if x < 0: a.remove(x)
• To loop over a list: >>> for i in range(len(mylist)); print(i,mylist[i])
>>> for i,value in enumerate(mylist): print(i,value)
or
• The step can be negative.
30
30
for Loops: zip
• Use zip to loop over two (or more) lists simultaneously:
In [13]: x=list(range(10))
In [14]: y=list(range(10,20))
In [15]: for a,b in zip(x,y): print(a,b)0 101 112 123 134 145 156 167 178 189 19
31
List Comprehensions
• Consider the code: numbers=list(range(10))xsq=[]for x in numbers: xsq.append(x**2)
• Python has an elegant alternative approach:
numbers=list(range(10))xsq=[x**2 for x in numbers]
• Logical expressions can be included:
xsq=[x**2 for x in numbers if x>5]
32
32
string formatting
• There are a few different ways for produce formatted output - we will use the Python 3 function the string .format() function.
• str.format()is very powerful and we will only touch on the basics here.
• Learn by examples:
>>> x=10>>> y=20
>>> print("x={}, y={}".format(x,y))x=10, y=20
>>> print("x={0}, y={1}".format(x,y))x=10, y=20
>>> print("x={a}, y={b}".format(a=10,b=11))x=10, y=11
33
33
string formatting• After the identifier in the {} we can specify formatting option by using a “:”
followed by the options.>>> print("x={0:10.5f}".format(2.35))x= 2.35000
>>> print("x={0:+010.5f}".format(2.35))x=+002.35000
>>> print("{:08b}".format(15))00001111
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]fill ::= <any character>align ::= "<" | ">" | "=" | "^"sign ::= "+" | "-" | " "width ::= integerprecision ::= integertype ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
.format spec: (from https://docs.python.org/3/library/string.html#formatspec):
• Please see online documentation for more explanations and examples of format specification.
34
34
Writing to a File• In general when you do an experiment under computer control you will want to
save data to a file.
• Here we are only concerned with writing data to the file as we will use numpy to read it back in (i.e. we will skip the general Python file reading routines).
• Procedure: >>> fh = open("example.txt", "w")>>> fh.write(str(x)+”\n”) >>> fh.close()
• The open() command takes the filename and the mode: (read: “r” (default), write: “w”, append: “a”) as arguments.
• The write() command takes a single string argument and writes the string to a file. ”\n” indicates a new line.
• It is likely that you will write() in a loop to save multiple values to the file.
• It is essential to close() the file afterwards. 35
35
Writing to a file
• If an error occurs then the file may not get closed properly.
• Alternative way:
with open(“results.txt”,”w") as f:s=string(some_data) f.write(s+’\n’)
• The file will be closed automatically once the “with” code block exits
36