What are functions and how can we use them?
Calling a function
Let's use a function that's built into Python: the built-in
If we type
sum and hit the
Enter key, we'll see what the variable
sum points to:
>>> numbers = [2, 1, 3, 4, 7, 11, 18]>>> sum<built-in function sum>
We're not actually using the function here, we're referring to the function object that the variable
sum points to.
To use this function, we need to put parentheses after it. Putting parenthesis after a function will call the function.
>>> sum()Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: sum() takes at least 1 positional argument (0 given)
When calling this function we got an error because the
sum function requires at least one argument but we didn't pass it any arguments.
To use the
sum function we have to pass it an iterable of numbers as an argument.
Arguments and return values
To pass an argument to a function, you put the argument inside the parentheses when calling the function.
Arguments are basically the inputs to a function.Functions have inputs( as arguments) and an output as a return value. The integer
46 is the return value of this function:
46 printed out at the Python REPL, but this
sum function didn't actually print 46, it returned 46.
If we put this function call on the right-hand side of an
= sign, we can assign the variable
total to whatever the return value of calling
numbers was (in this case, it was 46).
>>> total = sum(numbers)>>> total46
The default return value is
Not all functions have returned values.For example the
If we assign a variable to the return value of a
>>> name = print("Trey")Trey
We'll see text (
Trey) printed out, but we'll also see that the variable
>>> name>>> print(name)None
None is a special value that basically means this function doesn't have a return value.
In Python we typically assume that functions either perform some action or return something, but not both.The
sum function returns a value.
To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function).If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.
If that function has a return value, you can capture that return value into a variable or pass that return value straight into another function call.