Methods belong to objects
You have already called many functions that come after an object and a dot: words.append("hi"), line.split(","), prices.values(). These are methods: functions that belong to an object and work on that object. You write the object first, then a dot, then the method's name with its arguments in parentheses.
Compare a method with an ordinary function. len(motto) is a function: the object goes inside the parentheses. motto.count("s") calls a method of the string motto: it works on the string before the dot.
motto = "Practice makes progress"
print(len(motto))
print(motto.upper())
print(motto.count("s"))
print(motto.find("makes"))
print(motto.find("perfect"))
23
PRACTICE MAKES PROGRESS
3
9
-1find gives the index where the text starts, or -1 when it isn't there at all. A method works on any string, a literal one too: "ready, steady, go".count("y") is 2.
Each type has its own methods: upper and find belong to strings, append and sort to lists, values and items to dictionaries. Calling a method that the object's type doesn't have stops the program:
numbers = [3, 1, 2]
print(numbers.upper())
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(numbers.upper())
^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'upper'An AttributeError means the object has nothing by that name: a list has no upper.
Methods that return, methods that change
Strings are immutable, so a string method never changes the string. It returns a new string, and the result is lost unless you store it:
code = "abc-123"
code.upper()
print(code)
code = code.upper()
print(code)
abc-123
ABC-123Lists are mutable, and many list methods change the list itself. Most of them return None, so don't assign their result:
queue = ["Ann", "Bo"]
queue.append("Cy")
first = queue.pop(0)
print(first)
print(queue)
numbers = [3, 1, 2]
numbers = numbers.sort()
print(numbers)
Ann
['Bo', 'Cy']
Nonepop(0) both changes the list and returns the item it took out. sort only changes the list and returns None, so the last assignment threw the sorted list away. Write just numbers.sort() on its own line.
Dictionary methods work the same way. values() gives the values of the dictionary it is called on:
stock = {"apples": 4, "pears": 0, "plums": 7}
total = 0
for amount in stock.values():
total += amount
print(total)
11A method on a method's result
A method's result is an object too, so you can call a method on it straight away. Python works from left to right:
answer = " YES please "
print(answer.strip().lower())
print(answer.lower().count("e"))
yes please
3answer.strip() returns a new string without the spaces around it, and .lower() is called on that new string.