You are on page 1of 4

GENERALIDADES python is case-sensitive by default it copies only variable values, not references VARIABLES a = valor es posible asignar diferentes

tipos a una misma variable this is called "dynamic typing" OBJETOS dir(objeto) //returns list of all the properties and methods of the object TIPOS type(variable o valor) //devuelve el tipo NUMEROS float(#) makes it floating number 1/2 es 0 CADENAS string: 'asfsdfs' cadenas largas: """ string ... """ string.upper() string.lower() .isalpha() //checks only letters are contained .count('substring') string comparison == len(string) devuelve el # de caracteres concatenar strings: STRING1+STRING2 multiplicar string por numero> string*# 'subcadena' in 'stringABuscarLaSubcadena' return True/False segun se contenga o no la subcadena stringName[indice] //index starts with zero, valen too negativos index slices: stringName[InitialIndex:FinalIndexNotIncluded] if initialIndex is zero then it can be omitted if finalIndex is len(string) it can be omitted count(stringAAnalizar,stringBuscado) devuelve el # de veces q se halla secuencia buscada replace(string,'patronARemplazar','patronNuevo') retorna el string nuevo con valores remplazados find(string, subpatron) devuelve el index de inicio del subpatron primero hallad o formatting strings % ESCAPE VALUE

print "%.3f " % gc ie print formatoENTREDOBLESCOMILLAS % (var1,var2,var3...) %% es % porcentaje % es el escape value f,E,e floating d,i decimal or long integer o,x octal/hexadecimal s string or object with str() method r use the repr() function of the object % literal % name in parentheses selects the key name in a mapping object "%(num)d %(str)s" % { num :1, str : dna } -,+ left,right alignment 0 fills with zero the expression . represents the precision UNICODE ord('a') returns 97 chr(97) returns 'a' Literal stringName = u'string containing strange chars' FUNCTIONS def functionName (): //steps, remember indentation calling a function functionName(par1, par2, ...) print string1, string 2, string 3,... LISTS lista =[ obj1 ,obj2,...] accessed by indexes lista[2] concatenating lists + lista1 + lista2 adds both lists range(inicio, fin, step) //lista de naturales help(functionName) variable= raw_input("Enter value ...") CONDITIONALS if condition_without_parentheses : indentadas sentencias else :

indentadas sentencias besides we have: if condition: statements elif condition: statements else: statements ITERATIONS for arbitraryNameItem in list: sentencias TRY try: statements to try except <optionalErrorType>: bad escenario statements to do else: if no error in try segment RAISING EXCEPTIONS raise Exception; WHILE LOOPS while condition: statements OPERATORS +,-,*,/ x <<y ,x>>y bit shifting x & y bitwise and x!y bitwise or == equality of value IS equality of object reference CASTING TYPES typeName(variable) eg int("4555") also int (numberString, base) long() float() complex(real,imag) str() repr() eval() tuple() list() chr()

unichr() ord() hex() oct() READING FROM A FILE first open pointer f= open("filename") //the file here is a collection of lines for line in f: //sentences f.close() //closes the pointer other methods open(filename,'w') //to write write("string") COLLECTIONS mutable unlike strings Lists mutable ordered collections Via indexes [,,,...] Dictionaries mutable unordered collections Via keys {key1:val1,key2:val2,...} both list-or-dictionary[index-or-key] returns object lists can be sliced list[i:j] dictionary.has_key(key) returns True/False del element //for both id(object) //returns unique index MAP function map(functionToApplyName, collection) //return list of results of applying the function to each collection item LIST COMPREHENSIONS [expresion for var in [list] if condition-to-filter] //returns new list where ea ch var is evaluated for the expression

You might also like