REFERENCE SHEET - PYTHON - ONLY THE BASICS
GENERAL CUT BY TYPES OF SEQUENCE † [Link] - iterates over the elements of a
Distinguish between uppercase and lowercase. The index begins Types of sequences: 'str', 'array', 'tuple', 'list', etc. sequence in reverse order.
from 0. Spaces or tabs for code blocks. list1[start:stop]
Notation [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
HELP list1[start:stop:step] # §
reversed() returns the iterator, list() converts it into
Take every 2 elements list1[::2]
Help home page help() a list.
Invert a string str1[::-1]
Function help help([Link])
CONTROL AND FLOW
Module help help(re) 'start' and 'stop' are optional; Include the
index 'start', but 'stop' NO. 1. Operators for conditions in 'if else':
MODULE (OR LIBRARY) DICTIONARIES (HASH MAP) Check if two variables are
var1 is var2
the same object
It's just a file with a .py extension Create dict1 ={'clave1' :'valor1',2 :[3, 2]}
List module content dir(module1)
... are different objects var1 is not var2
Create sequence dict(zip(keyList, valueList)) Check if two variables
Load a module import module1 #* var1 == var2
Obtain, Set or dict1['key1'] #* they have the same value
Call module function module1.function1() dict1['clave1'] = 'newValue'
Insert element
create a new namespace and execute all the Obtain with value def [Link]('key1', defVal) WARNING: Use the operators 'and', 'or', 'not'
statements in the associated .py file within that space Check existence 'key1' in dict1
for composite conditions, no &&, ||, !.
names. If you want to load the module content into the space Remove element delete dict1['key1']
of current names, use 'from module1 import *' 2. Common use of the operator 'for':
Get list of keys [Link]() #***
Iterating over a
TYPES OF SCALARS Get list of values [Link]() collection (list or tuple) or for element in iterator:
[Link](dict2) an iterator
Check the data type: type(variable) Update values values from dict2 to dict1 If the elements are
sequences, they can be for a, b, c in iterator:
SIX COMMONLY USED DATA TYPES KeyError exception if the key does not exist. unpack
[Link]/long*- Large int is converted to long 'get()' by default (without 'defaultValue') will return 'pass' - declaration of no operation. It
[Link]* - 64 bits, there is no 'double' type 'None' if the key does not exist. use in areas where there are no actions.
[Link]*- True or False Return the lists of keys and values in the same
order. The order is not a particular order, it is very
4. Ternary expression - non-bulky 'if else'
[Link]*- ASCII value in 2.x and Unicode in 3 it is likely that it is not ordered.
v=true-expr if condition else false-expr
• Single / double / triple quotes Valid dictionary key types 5. Use if/elif instead of switch/case.
• It is treated like other sequences • Keys must be immutable like types. OBJECT-ORIENTED PROGRAMMING
• Special character with or preface with r scalars (int, float, string) or tuples (all the 'object' is the root of all types
this\f?ff objects in the tuple must also be
2. All (number, string, function, class,
• Formatting in various ways immutable
• The technical term here is 'hashability'. module, etc.) is an object, each object
template = '%.2f %s haha $%d' check if an object is hashable with the it has a 'type'. The object variable is a
str1 = template % (4.88, 'hello', 2) hash ('string'), hash ([1, 2]); this would fail. pointer to its location in memory.
str(), bool(), int() and float() are also functions of SETS 3. Objects are counted by reference.
explicit type conversion. Collection of disordered UNIQUE elements. [Link](5) => x
a = 5, b = a # Creates a 'reference' to
5. NoneType(None) - 'null' value (ONLY exists They are like dictionaries but only with keys. obj right of =, => a and b point to 5
an instance of the None object Create set([3, 6, 3]) {3, 6, 3} [Link](5) => x + 2
• Noneno is a reserved keyword, Check if it is a subset set1 is a subset of set2
del(a); [Link](5) => x + 1
Check if it is a superset set1 is a superset of set2
it is a unique instance of 'NoneType' Check if it is the same content set1 == set2
[Link] –basic form:
• None is a default value for class MyObject(object):
Union (or) set1 | set2 'self' is 'this' from Java/C++
arguments of optional functions: Intersection (and) set1 & set2 def __init__(self, name):
def func1(a, b, c = None) Difference set1 - set2 [Link] = name
def memberFunc1(self, arg1):
• Common use of None: Symmetric difference (xor) set1 ^ set2
..
@staticmethod
if variable is None:
FUNCTIONS def classFunc2(arg1):
[Link] - integrated model 'date and time' Function arguments are passed by reference. ..
provides the types 'datetime', 'date', 'time'. obj1 = MiObjecto('name1')
• Basic form obj1.memberFunc1('a')
•'datetime' combina 'date' y 'time' def func1(posArg1, keywordArg1 = 1, ...): MiObject.classFunc2('b')
Create obj dt1=[Link]('20200722', '%Y%m%d') 5. Useful interactive tool:
Get the obj [Link]() [Link]() NOTE: The keyword arguments MUST
dir(var1) #Lists all the methods of the obj.
datetime to string [Link]('%m/%d/%Y %H:%M') follow positional arguments; it is NOT 'evaluation'
Change vale dt2 = [Link](minute=0, second=30) lazy", the expressions are evaluated immediately.
COMMON CHAIN OPERATIONS
Obtain diff. diff=dt1-dt2 # '[Link]' • Function call mechanism:
List / tuple concatenated with v1,v2,v3
Note: Most objects are mutable, except strings and tuples. 1. The functions are local to the scope of the separator v1, v2, v3
module level. Formatting My name is {0} {name}
DATA STRUCTURES ns1=[Link]('Martin',nombre='Nelbren')
Internally, the arguments are packaged of chain
NOTE: All function calls that are not Get, e.g.: Divide sl1=[Link](' ') #=> ['Mi', 'nombre',... ]
[Link]() is an in-place operation (without creating a new one) in a tuple and dict, the function receives a tuple the name
Obtain substring
object) unless otherwise indicated. 'args' and dict 'kwargs' are unpacked. month = '5'
String padding with zeros
TUPLES • Common use of 'Functions are objects': [Link](2) => '05'
def func1(ops=[[Link], user_def_func, ..], ..):
Fixed-length one-dimensional sequence e for function in ops: EXCEPTION HANDLING
immutable objects of ANY type. value = function(value)
Basic form
Create tup1 = 4,5,6 tup2 = (6, 7, 8)
RETURN VALUES try:
Create nested tup1 = (4, 5, 6), (7, 8)
It returns none if the end of the function is reached.
..
except ValueError as e:
Convert sequence/iterator to tuple [1, 0, 2]
without a return statement. print e
Concatenate tup1 + tup2 except (TypeError, AnotherError):
Multiple values return as a tuple object. ..
Unpack a, b, c = tup
except
return (value1, value2)
Intercambiar variables b, a = a, b ..
value1, value2 = func1(..) finally:
LISTS ..
ANONYMOUS (LAMBDA) 2. Manually throw the exception
One-dimensional sequence of variable length,
mutable (modifiable) of objects of ANY type. Function that consists of a single statement. raise AssertionError # Assertion error
raise SystemExit # request program exit
Create list1=[1,'a',3] list2 = list(tup1)
lambda x : x * 2 # def func1(x):return x * 2 raise RuntimeError('Error message: ..')
Concatenate list1 + list2 list1 extends list2 Application of lambda functions: 'currying', also
known as deriving new functions from the LIST COMPREHENSIONS, SETS, AND DICTIONARIES
Add to the end of the list [Link]('b')
Insert at position [Link](posIdx, 'b') #**
existing through the application of partial args. Syntactic for code to be easier to read and write
Inverse insert valueAtIdx = [Link](posIdx) ma60 = lambda x : pd.rolling_mean(x, 60) 1. List Comprehensions
• Concise a new list by filtering the
Remove the first value from the list [Link]('a') USEFUL FUNCTIONS FOR DATA STRUCTURES elements of a collection and transforming them
Check existence 3 in list1 => True #***
1. Enumerate - returns a sequence (i, value) elements that pass the filter in a concise expression.
Order [Link]() of tuples where i is the index of the current element. [expr for val in collection if condition]
Sort with the function [Link](key = len) A shortcut of:
of user sort by len for i, value in enumerate(collection):