REPL
Read, Evaluate, Print and Loop - Each line is read, evaluated, the return value is then printed to the screen, and then the process repeats.
# Invoke REPL
python3.6
Python 3.6.4 (default, Jan 5 2018, 20:24:27)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
Note: Exit REPL by using
exit()
or pressingCtrl+D
.
Base Types
int
782
0
-192
0b010 # binairy
0o642 # octal
0xF3 # hexadecimal
### CONVERTING TYPES ###
>>> int("15")
15
>>> int("3f", 16) # 2nd parameters defines the int number base
63
>>> int(15.56) # truncate the decimal part
15
float
9.23
0.0
-1.7e-6 # multiply a float by 10 to the power of n
### CONVERTING TYPES ###
>>> float("-11.24e8")
-1124000000.0
>>> round(15.56,1) # rounding to 1 decimal (0 -> int)
15.6
bool
True
False
### CONVERTING TYPES ###
>>> bool(x)
False # when x is null, empty, None or False
True # any other x
string
"Hello World\n" # \n escapes the string to a new line
"Hello\tWorld" # \t escapes a tab in the string
'I\'m' # \ escapes the following character, in this case '
"""
sentence that stretches
multiple lines
"""
### CONVERTING TYPES ###
>>> str(x)
"x" # representation string of x for display
>>> repr(x)
"x" # literal representation string of x
bytes
b"toto\xfe" # Hexadecimal
b"toto\775" # octal
### CONVERTING TYPES ###
>>> bytes([72,9,64])
b'H\t@'
>>> chr(64)
'@' # code to character
>>> ord('@')
64 # character to code
Container Types
Ordered sequences
list []
[1, 5, 9]
["x", 11, 8.9]
[]
### CONVERTING DICTIONARIES ###
>>> list("abc")
['a', 'b', 'c']
# sequence of 1 type --> list of another type
>>> [int(x) for x in ('1', '29', '-3')]
[1, 29, -3]
### OPERATIONS ON LISTS ###
1st.append(val) # add item at the end of the list
1st.extend(seq) # add sequence of items at end
1st.insert(index, val) # insert item at index
1st.remove(val) # remove first item with value val
1st.pop([index]) # remove & return item at index id (default last)
1st.sort() # sort list in place
1st.reverse () # reverse list in place
tuple ()
# non-modifiable values (immutables)
(1, 5, 9)
11, "y", 7.4
("mot",)
str bytes: “ “, b” “
Ordered sequences of chars and/or bytes.
# seperator str and sequence of str --> assembled str
>>> ':'.join(['toto', '12', 'passwd'])
'toto:12:passwd'
# str splitted on whitespaces --> list of str
>>> "words with spaces".split()
['words', 'with', 'spaces']
# str splitted on separator str --> list of str
>>> "1, 2, 4, 8".split(",")
['1', '2', '4', '8']
Key containers
dictionary {}
dict(a=3, b=4, c="some words")
{"key":"value", 2:"two", 3:"three", 3.14:"pi"} # key/value associations
### CONVERTING DICTIONARIES ###
>>> dict([(3, "three"), (1, "one")])
{1:'one', 3:'three'}
### OPERATIONS ON DICTIONARIES ###
d[key] = value
d[key]
d.update(d2) # update/add associations
d.keys() # iterable view on keys
d.values() # iterable view on values
d.items() # iterable view on associations
d.pop([key,default]) # value
d.popitem () # (key, value)
d.get(keyl,default]) # value
d.setdefault(key[,default]) # value
d.clear ()
del d[key]
set ()
# keys are hashable values (base types, immutables...)
{"key1", "key2"}
{1, 2, 9, 0}
### CONVERTING SETS ###
>>> set(["one", "two"])
{'one', 'two'}
### OPERATIONS ON SETS ###
| # union
& # intersection
- # difference
^ # symmetric difference
<, <=, >, >= # inclusion relations
s.update(s2)
s.copy()
s.add(key)
s.remove(key)
s.discard(key)
s.clear()
s.pop()
Note:
frozenset
is an immutable set.
Identifiers
For variables, functions, modules, classes… names:
a...zA...Z_
followed by a...zA...Z_0...9
.
- diacritics allowed but should be avoided
- language keywords are forbidden
- lower/UPPER case discrimination
# allowed examples # not allowed examples
a 8y
toto for
x7 True
y_max
BigOne
Variables assignment
Assignment is the binding of a name with a value.
- evaluation of the right side expression value
- assigment in order with left side names
>>> x = 1.2 + 8 + sin(y)
>>> a = b = c = 0 # assign multiple variables to the same value
>>> x,y,z = 9.2,-7,0 # assign multiple variables to the multiple values
>>> a,b = b,a # swap values
>>> x += 3 # increment: x = x + 3
>>> x -= 3 # decrement: x = x - 3
>>> x = None # set an undefined variable
>>> del x # remove variable name
# unpacking of sequence in item and list
>>> a, *b = seq
>>> *a, b = seq
Sequence Containers Indexing
indexes
| lst = | [ | 10 | , | 20 | , | 30 | , | 40 | , | 50 | ] |
| -------------- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| positive index | | 0 | | 1 | | 2 | | 3 | | 4 | |
| negative index | | -5 | | -4 | | -3 | | -2 | | -1 | |
# individual access to items via lst[index]
>>> lst[0]
10
>>> lst[-1]
50
# on mutable sequences, remove items via del
>>> del lst[3]
[10, 20, 30, 50]
# on mutable sequences, modify items via assignment
>>> lst[1] = 100
[10, 100, 30, 40, 50]
slices
| lst = | [ | 10 | , | 20 | , | 30 | , | 40 | , | 50 | ] |
| -------------- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| positive slice | 0 | | 1 | | 2 | | 3 | | 4 | | 5 |
| negative slice | -5 | | -4 | | -3 | | -2 | | -1 | | |
# individual access to items via lst[start_slice:end_slice:step]
>>> lst[:-2] # missing slice indentation --> from start/up to end
[10, 20, 30]
>>> lst[1:-1]
[20, 30, 40]
>>> lst[::2]
[10, 30, 50]
>>> lst[::-1]
[50, 40, 30, 20, 10]
# on mutable sequences, remove items via del
>>> del lst[3:5]
[10, 20, 30]
# on mutable sequences, modify items via assignment
>>> lst[1:4] = [15, 25]
[10, 15, 25, 50]
Boolean logic
comparisons
Boolean syntax | < |
> |
<= |
>= |
== |
!= |
---|---|---|---|---|---|---|
Boolean result | < |
> |
≤ |
≥ |
= |
≠ |
and / or / not
a and b |
a or b |
not a |
---|---|---|
logical and (both simultaneously) | logical or (one or other or both) | logical not |
Note:
and
andor
return value ofa
orb
(under shortcut evaluation) –> ensure thata
andb
are booleans.
Statement Blocks
parent statement:
child statement block 1:
...
parent statement:
child statement block 2:
...
Modules/Names Imports
Custom module custom_module
–> custom_module.py
# Import specific functions from modules and rename them
from mymod import nom1, nom2 as fact
# Import the entire module
import mymod
# access functions
mymod.nom1()
Note: Modules and packages searched in python path (cf
sys.path
)
Maths
Math operators and functions
Python operatorx | + |
- |
* |
/ |
// |
% |
** |
---|---|---|---|---|---|---|---|
math result | addition | subtraction | multiplication | division | floor division | modulo | power |
priority (3: low, 1: high) | 3 | 3 | 2 | 2 | 2 | 2 | 1 |
Note:
@
to create a matrix.
>>> abs(-3.2) # absolute value of a number
3.2
>>> round(3.57, 1) # round a number, 2nd parameter = nr of decimals
3.6
>>> pow(4, 3) # same as power operator
64.0
Angles and radians
from math import sin, pi, ...
>>> sin(pi/4)
0.707...
>>> cos(2*pi/3)
0.4999...
>>> sqrt
Conditional Statement
if <logical condition>:
<statement block>
elif <logical condition>:
<statement block>
else:
<statement block>
if x: # if bool(x) == True:
if not x: # if bool(x) == False:
Exceptions and Errors
raise ExceptionClass(...) # signaling an error
# error processing
try:
<processing block> # runs under normal circumstances
except Exception as e:
<processing block> # runs when an error occurs
finally:
<processing block> # runs under all circumstances
Loop Statements
Conditional Loop Statement
Statements block is executed as long as the condition is true.
while <logical condition>:
<statement block>
### EXAMPLE ###
s = 0 # initialization before the loop
i = 1 # initialization before the loop
while i <= 100: # condition with at least one variable value (here i)
s = s + i**2
i += 1 # make the condition var change --> infinite loop!
print("sum:", s)
Iterative Loop Statement
Statements block is executed for each item of a container or iterator.
for <var> in <sequence>:
<statement block>
### GO OVER SEQUENCE VALUES ###
s = "some text" # initialization before the loop
cnt = 0 # initialization before the loop
for i in s: # loop variable, assignment managed by for statement
if c == "e":
cnt += 1
print("found", cnt, "'e'")
### GO OVER SEQUENCE VALUES ###
1st = [11, 18, 9, 12, 23, 4, 17]
lost = 1
for idx in range (len (lst)):
val = 1st [idx]
if val > 15:
lost. append (val)
1st [idx] = 15
print ("modif:", Ist, "-lost:", lost)
Algo: limit values greater than 15, memorizing of lost values.
Loop Control
break # immediate exit
continue # next iteration
else # block for normal loop exit