0% found this document useful (0 votes)
18 views

Py5 Hacks

This document provides a cheat sheet overview of key Python concepts like data types, variables, operators, conditional statements, and modules. It includes syntax examples and brief explanations of core language elements like integers, floats, booleans, strings, lists, tuples, dictionaries, sets, conditionals, functions and more.

Uploaded by

Gamer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Py5 Hacks

This document provides a cheat sheet overview of key Python concepts like data types, variables, operators, conditional statements, and modules. It includes syntax examples and brief explanations of core language elements like integers, floats, booleans, strings, lists, tuples, dictionaries, sets, conditionals, functions and more.

Uploaded by

Gamer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

©2012-2015 - Laurent Pointal Mémento v2.0.

6
License Creative Commons Attribution 4 Python 3 Cheat Sheet Latest version on :
https://perso.limsi.fr/pointal/python:memento
integer, float, boolean, string, bytes Base Types ◾ ordered sequences, fast index access, repeatable values Container Types
int 783 0 -192 0b010 0o642 0xF3 list [1,5,9] ["x",11,8.9] ["mot"] []
zero binary octal hexa tuple (1,5,9) 11,"y",7.4 ("mot",) ()
float 9.23 0.0 -1.7e-6
-6 Non modifiable values (immutables) ☝ expression with only comas →tuple
bool True False ×10
""
str bytes (ordered sequences of chars / bytes)
str "One\nTwo" Multiline string: b""
escaped new line """X\tY\tZ ◾ key containers, no a priori order, fast key access, each key is unique
'I\'m' 1\t2\t3""" dictionary dict {"key":"value"} dict(a=3,b=4,k="v") {}
escaped ' escaped tab (key/value associations) {1:"one",3:"three",2:"two",3.14:"π"}
bytes b"toto\xfe\775" collection set {"key1","key2"} {1,9,3,0} set()
hexadecimal octal ☝ immutables ☝ keys=hashable values (base types, immutables…) frozenset immutable set empty

for variables, functions, Identifiers type(expression) Conversions


modules, classes… names
int("15") → 15
int("3f",16) → 63 nd
can specify integer number base in 2 parameter
a…zA…Z_ followed by a…zA…Z_0…9
◽ diacritics allowed but should be avoided int(15.56) → 15 truncate decimal part
◽ language keywords forbidden float("-11.24e8") → -1124000000.0
◽ lower/UPPER case discrimination round(15.56,1)→ 15.6 rounding to 1 decimal (0 decimal → integer number)
☺ a toto x7 y_max BigOne bool(x) False for null x, empty container x , None or False x ; True for other x
☹ 8y and for str(x)→ "…" representation string of x for display (cf. formatting on the back)
chr(64)→'@' ord('@')→64 code ↔ char
= Variables assignment
repr(x)→ "…" literal representation string of x
☝ assignment ⇔ binding of a name with a value
1) evaluation of right side expression value bytes([72,9,64]) → b'H\t@'
2) assignment in order with left side names list("abc") → ['a','b','c']
x=1.2+8+sin(y) dict([(3,"three"),(1,"one")]) → {1:'one',3:'three'}
a=b=c=0 assignment to same value set(["one","two"]) → {'one','two'}
y,z,r=9.2,-7.6,0 multiple assignments separator str and sequence of str → assembled str
a,b=b,a values swap ':'.join(['toto','12','pswd']) → 'toto:12:pswd'
a,*b=seq unpacking of sequence in str splitted on whitespaces → list of str
*a,b=seq item and list "words with spaces".split() → ['words','with','spaces']
and str splitted on separator str → list of str
x+=3 increment ⇔ x=x+3 *=
x-=2 decrement ⇔ x=x-2 /= "1,4,8,2".split(",") → ['1','4','8','2']
x=None « undefined » constant value %= sequence of one type → list of another type (via list comprehension)
del x remove name x … [int(x) for x in ('1','29','-3')] → [1,29,-3]
for lists, tuples, strings, bytes… Sequence Containers Indexing
negative index -5 -4 -3 -2 -1 Items count Individual access to items via lst[index]
positive index 0 1 2 3 4 len(lst)→5 lst[0]→10 ⇒ first one lst[1]→20
lst=[10, 20, 30, 40, 50] lst[-1]→50 ⇒ last one lst[-2]→40
positive slice 0 1 2 3 4 5 ☝ index from 0
On mutable sequences (list), remove with
negative slice -5 -4 -3 -2 -1 (here from 0 to 4)
del lst[3] and modify with assignment
lst[4]=25
Access to sub-sequences via lst[start slice:end slice:step]
lst[:-1]→[10,20,30,40] lst[::-1]→[50,40,30,20,10] lst[1:3]→[20,30] lst[:3]→[10,20,30]
lst[1:-1]→[20,30,40] lst[::-2]→[50,30,10] lst[-3:-1]→[30,40] lst[3:]→[40,50]
lst[::2]→[10,30,50] lst[:]→[10,20,30,40,50] shallow copy of sequence
Missing slice indication → from start / up to end.
On mutable sequences (list), remove with del lst[3:5] and modify with assignment lst[1:4]=[15,25]

Boolean Logic Statements Blocks Modules/Names Imports


module truc⇔file truc.py
Comparisons : < > <= >= == != from monmod import nom1,nom2 as fct
(boolean results) ≤ ≥ = ≠ parent statement: →direct access to names, renaming with as
a and b logical and both simulta- statement block 1… import monmod →access via monmod.nom1 …
indentation !

-neously ⁝ ☝ modules and packages searched in python path (cf sys.path)


a or b logical or one or other parent statement: statement block executed only
or both Conditional Statement
statement block2… if a condition is true
☝ pitfall : and and or return value of a or ⁝ yes no yes
of b (under shortcut evaluation). if logical condition: ? ?
⇒ ensure that a and b are booleans. no
not a logical not
next statement after block 1 statements block
True Can go with several elif, elif... and only one
True and False constants ☝ configure editor to insert 4 spaces in if age<=18:
False final else. Only the block of first true
place of an indentation tab. state="Kid"
condition is executed. elif age>65:
☝ floating numbers… approximated values Maths
angles in radians ☝ with a var x: state="Retired"
if bool(x)==True: ⇔ if x: else:
Operators: + - * / // % ** from math import sin,pi… state="Active"
if bool(x)==False: ⇔ if not x:
Priority (…) × ÷ ab sin(pi/4)→0.707…
integer ÷ ÷ remainder cos(2*pi/3)→-0.4999… Exceptions on Errors
Signaling an error:
@ → matrix × python3.5+numpy sqrt(81)→9.0 √ raise ExcClass(…) error
(1+5.3)*2→12.6 log(e**2)→2.0 Errors processing: normal processing
abs(-3.2)→3.2 ceil(12.5)→13 try: raise X() errorraise
processing processing
round(3.57,1)→3.6 floor(12.5)→12 normal procesising block
pow(4,3)→64.0 modules math, statistics, random, except Exception as e: ☝ finally block for final processing
☝ usual order of operations decimal, fractions, numpy, etc. (cf. doc) error processing block in all cases.

You might also like