# Converting real to integer print 'int(3.14) =', int(3.14) # Converting integer to real print 'float(5) =', float(5) # Calculation between integer and real results in real print '5.0 / 2 + 3 = ', 5.0 / 2 + 3 # Integers in other base print "int('20', 8) =", int('20', 8) # base 8 print "int('20', 16) =", int('20', 16) # base 16 # Operations with complex numbers c = 3 + 4j print 'c =', c print 'Real Part:', c.real print 'Imaginary Part:', c.imag print 'Conjugate:', c.conjugate() s = 'Camel' # Concatenation print 'The ' + s + ' ran away!' # Interpolation print 'Size of %s => %d' % (s, len(s)) # String processed as a sequence for ch in s: print ch # Strings are objects if s.startswith('C'): print s.upper() # what will happen? print 3 * s # 3 * s is consistent with s + s + s # Zeros left print 'Now is %02d:%02d.' % (16, 30) # Real (The number after the decimal point specifies how many decimal digits ) print 'Percent: %.1f%%, Exponencial:%.2e' % (5.333, 0.00314) # Octal and hexadecimal print 'Decimal: %d, Octal: %o, Hexadecimal: %x' % (10, 10, 10) musicians = [('Page', 'guitarist', 'Led Zeppelin'), ('Fripp', 'guitarist', 'King Crimson')] # Parameters are identified by order msg = '{0} is {1} of {2}' for name, function, band in musicians: print(msg.format(name, function, band)) # Parameters are identified by name msg = '{greeting}, it is {hour:02d}:{minute:02d}' print msg.format(greeting='Good Morning', hour=7, minute=30) # Builtin function format() print 'Pi =', format(3.14159, '.3e') print 'Python'[::-1] # shows: nohtyP import string # the alphabet a = string.ascii_letters # Shifting left the alphabet b = a[1:] + a[0] # The function maketrans() creates a translation table # from the characters of both strings it received as parameters. # The characters not present in the table will be # copied to the output. tab = string.maketrans(a, b) # The message... msg = '''This text will be translated.. It will become very strange. ''' # The function translate() uses the translation table # created by maketrans() to translate the string print string.translate(msg, tab) import string # Creates a template string st = string.Template('$warning occurred in $when') # Fills the model with a dictionary s = st.substitute({'warning': 'Lack of electricity', 'when': 'April 3, 2002'}) # Shows: # Lack of electricity occurred in April 3, 2002 print s import UserString s = UserString.MutableString('Python') s[0] = 'p' print s # shows "python" # Unicode String u = u'Hüsker Dü' # Convert to str s = u.encode('latin1') print s, '=>', type(s) # String str s = 'Hüsker Dü' u = s.decode('latin1') print repr(u), '=>', type(u) # a new list: 70s Brit Progs progs = ['Yes', 'Genesis', 'Pink Floyd', 'ELP'] # processing the entire list for prog in progs: print prog # Changing the last element progs[-1] = 'King Crimson' # Including progs.append('Camel') # Removing progs.remove('Pink Floyd') # Ordering progs.sort() # Inverting progs.reverse() # prints with number order for i, prog in enumerate(progs): print i + 1, '=>', prog # prints from de second item print progs[1:] my_list = ['A', 'B', 'C'] print 'list:', my_list # The empty list is evaluated as false while my_list: # In queues, the first item is the first to go out # pop(0) removes and returns the first item print 'Left', my_list.pop(0), ', remain', len(my_list) # More items on the list my_list += ['D', 'E', 'F'] print 'list:', my_list while my_list: # On stacks, the first item is the last to go out # pop() removes and retorns the last item print 'Left', my_list.pop(), ', remain', len(my_list) # Data sets s1 = set(range(3)) s2 = set(range(10, 7, -1)) s3 = set(range(2, 10, 2)) # Shows the data print 's1:', s1, '\ns2:', s2, '\ns3:', s3 # Union s1s2 = s1.union(s2) print 'Union of s1 and s2:', s1s2 # Difference print 'Difference with s3:', s1s2.difference(s3) # Intersectiono print 'Intersection with s3:', s1s2.intersection(s3) # Tests if a set includes the other if s1.issuperset([1, 2]): print 's1 includes 1 and 2' # Tests if there is no common elements if s1.isdisjoint(s2): print 's1 and s2 have no common elements' # Progs and their albums progs = {'Yes': ['Close To The Edge', 'Fragile'], 'Genesis': ['Foxtrot', 'The Nursery Crime'], 'ELP': ['Brain Salad Surgery']} # More progs progs['King Crimson'] = ['Red', 'Discipline'] # items() returns a list of # tuples with key and value for prog, albums in progs.items(): print prog, '=>', albums # If there is 'ELP', removes if progs.has_key('ELP'): del progs['ELP'] # Sparse Matrix implemented # with dictionary # Sparse Matrix is a structure # that only stores values that are # present in the matrix dim = 6, 12 mat = {} # Tuples are immutable # Each tuple represents # a position in the matrix mat[3, 7] = 3 mat[4, 6] = 5 mat[6, 3] = 7 mat[5, 4] = 6 mat[2, 9] = 4 mat[1, 0] = 9 for lin in range(dim[0]): for col in range(dim[1]): # Method get(key, value) # returns the key value # in dictionary or # if the key doesn't exists # returns the second argument print mat.get((lin, col), 0), print # Matrix in form of string matrix = '''0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0''' mat = {} # split the matrix in lines for row, line in enumerate(matrix.splitlines()): # Splits the line int cols for col, column in enumerate(line.split()): column = int(column) # Places the column in the result, # if it is differente from zero if column: mat[row, col] = column print mat # The counting starts with zero print 'Complete matrix size:', (row + 1) * (col + 1) print 'Sparse matrix size:', len(mat) print 0 and 3 # Shows 0 print 2 and 3 # Shows 3 print 0 or 3 # Shows 3 print 2 or 3 # Shows 2 print not 0 # Shows True print not 2 # Shows False print 2 in (2, 3) # Shows True print 2 is 3 # Shows False