Python 3 Cheat Sheet
The basics of the Python language
Calculations 5. Inputs/outputs
basic operations and power:+ - * / ** {"French":"sorties","English":"outputs"}print(value,... ,sep=’␣’,end
– remainder and quotient of the Euclidean division:% // valueof any kind,sepandendoptional
a= bq+ rwith|r| < |b|, Python :sgn(r) = sgn(b) ["entries:"]texte=input("message")
– rounding and truncation:round, int a,b=eval(input("message"))
– other basic math functions :max, min, abs
6. Commentaires
[Link] and assignments
online:#
– types & conversions :int, float, list, str,... block :’’’...’’’ or"""..."""
dynamic typing: no declaration - encoding (1reline) for accented characters:
simple affection:ma_variable= -5 # coding: utf-8 or# coding: latin_1
– instructions on the same line:a= 1 ;b= 2
multiple affections:a=b= 0
7. Control Structures
– parallel affections:a,b= 1.2, -4
– permutation of variables:a,b,c=b,c,a – 1reline ends with ':, indented lines, no end
combined affectations:+=, -=, *=, etc. – simple tests:==, !=, <, <=, >, >=,in
x += 1(⇐⇒ x = x + 1) combined tests:and, or, not,a<b<c
conditional allocation:m=aifa>belseb – structure alternative :
ifcondition1:
3. Lists instructions
elifcondition2:
– list:L= [-1, 3.2, 1/3, 1e-3] elif = contraction of else if
– empty list:[ ] instructions
else:
list multiplication:[0]*3→ [0,0,0]
instructions
– element of a list:L[1] = 5
- while loop (conditional loop):
must already exist, the index starts at 0!
whilecondition:
list functions:max, min, len, sum instructions
– add an item to a list:[Link]-2.5 for loop (unconditional loop):
add a list to a list:[Link][5, 2, -1] foriinlist:loop traversal
insert x at position i:[Link](i,x) instructions
count the number of x:n=[Link](x)
return the index of 1hex : i=[Link](x) forIin range(5): for i from 0 to 4
delete an item:of theL[i] instructions
slicingL[i:j](included→ jexclu) range(i,j,k)inclusive→ jexclu, k = not
– watch out for list assignments:L1=L2 escape/break a loop:break(else), continue
pointing at the same object
– lists by comprehension (or by description): [Link]
[x/10forxin range(-5, 6) ]
[k**2forkin range(10)ifk% 3 != 0 ] definition of function:
sum([n[i]*x[i]foriinrange(len(x))])/sum(n) deff(x,y):
returnx squared plus y squared
multiple referrals:returna,borreturnlist
4. Strings
- function defined at the call:returneval(expression)
channel:helloorhello – scope of variables: locale if modified (except lists)
concatenation:everyone → globalx
element of a chain:text[i] – parameters (formal): names used in the definition
non-modifiable, the index starts at 0! arguments: values/expressions used in the call
– numerous methods (see help): recursive function: a function that calls itself
count, find, replace, split, join, format, ... edge effect: action of the function̸=returned value)
– ascii/unicode code:wordAchr65 method: function attached to an object
– cut a line with string too long:\ syntax:[Link]()
II Modules and extensions
1. Vocabulary – titre :title("mon␣joli␣dessin")
– make the drawing (do not forget it):show()
– module: Python code in [Link]
windowxlim(xmin,xmax) ;ylim(ymin,ymax)
loading into memory:importfile(without .py)
oraxis([xmin,xmax,ymin,ymax])
script: module intended to be executed
– texte :text(posx,posy,"string")
package: folder of modules (with init)
library: generic module/package
standard library: basic modules 6. Other classic graphs
– extension: optional package (download) scatter plot (crowd of options, s = size (20)) :
– distribution: Python + dependencies scatter(Xlist, Ylist, s=20, mark='o', color='red')
packages available in a repository interval cutting:Xlist=[Link](a,b,n)
anaconda/miniconda: distribution bar chart:bar(Xlist,Ylist)
conda: package manager – labels :xticks(Xpos,Xlabels)
conda install numpy pyqt matplotlib scipy sympy histograms:hist(datalist,bins)
conda update conda; conda update <packages> withbins=number_of_classesorlist_of_classes
whisker boxes:boxplot(dataL1,dataL2,...)
2. Importation and interactive help - pie chart:pie(datalist, labels=stringlist)
importer: load into memory
7. Matrices
global import (module):importmath
requires a prefixing:[Link]([Link]/2) packagenumpy: importnumpy as np
targeted importation:frommathimportsqrt,exp – define a matrix:A=[Link]([[1, 0], [-1, 2]])
exhaustive importation:frommathimport* – product :[Link](A)[Link](A,A)
– use of aliases:frommathimportlog as ln – other functions :identity, zeros, diag, shape, ...
– remove the import:oflog;of themath power:[Link].matrix_power(A, 5)
- renaming of function:ln=log;log=log10 fromnumpy.linalgimportmatrix_power as mp
workspace (variable explorer): – inverse:[Link](A)
contains variables and imported modules/functions
help:[Link]? [Link]? 8. Integration, stats and probability
packagescipy(which extendsnumpy)
3. Standard Library Modules
– integral:[Link](f,a,b)
mathsqrt,sin,log,exp,e,pi,floor,gcd also returns the error
randomrandom(),randint(1, 6),uniform(0, 2) the infinite:[Link]
– time :time(), sleep(3), strftime('format') binomial coefficient:[Link](n,p)
fractionsFraction('2/3')orFraction(-3, 4) binomial law:[Link](k,n,p)
– statistics :mean(L),median(L),pvariance(L), probability mass function
pstdev(L)population standard deviation normal distribution:[Link](x, mu, sigma)
turtlegoto(x,y),left(angle),forward(dist), cumulative distribution function = distribution function
backward(dist), up(), down(), ..., mainloop() inverse normal law:[Link](p, mu, sigma)
percent point function = fractile function
4. The matplotlib graphic library
9. Formal calculation
modulepyplotessential graphic functions
global import with alias or exhaustive: packagesympyexpressions with chains or symbols
[Link] as plt – formal symbols :x,y=symbols('x y')
[Link]* developexpand("(x+y)**2")orexpand((x+y)**2)
avoid prefixing – factorize:factor(x*y + 2*x)
simplifiersimplify(cos(x)**2 +sin(x)**2)
affectionexpr=x**2 + y**2
5. Curves
[Link](x, 3)
– curve :plot(Xlist,Ylist,options) approximate value:sqrt(75).evalf()
grillgrid() – others:limit, diff, integrate, Matrix, plot, ...