diff options
| -rw-r--r-- | tutorials/module_1/control_structures.ipynb | 377 | ||||
| -rw-r--r-- | tutorials/module_1/functions.ipynb | 216 |
2 files changed, 593 insertions, 0 deletions
diff --git a/tutorials/module_1/control_structures.ipynb b/tutorials/module_1/control_structures.ipynb new file mode 100644 index 0000000..4b0f049 --- /dev/null +++ b/tutorials/module_1/control_structures.ipynb @@ -0,0 +1,377 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "3a3edcbf-d972-4802-b3cf-d0e1f502bc83", + "metadata": {}, + "source": [ + "# Control Structures\n", + "\n", + "Control structures allow us to control the flow of execution in a Python\n", + "program. The two main types are **conditional statements (`if`\n", + "statements)** and **loops (`for` and `while` loops)**.\n", + "\n", + "## Conditional Statements\n", + "\n", + "Conditional statements allow a program to execute different blocks of\n", + "code depending on whether a given condition is `True` or `False`. These\n", + "conditions are typically comparisons, such as checking if one number is\n", + "greater than another.\n", + "\n", + "### The `if` Statement\n", + "\n", + "The simplest form of a conditional statement is the `if` statement. If\n", + "the condition evaluates to `True`, the indented block of code runs.\n", + "Otherwise, the program moves on without executing the statement.\n", + "\n", + "For example, consider a situation where we need to determine if a person\n", + "is an adult based on their age. If the age is 18 or greater, we print a\n", + "message saying they are an adult.\n", + "\n", + "### The `if-else` Statement\n", + "\n", + "Sometimes, we need to specify what should happen if the condition is\n", + "`False`. The `else` clause allows us to handle this case. Instead of\n", + "just skipping over the block, the program can execute an alternative\n", + "action.\n", + "\n", + "For instance, if a person is younger than 18, they are considered a\n", + "minor. If the condition of being an adult is not met, the program will\n", + "print a message indicating that the person is a minor.\n", + "\n", + "### The `if-elif-else` Statement\n", + "\n", + "When dealing with multiple conditions, the `if-elif-else` structure is\n", + "useful. The program evaluates conditions in order, executing the first\n", + "one that is `True`. If none of the conditions are met, the `else` block\n", + "runs.\n", + "\n", + "For example, in a grading system, different score ranges correspond to\n", + "different letter grades. If a student’s score is 90 or higher, they\n", + "receive an “A”. If it’s between 80 and 89, they get a “B”, and so on. If\n", + "none of the conditions match, they receive an “F”.\n", + "\n", + "### Nested `if` Statements\n", + "\n", + "Sometimes, we need to check conditions within other conditions. This is\n", + "known as **nesting**. For example, if we first determine that a person\n", + "is an adult, we can then check if they are a student. Based on that\n", + "information, we print different messages." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "0e1ddca8-50e7-42f9-980d-a11553bedd0d", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter the student's score (0-100): 3\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The student has failed.\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Is the student eligible for a retest? (yes/no): no\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The student has failed the course and must retake it next semester.\n" + ] + } + ], + "source": [ + "# Getting user input for the student's score\n", + "score = int(input(\"Enter the student's score (0-100): \"))\n", + "\n", + "if 0 <= score <= 100:\n", + " if score >= 90:\n", + " grade = \"A\"\n", + " elif score >= 80:\n", + " grade = \"B\"\n", + " elif score >= 70:\n", + " grade = \"C\"\n", + " elif score >= 60:\n", + " grade = \"D\"\n", + " else:\n", + " grade = \"F\" # Score below 60 is a failing grade\n", + "\n", + "\n", + " if grade == \"F\":\n", + " print(\"The student has failed.\")\n", + " retake_eligible = input(\"Is the student eligible for a retest? (yes/no): \").strip().lower()\n", + " \n", + " if retake_eligible == \"yes\":\n", + " print(\"The student is eligible for a retest.\")\n", + " else:\n", + " print(\"The student has failed the course and must retake it next semester.\")" + ] + }, + { + "cell_type": "markdown", + "id": "445cdeba-eaa7-4498-b58e-c61d274f6cea", + "metadata": {}, + "source": [ + "## Loops in Python\n", + "\n", + "Loops allow a program to execute a block of code multiple times. This is\n", + "especially useful for tasks such as processing lists of data, performing\n", + "repetitive calculations, or automating tasks.\n", + "\n", + "### The `for` Loop\n", + "\n", + "A `for` loop iterates over a sequence, such as a list, tuple, string, or\n", + "a range of numbers. Each iteration assigns the next value in the\n", + "sequence to a loop variable, which can then be used inside the loop.\n", + "\n", + "For instance, if we have a list of fruits and want to print each fruit’s\n", + "name, a `for` loop can iterate over the list and display each item.\n", + "\n", + "Another useful feature of `for` loops is the `range()` function, which\n", + "generates a sequence of numbers. This is commonly used when we need to\n", + "repeat an action a specific number of times. For example, iterating from\n", + "0 to 4 allows us to print a message five times.\n", + "\n", + "Additionally, the `enumerate()` function can be used to loop through a\n", + "list while keeping track of the index of each item. This is useful when\n", + "both the position and the value in a sequence are needed." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "0247beed-26d2-4e87-b515-acac559414f8", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "apple\n", + "banana\n", + "cherry\n" + ] + } + ], + "source": [ + "fruits = [\"apple\", \"banana\", \"cherry\"] \n", + "for x in fruits: \n", + " print(x)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "5be4f60f-13a1-4721-9290-2d8a1bc70db0", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "Finally finished!\n" + ] + } + ], + "source": [ + "for x in range(6): \n", + " print(x) \n", + "else: \n", + " print(\"Finally finished!\")" + ] + }, + { + "cell_type": "markdown", + "id": "762ddf23-0ecd-491e-93ba-1e861e9e73bf", + "metadata": {}, + "source": [ + "### The `while` Loop\n", + "\n", + "Unlike `for` loops, which iterate over a sequence, `while` loops\n", + "continue running as long as a specified condition remains `True`. This\n", + "is useful when the number of iterations is not known in advance.\n", + "\n", + "For example, a countdown timer can be implemented using a `while` loop.\n", + "The loop will continue decreasing the count until it reaches zero.\n", + "\n", + "It’s important to be careful with `while` loops to avoid infinite loops,\n", + "which occur when the condition never becomes `False`. To prevent this,\n", + "ensure that the condition will eventually change during the execution of\n", + "the loop.\n", + "\n", + "A `while` loop can also be used to wait for a certain event to occur.\n", + "For example, in interactive programs, a `while True` loop can keep\n", + "running until the user provides a valid input, at which point we break\n", + "out of the loop." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "05ef7dd1-e52f-4656-97a3-837e7aa5a9a1", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n", + "5\n" + ] + } + ], + "source": [ + "i = 1 \n", + "while i < 6: \n", + " print(i) \n", + " i += 1" + ] + }, + { + "cell_type": "markdown", + "id": "117cd48e-c944-41f5-aa50-258ff8bf0e1e", + "metadata": {}, + "source": [ + "## Loop Control Statements\n", + "\n", + "Python provides special statements to control the behavior of loops.\n", + "These can be used to break out of a loop, skip certain iterations, or\n", + "simply include a placeholder for future code.\n", + "\n", + "### The `break` Statement\n", + "\n", + "The `break` statement is used to exit a loop before it has iterated\n", + "through all its elements. When the `break` statement is encountered, the\n", + "loop stops immediately, and the program continues executing the next\n", + "statement outside the loop.\n", + "\n", + "For instance, if we are searching for a specific value in a list, we can\n", + "use a `break` statement to stop the loop as soon as we find the item,\n", + "instead of continuing unnecessary iterations.\n", + "\n", + "### The `continue` Statement\n", + "\n", + "The `continue` statement is used to skip the current iteration and\n", + "proceed to the next one. Instead of exiting the loop entirely, it simply\n", + "moves on to the next cycle.\n", + "\n", + "For example, if we are iterating over numbers and want to skip\n", + "processing number 2, we can use `continue`. The loop will ignore that\n", + "iteration and proceed with the next number.\n", + "\n", + "### The `pass` Statement\n", + "\n", + "The `pass` statement is a placeholder that does nothing. It is useful\n", + "when a block of code is syntactically required but no action needs to be\n", + "performed yet.\n", + "\n", + "For example, in a loop where a condition has not yet been implemented,\n", + "using `pass` ensures that the code remains valid while avoiding errors." + ] + }, + { + "cell_type": "markdown", + "id": "1a49130f-d996-4229-914f-7255301d9077", + "metadata": {}, + "source": [ + "# Excercise\n", + "\n", + "So far these examples are quite simple and straightforward. Let's apply this knowledge to programming a CNC \n", + "\n", + "Write a Python program that:\n", + "- Asks the user to input the current temperature of the machine.\n", + "- Uses if/elif/else statements to print the correct system response:\n", + " - If the temperature is below 40°C, print: \"Temperature too low. Warming system activated.\"\n", + " - If the temperature is between 40°C and 85°C, print: \"Temperature is within safe range.\"\n", + " - If the temperature is above 85°C but below 100°C, print: \"Warning: High temperature. Cooling fan activated.\"\n", + " - If the temperature is 100°C or above, print: \"CRITICAL: Shutting down to prevent damage.\"" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "d551eacc-96a9-4c41-90d7-eb1d9da0f87d", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter current temperature in Celsius: 80\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Temperature is within safe range.\n" + ] + } + ], + "source": [ + "# Temperature monitoring system for CNC machine\n", + "\n", + "# Get temperature input from user\n", + "temperature = float(input(\"Enter current temperature in Celsius: \"))\n", + "\n", + "# Check temperature conditions\n", + "if temperature < 40:\n", + " print(\"Temperature too low. Warming system activated.\")\n", + " HEAT = TRUE\n", + "elif 40 <= temperature <= 85:\n", + " print(\"Temperature is within safe range.\")\n", + "elif 85 < temperature < 100:\n", + " print(\"Warning: High temperature. Cooling fan activated.\")\n", + " fan = TRUE\n", + "else: # temperature >= 100\n", + " print(\"CRITICAL: Shutting down to prevent damage.\")\n", + " motor = FALSE\n", + " heat = FALSE\n" + ] + } + ], + "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.13.2" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/tutorials/module_1/functions.ipynb b/tutorials/module_1/functions.ipynb new file mode 100644 index 0000000..6662537 --- /dev/null +++ b/tutorials/module_1/functions.ipynb @@ -0,0 +1,216 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "8e2f3fed-9592-4c3a-a0a3-1d9c8d58244f", + "metadata": {}, + "source": [ + "# Functions\n", + "\n", + "Like a traditional mathematical functions, python functions can take an\n", + "input, process it, and give an output. In python, the input variables\n", + "are referred to as *arguments*. Functions are blocks of code that is run\n", + "every time it’s called. This allows us to re-use code.\n", + "\n", + "Functions are defined by using the <code> def </code> keyword. Reminder:\n", + "it is important to keep track of indentations as it signifies the end of\n", + "the function when the indentation returns back to the same level.\n", + "\n", + "## Defining Functions\n", + "\n", + "### Simple function\n", + "\n", + "A simple function with no input variable can be useful if you need to\n", + "re-use code multiple times without having to re-write it." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "b673514c-db14-4da7-8f6a-65402b27c3c6", + "metadata": {}, + "outputs": [], + "source": [ + "def function_name():\n", + " print(\"This is from a function\")" + ] + }, + { + "cell_type": "markdown", + "id": "b7cca02d-2d53-4acd-ada5-cb8221008b52", + "metadata": {}, + "source": [ + "### Defining a function with one input\n", + "We can pass variables through to the function to be processed as\n", + "follows:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "89f84f81-461a-42e3-9e7a-a6be2ac8c4d7", + "metadata": {}, + "outputs": [], + "source": [ + "def function(x):\n", + " print(x + \" is best\")" + ] + }, + { + "cell_type": "markdown", + "id": "0d0d30cb-83d1-438f-85b0-c5e3e49eff29", + "metadata": {}, + "source": [ + "Note input variables can be of any data type (integer, float, string,\n", + "etc.). \n", + "\n", + "### Returning values from a function If we want to calculate a\n", + "value and pass it back to the script for further use, we can use the\n", + "`return` keyword. Let’s define a linear function that takes two inputs,\n", + "`x` and `b`, computes the corresponding `y` value, and returns it so it\n", + "can be used elsewhere in the code." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "5f2ff033-050c-4939-bab4-f55ec0de688b", + "metadata": {}, + "outputs": [], + "source": [ + "def function(x, b):\n", + " y = 3*x+b\n", + " return y" + ] + }, + { + "cell_type": "markdown", + "id": "a2ad94cf-6e16-4186-874c-972d6932858a", + "metadata": {}, + "source": [ + "For multiple output variables we can add \n", + "\n", + "## Calling functions Now that\n", + "we’ve covered defining functions we want to call the function in order\n", + "to execute the block inside the function. To do this, we simply re-call\n", + "the function name as follows." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "4bff7ef2-630f-43d3-b54a-cc8214aa7034", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "function(2,-1)" + ] + }, + { + "cell_type": "markdown", + "id": "caeeca6c-3442-4785-9d54-e39801ee3cf6", + "metadata": {}, + "source": [ + "Note that when running this code, nothing happens. This is because we\n", + "haven’t told the computer what to do with the output. Hence, if we wish\n", + "to store the output then we need to use the assign operator `=`." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "b47437eb-050d-481e-a72b-201a7703b193", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5\n" + ] + } + ], + "source": [ + "output = function(2,-1)\n", + "\n", + "print(output)" + ] + }, + { + "cell_type": "markdown", + "id": "8cd86a50-5dc6-42df-b651-a147b445cb57", + "metadata": {}, + "source": [ + "In case you want to return multiple output variable from a single\n", + "function we will have…\n", + "\n", + "## Summary" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "d22da5ff-85ee-4658-a959-1a2b5df6eb9a", + "metadata": {}, + "outputs": [], + "source": [ + "def function_name(argument1, argument2, argument3):\n", + " output1 = argument1 * argument2 - argument3\n", + " output2 = argument2 + argument3\n", + " return output1, output2\n", + "\n", + "[solution1, solution2] = function_name(1,2,3)" + ] + }, + { + "cell_type": "markdown", + "id": "bd984f25-729f-437c-8df4-0feb75aa7ed8", + "metadata": {}, + "source": [ + "- `def` - defines a function. All the code that is indented underneath\n", + " is considered inside the function block.\n", + "- `function_name` - this is used to call the function block.\n", + "- `argument1` (optional) - input variable. This is data that can be\n", + " pass to the function. It is possible to have multiple variables\n", + " separated by a comma. As well as can be omitted if the function\n", + " should just give you an output such as.\n", + "- `return` (optional) - if you wish to return something to your\n", + " script, the return keyword is used. The keyword can be followed by\n", + " an output variable or a constant. For multiple output variables,\n", + " separate them by a comma." + ] + } + ], + "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.13.2" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} |
