3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 00:54:21) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] Python Type "help", "copyright", "credits" or "license" for more information. # Something familiar: w1 = 'words' # What is w1? # It is the name of a variable that refers to an object. # The object has a type and it has contents. # We can see the type: type(w1) # And get help on it: help(str) Help on class str in module builtins: # (Lots of help information omitted.) # When we want to do something with an object, we usually call a method on it. w1.index('s') 4 w1 'words' w1.islower() True w1.replace('d', 'dsmith') 'wordsmiths' w1 'words' # w1 is unchanged! The replace method doesn't change the string, # it returns a new string. In fact, method replace couldn't change w1 even if # it wanted to because strings are immutable. # We can also use operators to do things to with object: 'Happy' + 'New' + 'Year' 'HappyNewYear' w1[4] 's' w1[0] 'w' # Let's make some more strings. w2 = 'swords' w3 = w2[1:] w1 'words' w2 'swords' w3 'words' w1 == w2 False w2 'swords' # At this point, we might say that "w1 and w3 are the same." # Python gives us two ways to ask whether they are the same. w1 == w3 True w1 is w3 False # Huh? # This actually makes perfect sense: # Double equals checks whether they have the same value, # but "is" checks whether they are the same object. # It was sloppy to say that "w1 and w3 are the same". # More precise would be to say that "w1 and w3 each reference # a string object with the value 'words'." # Or to spell it out even further, "w1 references a string # object with the value 'words' and so does w3, but they are # two different string objects." # In addition to str, # there are many other useful types of object already defined in Python, # including list and dictionary. names = ['Danny', 'Catherine', 'Tom'] colleges = {'Danny': 'Vic', 'Tom':'Innis'} # In fact, every value in Python is an object, including # simple things like integers and booleans. n = 3 type(n) # Even though we normally use operators with ints ... n + 15 18 # ... we can actually call methods on them # (which is a clear sign that they are objects): n.__ceil__() 3 n.__lt__(2) False n.__add__(14) 17 n + 14 17