4.2 Defining Functions
You’ve called many built-in functions (int
, float
, print
, input
, type
, sum
, len
, min
and max
) and a few functions from the statistics module (mean
, median
and mode
). Each performed a single, well-defined task. You’ll often define and call custom functions. The following session defines a square
function that calculates the square of its argument. Then it calls the function twice—once to square the int
value 7
(producing the int
value 49
) and once to square the float
value 2.5
(producing the float
value 6.25
):
In [1]: def square(number):
...: """Calculate the square of number."""
...: return number ** 2
...:
In [2]: square(7)
Out[2]: 49
In [3]: square(2.5)
Out[3]: 6.25
The statements defining the function in the first ...
Get Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and The Cloud now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.