Files
misc/python/atms-310/notebooks/Week 02 W.ipynb
2025-07-02 00:07:49 -07:00

428 lines
11 KiB
Plaintext
Executable File

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h1>3. Functions and Logic</h1>\n",
"<h2>10/04/23</h2>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2>3.0 Last Time...</h2>\n",
"\n",
"<ul>\n",
" <li>A list is a <b>mutable</b>, <b>ordered</b> sequence of elements.</li>\n",
" <li>Python counts starting with 0, not 1.</li>\n",
" <li>You can also count backwards from the end of a list using negative numbers.</li>\n",
" <li>A list can be sliced, where the slice is defined by a range that has an inclusive lower bound and an exclusive upper bound.</li>\n",
" <li>Values in a list can be changed by assignment or by particular methods.</li>\n",
" <li>A tuple is an <b>immutable</b>, <b>ordered</b> sequence of elements.</li>\n",
" <li>A dictionary is a <b>mutable</b>, <b>unordered</b> sequence of elements consisting of key:value pairs.</li>\n",
"</ul>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2>3.1 Functions</h2>\n",
"\n",
"A <b>function</b> is a self-contained block of code that can be \"called\" in any other code. It can take user-specified input and return output (which is generally a single output value: you can put multiple outputs into a list).\n",
"\n",
"To create a function, we start with a <b>def</b> statement that defines the name of the function and then follows with a list of input arguments in parentheses, followed by a colon.\n",
"\n",
"All the code that you want to be executed within a function should be indented (by default, this is typically indented by four spaces). The amount of whitespace before a command in Python matters! Everything indented together will be run together; there's no need to specify the end of the function."
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [],
"source": [
"# You can start by defining a function that calculates the surface area\n",
"# of a cylinder. \n",
"# This can go in its own file so that you can refer to it in the future\n",
"# from any code you may want to run.\n",
"def area(radius, height):\n",
" a = 2*3.14*radius**2 + 2*3.14*radius*height\n",
" return a\n",
"\n",
"\n",
"# Basically, this function is called 'area' and takes as input two variables\n",
"# called 'radius' and 'height' from the user. \n",
"# It calculates the surface area of a cylinder, then outputs or 'returns' \n",
"# that area to the original code.\n",
"\n",
"# Running this block of code now will output nothing; you've just defined\n",
"# the function."
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"94.2\n"
]
}
],
"source": [
"# Now, try calling the function using a radius of 3 and a height of 2.\n",
"print(area(3,2))"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"94.2\n"
]
}
],
"source": [
"# An even shorter version of that function would be:\n",
"def area(radius, height):\n",
" return 2*3.14*radius**2 + 2*3.14*radius*height\n",
"\n",
"print(area(3,2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The arguments in this example ('radius' and 'height') are what's known as <b>positional arguments</b>, meaning that it knows the first argument corresponds to the radius and the second argument corresponds to the height.\n",
"\n",
"Alternatively, you can use what are known as <b>keyword arguments</b>."
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"94.2\n"
]
}
],
"source": [
"# Can write the arguments out of order if we're using keywords!\n",
"print(area(height=2, radius=3))"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"62.8\n"
]
}
],
"source": [
"# Note that this doesn't work with positional arguments:\n",
"print(area(2,3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can facilitate long lists of arguments by treating positional arguments like lists and treating keyword arguments like dictionaries. To do this, in the function call, you just need to place an asterisk (\\*) before the list with positional arguments and two asterisks (\\*\\*) before the list with keyword arguments."
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"94.2\n"
]
}
],
"source": [
"# Call the function using a list of positional arguments.\n",
"positional = [3,2] # plugging values from the list \"positional\" into area function\n",
"print(area(*positional))"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"94.2\n"
]
}
],
"source": [
"# Call the function using a dictionary of keyword arguments.\n",
"\n",
"keyword = {'height':2, 'radius':3}\n",
"print(area(**keyword))"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"94.2\n"
]
}
],
"source": [
"# Call the function using a combo of positional and keyword arguments.\n",
"positional = [3]\n",
"keyword = {'height':2}\n",
"print(area(*positional,**keyword))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This seems like a silly way of going about it, but if you're passing dozens or hundreds of variables to a particular function, it definitely makes life easier!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2>3.2 Logical Constructs</h2>\n",
"\n",
"Logic in Python is handled through <b>if statements</b>. The general idea behind an if statement is that we check whether something is true: if it is, we then execute certain code before continuing.\n",
"\n",
"If statements are formatted by writing <b>if</b> and then some condition that must be met, followed by a colon. The block of code we wish to execute if the statement is true must all be indented together."
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ass\n",
"booty\n"
]
}
],
"source": [
"# Write a code that checks whether a given variable is equal to 3.\n",
"a = 3\n",
"if a == 3:\n",
" print('ass')\n",
"print('booty')"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [],
"source": [
"# If the condition is not true, the code ignores what's indented.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also specify what will be done if your conditional statement is not true by using <b>else:</b>."
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hell no\n",
"buttocks\n"
]
}
],
"source": [
"# Now, if the condition is not true, the code continues with what follows\n",
"# the else statement.\n",
"a = 2\n",
"if a == 3:\n",
" print('yes!')\n",
"else:\n",
" print('hell no')\n",
"\n",
"print('buttocks')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Want to deal with more than one scenario? Use <b>elif</b>, which is short for <b>else if:</b>. In other words, if the previous condition is not true, but this new condition is true, do this instead."
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"its 3\n",
"end\n"
]
}
],
"source": [
"a = 3\n",
"if a == 3:\n",
" print('its 3')\n",
"elif a == 2:\n",
" print('its 2')\n",
"else: print('it aint 2 or 3')\n",
"\n",
"print('end')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pay close attention to the indentation in the above code!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<b>An example!</b>\n",
"\n",
"Write an if/elif/else statement in the box below to check whether a particular variable is positive, negative, or equal to zero. Each possibility should print a string statement: \"I am positive.\", \"I am negative.\", or \"I am zero.\"\n",
"\n",
"Try testing it with different values to make sure it works!\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"its negative\n",
"end\n"
]
}
],
"source": [
"d = input('enter a number')\n",
"f = int(d)\n",
"if f == 0:\n",
" print('its zero')\n",
"elif f < 0:\n",
" print('its negative')\n",
"elif f > 0:\n",
" print('its positive')\n",
"print('end')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2>TAKE-HOME POINTS</h2>\n",
"\n",
"<ul>\n",
" <li>A <b>function</b> is a block of code that can be called.</li>\n",
" <li>Functions can be called using either positional or keyword arguments.</li>\n",
" <li>Positional arguments can be described via lists and keyword arguments can be described via dictionaries.</li>\n",
" <li>Python uses if statements for logical constructs.</li>\n",
" <li>The code within an <b>if</b> statement is run if the current statement is true.</li>\n",
" <li>The code within an <b>elif</b> statement applies if prior statements are not true <b>and</b> the current statement is true.</li>\n",
" <li>The code within an <b>else</b> statement applies if all prior statements are not true.</li>\n",
"</ul>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}