3.5 Built-In Functions and Methods

3.5.1 Functions

A function is a block of code that performs a task. Python comes with a substantial set of pre-written functions.

To use a function, type the function’s name, followed by parentheses. Usually, a function will operate on some data. Specify the data that you want to input to your function within the parentheses. Each item within the parentheses is called an argument.

For example, the print() function prints its argument to screen:

print('howdy')
## howdy

Note that we can also pass in a variable name as an argument:

myString = "yeehaw"
print(myString)
## yeehaw

Throughout the course, we will learn about many of the functions that are a part of the Python language. For now, also note the type() function. This function takes any object as an argument and returns the data type of your object.

myObject = 5**3/7
print(type(myObject))
## <class 'float'>

3.5.2 Methods

Every data type that we use in Python (strings, integers, etc.) is associated with a set of functions unique to the data type. These functions are called methods.

The syntax for using a method is:

<objectName>.<methodName>()

3.5.2.1 Example

The string method .upper() is used to convert a string into uppercase letters. We can use it either directly on the string itself:

"peppa".upper()
## 'PEPPA'

or by operating on a variable:

pig = "peppa"
pig.upper()
## 'PEPPA'

3.5.2.2 Modifying objects

Using a method may or not modify the object you run it on. For example, the .upper() method shows you the uppercase version of a string but does not modify the actual object that you are operating on. Observe the following code block:

pig = "peppa"
pig.upper()
print(pig)
## peppa

pig has not been updated. To actually save the result of .upper(), we have to assign it to a variable:

pig_caps = pig.upper()
print(pig_caps)
## PEPPA

Some methods do modify underlying variables. For example, the list .append() method (which we will learn about later) does change the list if operates on:

myList = []
print(myList)
## []
myList.append('apple')
print(myList)
## ['apple']

myList is altered by myList.append('apple'). There’s no need to type something like myList = myList.append('apple') - this would in fact be an error. Whether methods modify the objects they operate on is something you’ll have to keep track of on a case-by-case basis as you learn new methods.