Skip to content

Instantly share code, notes, and snippets.

@i-am-unknown-81514525
Last active October 23, 2023 20:56
Show Gist options
  • Save i-am-unknown-81514525/55a5f53f44276b4e813c3f8823f4c426 to your computer and use it in GitHub Desktop.
Save i-am-unknown-81514525/55a5f53f44276b4e813c3f8823f4c426 to your computer and use it in GitHub Desktop.
Python tutorial on functions: Jupyter Notebook
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"source": [
"# Basic Function\n",
"\n",
"A function is a block of code which only runs when it is called\n",
"\n",
"A (basic) python function is declared using the `def` keyword like so."
],
"metadata": {
"collapsed": false
},
"id": "b043aa3c79f63e97"
},
{
"cell_type": "code",
"execution_count": 423,
"outputs": [],
"source": [
"def function_1():\n",
" print(\"Hello World\")"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:36.963245900Z",
"start_time": "2023-10-10T20:51:36.429741100Z"
}
},
"id": "454ae1541e9509d"
},
{
"cell_type": "markdown",
"source": [
"This function will do absolutely nothing until you call it.\n",
"\n",
"To call a function, you will write the name of the function (func_name) and a pair of parenthesis. \n",
"\n",
"In this example, we would call our function with"
],
"metadata": {
"collapsed": false
},
"id": "ba8e9a702bc5c528"
},
{
"cell_type": "code",
"execution_count": 424,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello World\n"
]
}
],
"source": [
"func_name()"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:37.038245400Z",
"start_time": "2023-10-10T20:51:36.459245800Z"
}
},
"id": "676cea59c6fed11b"
},
{
"cell_type": "markdown",
"source": [
"This call would print \"Hello World\"\n",
"\n",
"Some functions have something called an argument.\n",
"\n",
"For instance, the following is telling the code to accept one argument\n"
],
"metadata": {
"collapsed": false
},
"id": "8ba6f336e64d387b"
},
{
"cell_type": "code",
"execution_count": 425,
"outputs": [],
"source": [
"def function_2(x): \n",
" print(x)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:37.063864100Z",
"start_time": "2023-10-10T20:51:36.473246600Z"
}
},
"id": "825f72dbf81aef7b"
},
{
"cell_type": "markdown",
"source": [
"When we call the function, we have to provide that argument. For instance, we could provide the function \"Test\" like so."
],
"metadata": {
"collapsed": false
},
"id": "6907957247754b2e"
},
{
"cell_type": "code",
"execution_count": 426,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Test\n"
]
}
],
"source": [
"function_2(\"Test\")"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:37.098551400Z",
"start_time": "2023-10-10T20:51:36.491244600Z"
}
},
"id": "5e833e7524c9a7d2"
},
{
"cell_type": "markdown",
"source": [
"You can also pass in multiple arguments to the function. This can be easily demonstrated through an example."
],
"metadata": {
"collapsed": false
},
"id": "b82ff0275366b52e"
},
{
"cell_type": "code",
"execution_count": 427,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"2\n",
"3\n"
]
}
],
"source": [
"def function_3(x,y,z):\n",
" print(x)\n",
" print(y)\n",
" print(z)\n",
" \n",
"function_3(1,2,3)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:37.196822800Z",
"start_time": "2023-10-10T20:51:36.513245100Z"
}
},
"id": "fc65f8192d4607c9"
},
{
"cell_type": "markdown",
"source": [
"You can also make a function return a value to the main script for further usage instead of printing it out, this make use of the `return` keyword to return the result so it can be retrieve."
],
"metadata": {
"collapsed": false
},
"id": "e36a64a559d5c611"
},
{
"cell_type": "code",
"execution_count": 428,
"outputs": [],
"source": [
"def add(x,y):\n",
" return x + y"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:37.755899800Z",
"start_time": "2023-10-10T20:51:36.537246900Z"
}
},
"id": "942f2257022cecf3"
},
{
"cell_type": "code",
"execution_count": 429,
"outputs": [
{
"data": {
"text/plain": "30"
},
"execution_count": 429,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x = 10\n",
"y = 20\n",
"add(x, y)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:37.836918600Z",
"start_time": "2023-10-10T20:51:37.055317900Z"
}
},
"id": "126769dfd91fea46"
},
{
"cell_type": "markdown",
"source": [
"**It is important to note that calling function here will not actually print when running in a python script. This behaviour only exists in REPL or Jypyter Notebook**"
],
"metadata": {
"collapsed": false
},
"id": "bf269a9958051a32"
},
{
"cell_type": "markdown",
"source": [
"Similar to how you can pass in multiple variable to the function, you can also return multiple variables:"
],
"metadata": {
"collapsed": false
},
"id": "ef4adaae094dce92"
},
{
"cell_type": "code",
"execution_count": 430,
"outputs": [],
"source": [
"def swap(x,y):\n",
" return y,x"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:37.836918600Z",
"start_time": "2023-10-10T20:51:37.304884Z"
}
},
"id": "70e0cde0a8c1494e"
},
{
"cell_type": "code",
"execution_count": 431,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Before swap: x=10, y=20\n",
"After swap: x=20, y=10\n"
]
}
],
"source": [
"x = 10\n",
"y = 20\n",
"print(f'Before swap: {x=}, {y=}')\n",
"x,y = swap(x,y)\n",
"print(f'After swap: {x=}, {y=}')"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:37.837900400Z",
"start_time": "2023-10-10T20:51:37.372517500Z"
}
},
"id": "1c1211f704ca9af4"
},
{
"cell_type": "markdown",
"source": [
"The function could also be completed in a simple way with `lambda`:"
],
"metadata": {
"collapsed": false
},
"id": "3e18ae21734ab600"
},
{
"cell_type": "code",
"execution_count": 432,
"outputs": [],
"source": [
"add_2 = lambda x,y: x+y"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:37.837900400Z",
"start_time": "2023-10-10T20:51:37.441687Z"
}
},
"id": "de15fa4599e7a500"
},
{
"cell_type": "code",
"execution_count": 433,
"outputs": [
{
"data": {
"text/plain": "30"
},
"execution_count": 433,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"add_2(10, 20)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:37.944207600Z",
"start_time": "2023-10-10T20:51:37.505689900Z"
}
},
"id": "78fa5d0cd6735a94"
},
{
"cell_type": "markdown",
"source": [
"You can also type hint the type of the input:"
],
"metadata": {
"collapsed": false
},
"id": "146ff7ae4b521788"
},
{
"cell_type": "markdown",
"source": [],
"metadata": {
"collapsed": false
},
"id": "c8f00d2a425da67e"
},
{
"cell_type": "code",
"execution_count": 434,
"outputs": [],
"source": [
"def add_3(x:int, y:int)->int:\n",
" return x+y"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.247632Z",
"start_time": "2023-10-10T20:51:37.723907500Z"
}
},
"id": "eff11e0a94551751"
},
{
"cell_type": "markdown",
"source": [
"This do not have direct affection on how you run the code and how it output, but it will be helpful for IDE and other program to understand the code."
],
"metadata": {
"collapsed": false
},
"id": "32c605ab104ab174"
},
{
"cell_type": "code",
"execution_count": 435,
"outputs": [
{
"data": {
"text/plain": "30"
},
"execution_count": 435,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"add_3(10,20)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.327611900Z",
"start_time": "2023-10-10T20:51:38.018206400Z"
}
},
"id": "5fe7770204c969d2"
},
{
"cell_type": "markdown",
"source": [
"# In depth:\n",
"From here, it will be overlap with other topic or even introduce on similar topic"
],
"metadata": {
"collapsed": false
},
"id": "407be2b4457686f9"
},
{
"cell_type": "markdown",
"source": [
"## In depth - Generic Function\n",
"If your function can accept different type on input to produce different type of output \n",
"**(New on Python 3.12)** **(It would return SyntaxError below Python3.12)**\n",
"Refer to [PEP 695](https://peps.python.org/pep-0695/)"
],
"metadata": {
"collapsed": false
},
"id": "f039b1b9b6328ac0"
},
{
"cell_type": "code",
"execution_count": 436,
"outputs": [
{
"ename": "SyntaxError",
"evalue": "expected '(' (4172095876.py, line 1)",
"output_type": "error",
"traceback": [
"\u001B[1;36m Cell \u001B[1;32mIn[436], line 1\u001B[1;36m\u001B[0m\n\u001B[1;33m def make_2_element_as_tuple[T](x:T, y:T)->tuple[T,T]:\u001B[0m\n\u001B[1;37m ^\u001B[0m\n\u001B[1;31mSyntaxError\u001B[0m\u001B[1;31m:\u001B[0m expected '('\n"
]
}
],
"source": [
"%%capture\n",
"def make_2_element_as_tuple[T](x:T, y:T)->tuple[T,T]:\n",
" return (x,y)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.361614700Z",
"start_time": "2023-10-10T20:51:38.071055500Z"
}
},
"id": "433765fd068f0b87"
},
{
"cell_type": "markdown",
"source": [
"This can be achieved below Python 3.12 through `typing` for same functionality but slightly more complicated:"
],
"metadata": {
"collapsed": false
},
"id": "1a76882b60433dc2"
},
{
"cell_type": "code",
"execution_count": 437,
"outputs": [],
"source": [
"from typing import TypeVar\n",
"_T = TypeVar('_T')\n",
"def make_2_element_as_tuple(x:_T, y:_T)->tuple[_T,_T]:\n",
" return (x,y)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.365611900Z",
"start_time": "2023-10-10T20:51:38.130399300Z"
}
},
"id": "9ac1c804e964fc20"
},
{
"cell_type": "markdown",
"source": [
"It could also accept different argument have different type by:"
],
"metadata": {
"collapsed": false
},
"id": "15368fe7bc2cc399"
},
{
"cell_type": "code",
"execution_count": 438,
"outputs": [
{
"ename": "SyntaxError",
"evalue": "expected '(' (1314718479.py, line 1)",
"output_type": "error",
"traceback": [
"\u001B[1;36m Cell \u001B[1;32mIn[438], line 1\u001B[1;36m\u001B[0m\n\u001B[1;33m def make_2_element_as_tuple_2[S,T](x:S, y:T)->tuple[S,T]:\u001B[0m\n\u001B[1;37m ^\u001B[0m\n\u001B[1;31mSyntaxError\u001B[0m\u001B[1;31m:\u001B[0m expected '('\n"
]
}
],
"source": [
"%%capture\n",
"def make_2_element_as_tuple_2[S,T](x:S, y:T)->tuple[S,T]:\n",
" return (x,y)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.379606Z",
"start_time": "2023-10-10T20:51:38.175938Z"
}
},
"id": "9ad150634a3ecbcc"
},
{
"cell_type": "code",
"execution_count": 439,
"outputs": [],
"source": [
"from typing import TypeVar\n",
"_S = TypeVar('_S')\n",
"_T = TypeVar('_T')\n",
"def make_2_element_as_tuple(x:_S, y:_T)->tuple[_S,_T]:\n",
" return (x,y)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.611669900Z",
"start_time": "2023-10-10T20:51:38.231917200Z"
}
},
"id": "88161338b3f0b79b"
},
{
"cell_type": "markdown",
"source": [
"## In depth -- Explanation of lambda\n",
"`lambda` are single line and they don't use any indentations.\n",
"it also doesn't have a unique name on each define, it uses <lambda> as `__name__` example of this is:"
],
"metadata": {
"collapsed": false
},
"id": "a9fc05075aee7110"
},
{
"cell_type": "code",
"execution_count": 440,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"cool_name\n",
"<lambda>\n"
]
}
],
"source": [
"def cool_name():\n",
" pass\n",
"print(cool_name.__name__)\n",
"print((lambda:...).__name__)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.686857Z",
"start_time": "2023-10-10T20:51:38.271613300Z"
}
},
"id": "10cc0458698acbd9"
},
{
"cell_type": "markdown",
"source": [
"## In depth -- Generator/Iterator\n",
"Generator/Iterator is a kind of object that works similar to function but don't output the entire list of output at once, Usually used when there will be a list of output. Example:\n",
"\n",
"- `iter(range())` from built-in iterator\n",
"- prime number generator\n",
"\n",
"You can use:\n",
"- `next()` to retrieve the next value or use \n",
"- `for` loop to iterate over all result during running.\n",
"- `list()` to make it feature like normal function then generator/iterator\n",
" (Note that generator/iterator can go infinity long so use of `list()` is not recommended)\n",
"\n",
"Example:"
],
"metadata": {
"collapsed": false
},
"id": "830a37c45de9e436"
},
{
"cell_type": "code",
"execution_count": 441,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n",
"8\n",
"9\n"
]
}
],
"source": [
"for num in iter(range(10)):\n",
" print(num)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.716898700Z",
"start_time": "2023-10-10T20:51:38.343614700Z"
}
},
"id": "7380a17c597d6bd2"
},
{
"cell_type": "code",
"execution_count": 442,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n"
]
}
],
"source": [
"a = iter(range(10))\n",
"print(next(a))\n",
"print(next(a))"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.745892800Z",
"start_time": "2023-10-10T20:51:38.379606Z"
}
},
"id": "b241c51d065dfe76"
},
{
"cell_type": "code",
"execution_count": 443,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
]
}
],
"source": [
"print(list(iter(range(10))))"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.756898800Z",
"start_time": "2023-10-10T20:51:38.437122400Z"
}
},
"id": "ed89be5c32cd3d5f"
},
{
"cell_type": "markdown",
"source": [
"This is helpful because it does not need to wait until all results are generated to do operation, this can help reduce memory usage and stream result output. This will be demonstrated in later example(ref: 1)\n",
"\n",
"A basic generator to generate the power of 2 of the number from 0 to end-1:"
],
"metadata": {
"collapsed": false
},
"id": "ed4770125713d0e"
},
{
"cell_type": "code",
"execution_count": 444,
"outputs": [],
"source": [
"def power_of_2_to(end:int)->list[int]:\n",
" for i in range(end):\n",
" yield i**2"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.759895900Z",
"start_time": "2023-10-10T20:51:38.501669500Z"
}
},
"id": "8c49c3456dc79e3d"
},
{
"cell_type": "markdown",
"source": [
"You can run it by:"
],
"metadata": {
"collapsed": false
},
"id": "d01dd270e84c748e"
},
{
"cell_type": "code",
"execution_count": 445,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"4\n",
"9\n",
"16\n"
]
}
],
"source": [
"for num in power_of_2_to(5):\n",
" print(num)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.764892200Z",
"start_time": "2023-10-10T20:51:38.609671500Z"
}
},
"id": "5056a48ac63e9e01"
},
{
"cell_type": "markdown",
"source": [
"[ref: 1] You can find this through a slight modification from the previous generator demonstration:"
],
"metadata": {
"collapsed": false
},
"id": "d624cfa36a22adaa"
},
{
"cell_type": "code",
"execution_count": 446,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Calculating 0 to the power of 2\n",
"0\n",
"Calculating 1 to the power of 2\n",
"1\n",
"Calculating 2 to the power of 2\n",
"4\n",
"Calculating 3 to the power of 2\n",
"9\n",
"Calculating 4 to the power of 2\n",
"16\n"
]
}
],
"source": [
"def power_of_2_to(end:int)->list[int]:\n",
" for i in range(end):\n",
" print(f\"Calculating {i} to the power of 2\")\n",
" yield i**2\n",
"for num in power_of_2_to(5):\n",
" print(num)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:38.979896800Z",
"start_time": "2023-10-10T20:51:38.638670600Z"
}
},
"id": "f219caf90cdfb525"
},
{
"cell_type": "markdown",
"source": [
"This display that the yield will pause the generator continue until next time the program retrieves the value through for loop or next()\n",
"\n",
"You can also create a one-linear generator by adding a bracket to a `for` loop expression"
],
"metadata": {
"collapsed": false
},
"id": "123f4ab23c07ba94"
},
{
"cell_type": "code",
"execution_count": 447,
"outputs": [],
"source": [
"a = (x**2 for x in range(5))"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-10-10T20:51:39.057896200Z",
"start_time": "2023-10-10T20:51:38.678858800Z"
}
},
"id": "98eb9005ad5b1677"
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
@annguyen2k8
Copy link

thanks your tutorial

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment