{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Built-In Functions and Methods\n",
"\n",
"Built-in functions are, as the name implies, already a part of the Python library. These are functions that are so commonly used that you just need to *call* them in order to use them yourself! We have already seen a few examples of built-in functions including ```print()``` and ```type()```. There are some mathematical built-in functions, for example we can find the maximum or minimum of given numbers, or the absolute value of a single number. We can even round floating point numbers to a specified decimal. Additionally, there are functions that give us general information about the input, such as the length of a string or the type of the input object.\n",
"\n",
"To call a built-in function, we use the function name with parentheses around the function input. For example the function name for maximum is ```max()``` and calling this function takes the format below.\n",
"\n",
"```python\n",
"\n",
"max(...)\n",
"```\n",
"Functions take arguments as input, and if we are unsure what arguments a function accepts, there's a built-in function for that! The ```help()``` function. This function accepts a function as input and outputs the key characterics, namely what it takes as input and what it outputs. Calling the ```help``` function on ```max```, we see we can enter two or more arguments and we expect the largest argument to be returned. We can alternately enter an iterable argument, like a sequence, dicussed in detail in [Chapter 4: Data Structures](../../../04/DataStructures.ipynb)."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on built-in function max in module builtins:\n",
"\n",
"max(...)\n",
" max(iterable, *[, default=obj, key=func]) -> value\n",
" max(arg1, arg2, *args, *[, key=func]) -> value\n",
" \n",
" With a single iterable argument, return its biggest item. The\n",
" default keyword-only argument specifies an object to return if\n",
" the provided iterable is empty.\n",
" With two or more arguments, return the largest argument.\n",
"\n"
]
}
],
"source": [
"help(max)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So we can call the ```max``` function with multiple arguments and it returns the max. Below, we call the max function with three arguments and the largest value is returned."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4.1"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"max(2, 4.1, -3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Below is a short list of common built-in functions. For a more complete list see the Python documentation here: \n",
"[Built-in Function Documentation](https://docs.python.org/3/library/functions.html)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| Built-in Python Functions | Description |\n",
"| ----------- | ----------- |\n",
"| max(...) | Maximum function: Returns the maximum of the given inputs. |\n",
"| min(...) | Minimum function: Returns the maximum of the given inputs. |\n",
"| sum(...) | Sum function: Returns the sum of a given iterable. |\n",
"| abs(...) | Absolute value function: Returns the absolute value of the given input. |\n",
"| round(...) | Rounding function: Returns the rounded input. |\n",
"| len(...) | Length function: Returns the length of given input. |\n",
"| type(...) | Data Type function: Returns the datatype of the input. |\n",
"| print(...) | Print function: Prints the input|"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Libraries"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are a lot of functions and tools that are not contained directly in Python. If we want to access more specific functions or if we want to manipulate particular objects, we may have to import a library or a module. A **module** is a collection of functions and code that are related in some way, while a **library** is a collection of modules that are helpful in performing tasks. While there is a distinction, we will use library throughout this textbook to encompass both. \n",
"\n",
"For example, there are numerous mathematical functions that are not built-in to Python, but are still important and common. We can gain access to them by importing the math library. This gives us access to the exponential, logarithmic, square root, and even floor and ceiling functions, in addition to storing the number pi or computing factorials. Hence we can think of these functions as being built-in to their respective libraries.\n",
"\n",
"We will see later that we can import a library, `matplotlib`, to assist with graphing or visualing data, or the `numpy` library which allows us access to different types of objects and their manipulation. Throughout this textbook, we will import libraries as needed."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Math Library"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To access the functions built in to the math library, we first import the library by running the line below."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"import math"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since these functions are coming from the math library, to call them we use \n",
"```python \n",
"math.name_of_function\n",
"```\n",
"\n",
"For example, suppose we want to compute log(5). Using the math library, we write the following line."
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1.6094379124341003"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"math.log(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To check the key aspects of the function, we can again use the help function to view the documentation regarding \n",
"```python \n",
"math.log(...)\n",
"```\n",
"Note, to ensure the input to the help function is itself a function, we do not input an argument for log."
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on built-in function log in module math:\n",
"\n",
"log(...)\n",
" log(x, [base=math.e])\n",
" Return the logarithm of x to the given base.\n",
" \n",
" If the base not specified, returns the natural logarithm (base e) of x.\n",
"\n"
]
}
],
"source": [
"help(math.log)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Did the log function do as we intended? Well, based on the documentation, if we do not specifiy the base, \n",
"```python\n",
"math.log(5)\n",
"```\n",
"is the natural logarithm, $\\ln(5)$. Typing $\\log(5)$ on your calculator assumes base 10, which we can mimic by specifing the argument for the base for the optional argument of the math.log function."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.6989700043360187"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"math.log(5, 10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So it is important to know the default values for these built-in functions! \n",
"\n",
"A few of the more common math functions are included below; for a complete list see the documentation here \n",
"[Built-in Math Function Documentation](https://docs.python.org/3/library/math.html)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| Built-in Math Functions | Description |\n",
"| ----------- | ----------- |\n",
"| math.log(...) | Returns log of input. If no base is specified uses base $e$. |\n",
"| math.exp(...) | Returns $e$ to the power of the input. |\n",
"| math.sqrt(...) | Returns the square root of the input. |\n",
"| math.floor(...) | Returns the floor of the input. |\n",
"| math.ceil(...) | Returns the ceiling of the input. |\n",
"| math.factorial(...) | Returns the factorial of the input.|\n",
"| math.pi | Returns pi. |\n",
"| math.e | Returns $e$. |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since the output of these math functions are in fact numbers, we can manipulate them however we want!"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"63.1415926535898"
]
},
"execution_count": 66,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"math.factorial(6)/math.floor(12.9879) + math.pi"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Methods\n",
"\n",
"Methods are similar to functions in that they provide an output based on some input. However, a major difference is that methods are built on specific *objects* and can easily modify the original input *object*. The format for a method is\n",
"```python \n",
"object.method()\n",
"```\n",
"where *method* performs some action on *object*. Objects can be datatypes like strings, or more complicated data structures.\n",
"As we previously saw, we can define the string *candy* and use the ```.replace()``` method to modify the original string object."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'candy is my favorite treat. my favorite candy is LICORICE.'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"candy = \"candy is my favorite treat. my favorite candy is BUBBLE GUM.\"\n",
"candy.replace(\"BUBBLE GUM\", \"LICORICE\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And there are many methods made for string datatypes. Some common string methods are seen in the table below.\n",
"\n",
"| Built-in Methods on Strings | Description |\n",
"| ----------- | ----------- |\n",
"| string.replace('old', 'new') | Replaces any 'old' elements with 'new' in the given string |\n",
"| string.upper() | Returns an uppercase version of the given string |\n",
"| string.lower() | Returns a lowercase version of the given string |\n",
"| string.strip() | Returns the given string with additional spaces at beginning or end removed |\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will see methods acting on different objects throughout this book as we delve deeper into the structure of Python.\n",
"\n",
"Note all of the tools used in this section are built-in to various libraries or directly within Python. If we want to repeat our own process or perform an action and we cannot find a premade function, we also have the option to create our own functions! "
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.12"
},
"vscode": {
"interpreter": {
"hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}